llvm-project
69 строк · 2.5 Кб
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() {31LLVMContext Context;32
33// Create the "module" or "program" or "translation unit" to hold the34// function35Module *M = new Module("test", Context);36
37// Create the main function: first create the type 'int ()'38FunctionType *FT =39FunctionType::get(Type::getInt32Ty(Context), /*not vararg*/false);40
41// By passing a module as the last parameter to the Function constructor,42// it automatically gets appended to the Module.43Function *F = Function::Create(FT, Function::ExternalLinkage, "main", M);44
45// Add a basic block to the function... again, it automatically inserts46// because of the last argument.47BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", F);48
49// Get pointers to the constant integers...50Value *Two = ConstantInt::get(Type::getInt32Ty(Context), 2);51Value *Three = ConstantInt::get(Type::getInt32Ty(Context), 3);52
53// Create the add instruction... does not insert...54Instruction *Add = BinaryOperator::Create(Instruction::Add, Two, Three,55"addresult");56
57// explicitly insert it into the basic block...58Add->insertInto(BB, BB->end());59
60// Create the return instruction and add it to the basic block61ReturnInst::Create(Context, Add)->insertInto(BB, BB->end());62
63// Output the bitcode file to stdout64WriteBitcodeToFile(*M, outs());65
66// Delete the module and all of its contents.67delete M;68return 0;69}
70