ModuleMaker.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. #include "llvm/Bitcode/BitcodeWriter.h"
  15. #include "llvm/IR/BasicBlock.h"
  16. #include "llvm/IR/Constants.h"
  17. #include "llvm/IR/DerivedTypes.h"
  18. #include "llvm/IR/Function.h"
  19. #include "llvm/IR/InstrTypes.h"
  20. #include "llvm/IR/Instruction.h"
  21. #include "llvm/IR/Instructions.h"
  22. #include "llvm/IR/LLVMContext.h"
  23. #include "llvm/IR/Module.h"
  24. #include "llvm/IR/Type.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. using namespace llvm;
  27. int main() {
  28. LLVMContext Context;
  29. // Create the "module" or "program" or "translation unit" to hold the
  30. // function
  31. Module *M = new Module("test", Context);
  32. // Create the main function: first create the type 'int ()'
  33. FunctionType *FT =
  34. FunctionType::get(Type::getInt32Ty(Context), /*not vararg*/false);
  35. // By passing a module as the last parameter to the Function constructor,
  36. // it automatically gets appended to the Module.
  37. Function *F = Function::Create(FT, Function::ExternalLinkage, "main", M);
  38. // Add a basic block to the function... again, it automatically inserts
  39. // because of the last argument.
  40. BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", F);
  41. // Get pointers to the constant integers...
  42. Value *Two = ConstantInt::get(Type::getInt32Ty(Context), 2);
  43. Value *Three = ConstantInt::get(Type::getInt32Ty(Context), 3);
  44. // Create the add instruction... does not insert...
  45. Instruction *Add = BinaryOperator::Create(Instruction::Add, Two, Three,
  46. "addresult");
  47. // explicitly insert it into the basic block...
  48. BB->getInstList().push_back(Add);
  49. // Create the return instruction and add it to the basic block
  50. BB->getInstList().push_back(ReturnInst::Create(Context, Add));
  51. // Output the bitcode file to stdout
  52. WriteBitcodeToFile(*M, outs());
  53. // Delete the module and all of its contents.
  54. delete M;
  55. return 0;
  56. }