xref: /llvm-project/llvm/examples/ModuleMaker/ModuleMaker.cpp (revision 5b81eea7a5da840b23e9183f3f5c0eae78f64bd7)
1 //===- ModuleMaker.cpp - Example project which creates modules --*- C++ -*-===//
2 //
3 // This programs is a simple example that creates an LLVM module "from scratch",
4 // emitting it as a bytecode file to standard out.  This is just to show how
5 // LLVM projects work and to demonstrate some of the LLVM APIs.
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/Module.h"
10 #include "llvm/DerivedTypes.h"
11 #include "llvm/Constants.h"
12 #include "llvm/Instructions.h"
13 #include "llvm/Bytecode/Writer.h"
14 #include <iostream>
15 
16 using namespace llvm;
17 
18 int main() {
19   // Create the "module" or "program" or "translation unit" to hold the
20   // function
21   Module *M = new Module("test");
22 
23   // Create the main function: first create the type 'int ()'
24   FunctionType *FT = FunctionType::get(Type::IntTy, std::vector<const Type*>(),
25                                        /*not vararg*/false);
26 
27   // By passing a module as the last parameter to the Function constructor,
28   // it automatically gets appended to the Module.
29   Function *F = new Function(FT, Function::ExternalLinkage, "main", M);
30 
31   // Add a basic block to the function... again, it automatically inserts
32   // because of the last argument.
33   BasicBlock *BB = new BasicBlock("EntryBlock", F);
34 
35   // Get pointers to the constant integers...
36   Value *Two = ConstantSInt::get(Type::IntTy, 2);
37   Value *Three = ConstantSInt::get(Type::IntTy, 3);
38 
39   // Create the add instruction... does not insert...
40   Instruction *Add = BinaryOperator::create(Instruction::Add, Two, Three,
41                                             "addresult");
42 
43   // explicitly insert it into the basic block...
44   BB->getInstList().push_back(Add);
45 
46   // Create the return instruction and add it to the basic block
47   BB->getInstList().push_back(new ReturnInst(Add));
48 
49   // Output the bytecode file to stdout
50   WriteBytecodeToFile(M, std::cout);
51 
52   // Delete the module and all of its contents.
53   delete M;
54   return 0;
55 }
56