1 //===- examples/ModuleMaker/ModuleMaker.cpp - Example project ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This programs is a simple example that creates an LLVM module "from scratch",
11 // emitting it as a bitcode file to standard out. This is just to show how
12 // LLVM projects work and to demonstrate some of the LLVM APIs.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/LLVMContext.h"
17 #include "llvm/Module.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Bitcode/ReaderWriter.h"
22 #include "llvm/Support/raw_ostream.h"
28 // Create the "module" or "program" or "translation unit" to hold the
30 Module *M = new Module("test", Context);
32 // Create the main function: first create the type 'int ()'
34 FunctionType::get(Type::getInt32Ty(Context), /*not vararg*/false);
36 // By passing a module as the last parameter to the Function constructor,
37 // it automatically gets appended to the Module.
38 Function *F = Function::Create(FT, Function::ExternalLinkage, "main", M);
40 // Add a basic block to the function... again, it automatically inserts
41 // because of the last argument.
42 BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", F);
44 // Get pointers to the constant integers...
45 Value *Two = ConstantInt::get(Type::getInt32Ty(Context), 2);
46 Value *Three = ConstantInt::get(Type::getInt32Ty(Context), 3);
48 // Create the add instruction... does not insert...
49 Instruction *Add = BinaryOperator::Create(Instruction::Add, Two, Three,
52 // explicitly insert it into the basic block...
53 BB->getInstList().push_back(Add);
55 // Create the return instruction and add it to the basic block
56 BB->getInstList().push_back(ReturnInst::Create(Context, Add));
58 // Output the bitcode file to stdout
59 WriteBitcodeToFile(M, outs());
61 // Delete the module and all of its contents.