1//===- examples/ModuleMaker/ModuleMaker.cpp - Example project ---*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This programs is a simple example that creates an LLVM module "from scratch",
10// emitting it as a bitcode file to standard out. This is just to show how
11// LLVM projects work and to demonstrate some of the LLVM APIs.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Bitcode/BitcodeWriter.h"
16#include "llvm/IR/BasicBlock.h"
17#include "llvm/IR/Constants.h"
18#include "llvm/IR/DerivedTypes.h"
19#include "llvm/IR/Function.h"
20#include "llvm/IR/InstrTypes.h"
21#include "llvm/IR/Instruction.h"
22#include "llvm/IR/Instructions.h"
23#include "llvm/IR/LLVMContext.h"
24#include "llvm/IR/Module.h"
25#include "llvm/IR/Type.h"
26#include "llvm/Support/raw_ostream.h"
27
28using namespace llvm;
29
30int main() {
31 LLVMContext Context;
32
33 // Create the "module" or "program" or "translation unit" to hold the
34 // function
35 Module *M = new Module("test", Context);
36
37 // Create the main function: first create the type 'int ()'
38 FunctionType *FT =
39 FunctionType::get(Result: Type::getInt32Ty(C&: Context), /*not vararg*/isVarArg: false);
40
41 // By passing a module as the last parameter to the Function constructor,
42 // it automatically gets appended to the Module.
43 Function *F = Function::Create(Ty: FT, Linkage: Function::ExternalLinkage, N: "main", M);
44
45 // Add a basic block to the function... again, it automatically inserts
46 // because of the last argument.
47 BasicBlock *BB = BasicBlock::Create(Context, Name: "EntryBlock", Parent: F);
48
49 // Get pointers to the constant integers...
50 Value *Two = ConstantInt::get(Ty: Type::getInt32Ty(C&: Context), V: 2);
51 Value *Three = ConstantInt::get(Ty: Type::getInt32Ty(C&: Context), V: 3);
52
53 // Create the add instruction... does not insert...
54 Instruction *Add = BinaryOperator::Create(Op: Instruction::Add, S1: Two, S2: Three,
55 Name: "addresult");
56
57 // explicitly insert it into the basic block...
58 Add->insertInto(ParentBB: BB, It: BB->end());
59
60 // Create the return instruction and add it to the basic block
61 ReturnInst::Create(C&: Context, retVal: Add)->insertInto(ParentBB: BB, It: BB->end());
62
63 // Output the bitcode file to stdout
64 WriteBitcodeToFile(M: *M, Out&: outs());
65
66 // Delete the module and all of its contents.
67 delete M;
68 return 0;
69}
70

source code of llvm/examples/ModuleMaker/ModuleMaker.cpp