Reid Spencer | 66e7cd0 | 2004-09-11 20:30:11 +0000 | [diff] [blame^] | 1 | //===- examples/ModuleMaker/ModuleMaker.cpp - Example project ---*- C++ -*-===// |
Chris Lattner | 8ca0eeb | 2003-08-21 22:29:52 +0000 | [diff] [blame] | 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" |
Reid Spencer | 321f831 | 2004-07-04 12:22:14 +0000 | [diff] [blame] | 14 | #include <iostream> |
Chris Lattner | 8ca0eeb | 2003-08-21 22:29:52 +0000 | [diff] [blame] | 15 | |
Brian Gaeke | d0fde30 | 2003-11-11 22:41:34 +0000 | [diff] [blame] | 16 | using namespace llvm; |
| 17 | |
Chris Lattner | 8ca0eeb | 2003-08-21 22:29:52 +0000 | [diff] [blame] | 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 | } |