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