Skip to content

Instantly share code, notes, and snippets.

@wreulicke
Last active January 8, 2018 17:37
Show Gist options
  • Save wreulicke/dd387c40d335f66514782bc69926b9c4 to your computer and use it in GitHub Desktop.
Save wreulicke/dd387c40d335f66514782bc69926b9c4 to your computer and use it in GitHub Desktop.
LLVMのメモ
#include <iostream>
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
int main()
{
llvm::LLVMContext context;
llvm::IRBuilder<> builder(context);
std::unique_ptr<llvm::Module> module =
llvm::make_unique<llvm::Module>("top", context);
llvm::FunctionType *funcType = llvm::FunctionType::get(builder.getVoidTy(), false);
llvm::Function *mainFunc =
llvm::Function::Create(funcType, llvm::Function::ExternalLinkage, "main", module.get());
llvm::BasicBlock *entry = llvm::BasicBlock::Create(context, "entrypoint", mainFunc);
builder.SetInsertPoint(entry);
llvm::Value *hello = builder.CreateGlobalStringPtr("Hello %s\n");
llvm::Value *john = builder.CreateGlobalStringPtr("John");
std::vector<llvm::Type *> putsArgs;
putsArgs.push_back(builder.getInt8Ty()->getPointerTo());
llvm::ArrayRef<llvm::Type *> argsRef(putsArgs);
llvm::FunctionType *putsType =
// 可変長引数なので trueにした
llvm::FunctionType::get(builder.getInt32Ty(), argsRef, true);
llvm::Constant *putsFunc = module->getOrInsertFunction("printf", putsType);
std::vector<llvm::Value *> args;
args.push_back(hello);
args.push_back(john);
llvm::ArrayRef<llvm::Value *> argumentsRef(args);
builder.CreateCall(putsFunc, argumentsRef);
builder.CreateRetVoid();
module->print(llvm::outs(), nullptr);
return 0;
}

llvmのインストール

とりあえず今回はお試しで、OSXから

brew install --with-toolchain llvm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment