2

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++?

6
  • Have you looked at the JITEngine? checkout llvm's kaleidoscope tutorial. The tutorial you're onto is outdated. Commented May 30, 2020 at 7:04
  • @droptop, at Kaleidoscope, I cannot spot it. Can you please help me finding the point? Commented May 30, 2020 at 9:46
  • @ar2015 llvm.org/docs/tutorial/BuildingAJIT1.html Commented May 30, 2020 at 9: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. Commented May 30, 2020 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? Commented May 30, 2020 at 11:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.