1

I have get an example llvm code from here. This code has some problems that I fixed them too. At this point, all it does is to dump the translated IR code. What I am after is to create an executable from my C++ code without calling llvm-as/llc/clang in my bash. How can I achieve that?

I do not want to create any IR or bytecode intermediate file at all too.

#include <llvm/ADT/ArrayRef.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/IRBuilder.h>
#include <vector>
#include <string>

int main()
{
    llvm::LLVMContext context;
    llvm::Module *module = new llvm::Module("myModule", context);
    llvm::IRBuilder<> builder(context);

    llvm::FunctionType *funcType = llvm::FunctionType::get(builder.getVoidTy(), false);
    llvm::Function *mainFunc = 
        llvm::Function::Create(funcType, llvm::Function::ExternalLinkage, "main", module);
    llvm::BasicBlock *entry = llvm::BasicBlock::Create(context, "entrypoint", mainFunc);
    builder.SetInsertPoint(entry);

    llvm::Value *helloWorld = builder.CreateGlobalStringPtr("hello world!\n");

    std::vector<llvm::Type *> putsArgs;
    putsArgs.push_back(builder.getInt8Ty()->getPointerTo());
    llvm::ArrayRef<llvm::Type*>  argsRef(putsArgs);

    llvm::FunctionType *putsType = 
        llvm::FunctionType::get(builder.getInt32Ty(), argsRef, false);
    llvm::FunctionCallee putsFunc = module->getOrInsertFunction("puts", putsType);

    builder.CreateCall(putsFunc, helloWorld);
    builder.CreateRetVoid();
    module->print(llvm::errs(), nullptr);
}

A side question: BTW, when I am searching for LLVM examples, a lot of results are IR examples. How can I get the results to teach creating from C++?

ar2015
  • 5,558
  • 8
  • 53
  • 110
  • Have you looked at the `JITEngine`? checkout llvm's kaleidoscope tutorial. The tutorial you're onto is outdated. – droptop May 30 '20 at 07:04
  • @droptop, at [Kaleidoscope](https://github.com/keyboardio/Kaleidoscope), I cannot spot it. Can you please help me finding the point? – ar2015 May 30 '20 at 09:46
  • @ar2015 https://llvm.org/docs/tutorial/BuildingAJIT1.html – droptop May 30 '20 at 09:48
  • @droptop , I don't feel comfortable about llvm documentation. It looks like they are reluctant to write a proper tutorial: `Example code from Chapters 3 to 5 will compile and run, but has not been updated`. I also do not look after JIT. I want a natural compilation. – ar2015 May 30 '20 at 10:10
  • @droptop, just now someone told me that I cannot do this. I need to dump it to an object file first then creating an executable out of it. Is this true? – ar2015 May 30 '20 at 11:03
  • @ar2015 Yup. There's no escaping object files if you want to create an executable. You however just interpret your generated IR using `lli`, which of course doesn't create an executable. – droptop May 30 '20 at 11:40

0 Answers0