ModuleMaker.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //===- examples/ModuleMaker/ModuleMaker.cpp - Example project ---*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  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.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Bitcode/ReaderWriter.h"
  16. #include "llvm/IR/Constants.h"
  17. #include "llvm/IR/DerivedTypes.h"
  18. #include "llvm/IR/Instructions.h"
  19. #include "llvm/IR/LLVMContext.h"
  20. #include "llvm/IR/Module.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. using namespace llvm;
  23. int main() {
  24. LLVMContext Context;
  25. // Create the "module" or "program" or "translation unit" to hold the
  26. // function
  27. Module *M = new Module("test", Context);
  28. // Create the main function: first create the type 'int ()'
  29. FunctionType *FT =
  30. FunctionType::get(Type::getInt32Ty(Context), /*not vararg*/false);
  31. // By passing a module as the last parameter to the Function constructor,
  32. // it automatically gets appended to the Module.
  33. Function *F = Function::Create(FT, Function::ExternalLinkage, "main", M);
  34. // Add a basic block to the function... again, it automatically inserts
  35. // because of the last argument.
  36. BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", F);
  37. // Get pointers to the constant integers...
  38. Value *Two = ConstantInt::get(Type::getInt32Ty(Context), 2);
  39. Value *Three = ConstantInt::get(Type::getInt32Ty(Context), 3);
  40. // Create the add instruction... does not insert...
  41. Instruction *Add = BinaryOperator::Create(Instruction::Add, Two, Three,
  42. "addresult");
  43. // explicitly insert it into the basic block...
  44. BB->getInstList().push_back(Add);
  45. // Create the return instruction and add it to the basic block
  46. BB->getInstList().push_back(ReturnInst::Create(Context, Add));
  47. // Output the bitcode file to stdout
  48. WriteBitcodeToFile(M, outs());
  49. // Delete the module and all of its contents.
  50. delete M;
  51. return 0;
  52. }