Ast.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. // LLVM includes
  2. #include "llvm/IR/Verifier.h"
  3. // Local includes
  4. #include "Ast.h"
  5. #include "Parser.h"
  6. #include "JIT.h"
  7. using namespace jit;
  8. namespace ast{
  9. // attributes added from chapter 3 of the tutorial
  10. std::unique_ptr<Module> AstObjects::TheModule =
  11. std::make_unique<Module>("my cool jit", getGlobalContext());
  12. IRBuilder<> AstObjects::Builder(getGlobalContext());
  13. std::map<std::string, AllocaInst*> AstObjects::NamedValues;
  14. Value *ErrorV(const char *Str) {
  15. parser::Error(Str);
  16. return nullptr;
  17. }
  18. Value *NumberExprAST::codegen() {
  19. return ConstantFP::get(getGlobalContext(), APFloat(Val));
  20. }
  21. Value *VariableExprAST::codegen() {
  22. // Look this variable up in the function.
  23. Value *V = AstObjects::NamedValues[Name];
  24. if (!V)
  25. return ErrorV("Unknown variable name");
  26. // Load the value.
  27. return AstObjects::Builder.CreateLoad(V, Name.c_str());
  28. }
  29. Value *UnaryExprAST::codegen() {
  30. Value *OperandV = Operand->codegen();
  31. if (!OperandV)
  32. return nullptr;
  33. Function *F = getFunction(std::string("unary") + Opcode);
  34. if (!F)
  35. return ErrorV("Unknown unary operator");
  36. return AstObjects::Builder.CreateCall(F, OperandV, "unop");
  37. }
  38. Value *BinaryExprAST::codegen() {
  39. // Special case '=' because we don't want to emit the LHS as an expression.
  40. if (Op == '=') {
  41. // Assignment requires the LHS to be an identifier.
  42. // This assume we're building without RTTI because LLVM builds that way by
  43. // default. If you build LLVM with RTTI this can be changed to a
  44. // dynamic_cast for automatic error checking.
  45. VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS.get());
  46. if (!LHSE)
  47. return ErrorV("destination of '=' must be a variable");
  48. // Codegen the RHS.
  49. Value *Val = RHS->codegen();
  50. if (!Val)
  51. return nullptr;
  52. // Look up the name.
  53. Value *Variable = AstObjects::NamedValues[LHSE->getName()];
  54. if (!Variable)
  55. return ErrorV("Unknown variable name");
  56. AstObjects::Builder.CreateStore(Val, Variable);
  57. return Val;
  58. }
  59. Value *L = LHS->codegen();
  60. Value *R = RHS->codegen();
  61. if (!L || !R)
  62. return nullptr;
  63. switch (Op) {
  64. case '+':
  65. return AstObjects::Builder.CreateFAdd(L, R, "addtmp");
  66. case '-':
  67. return AstObjects::Builder.CreateFSub(L, R, "subtmp");
  68. case '*':
  69. return AstObjects::Builder.CreateFMul(L, R, "multmp");
  70. case '<':
  71. L = AstObjects::Builder.CreateFCmpULT(L, R, "cmptmp");
  72. // Convert bool 0/1 to double 0.0 or 1.0
  73. return AstObjects::Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
  74. "booltmp");
  75. default:
  76. break;
  77. }
  78. // If it wasn't a builtin binary operator, it must be a user defined one. Emit
  79. // a call to it.
  80. Function *F = getFunction(std::string("binary") + Op);
  81. assert(F && "binary operator not found!");
  82. Value *Ops[] = {L, R};
  83. return AstObjects::Builder.CreateCall(F, Ops, "binop");
  84. }
  85. Value *CallExprAST::codegen() {
  86. // Look up the name in the global module table.
  87. Function *CalleeF = getFunction(Callee);
  88. if (!CalleeF)
  89. return ErrorV("Unknown function referenced");
  90. // If argument mismatch error.
  91. if (CalleeF->arg_size() != Args.size())
  92. return ErrorV("Incorrect # arguments passed");
  93. std::vector<Value *> ArgsV;
  94. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  95. ArgsV.push_back(Args[i]->codegen());
  96. if (!ArgsV.back())
  97. return nullptr;
  98. }
  99. return AstObjects::Builder.CreateCall(CalleeF, ArgsV, "calltmp");
  100. }
  101. Value *IfExprAST::codegen() {
  102. Value *CondV = Cond->codegen();
  103. if (!CondV)
  104. return nullptr;
  105. // Convert condition to a bool by comparing equal to 0.0.
  106. CondV = AstObjects::Builder.CreateFCmpONE(
  107. CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
  108. Function *TheFunction = AstObjects::Builder.GetInsertBlock()->getParent();
  109. // Create blocks for the then and else cases. Insert the 'then' block at the
  110. // end of the function.
  111. BasicBlock *ThenBB =
  112. BasicBlock::Create(getGlobalContext(), "then", TheFunction);
  113. BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
  114. BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
  115. AstObjects::Builder.CreateCondBr(CondV, ThenBB, ElseBB);
  116. // Emit then value.
  117. AstObjects::Builder.SetInsertPoint(ThenBB);
  118. Value *ThenV = Then->codegen();
  119. if (!ThenV)
  120. return nullptr;
  121. AstObjects::Builder.CreateBr(MergeBB);
  122. // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
  123. ThenBB = AstObjects::Builder.GetInsertBlock();
  124. // Emit else block.
  125. TheFunction->getBasicBlockList().push_back(ElseBB);
  126. AstObjects::Builder.SetInsertPoint(ElseBB);
  127. Value *ElseV = Else->codegen();
  128. if (!ElseV)
  129. return nullptr;
  130. AstObjects::Builder.CreateBr(MergeBB);
  131. // codegen of 'Else' can change the current block, update ElseBB for the PHI.
  132. ElseBB = AstObjects::Builder.GetInsertBlock();
  133. // Emit merge block.
  134. TheFunction->getBasicBlockList().push_back(MergeBB);
  135. AstObjects::Builder.SetInsertPoint(MergeBB);
  136. PHINode *PN =
  137. AstObjects::Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
  138. PN->addIncoming(ThenV, ThenBB);
  139. PN->addIncoming(ElseV, ElseBB);
  140. return PN;
  141. }
  142. // Output for-loop as:
  143. // var = alloca double
  144. // ...
  145. // start = startexpr
  146. // store start -> var
  147. // goto loop
  148. // loop:
  149. // ...
  150. // bodyexpr
  151. // ...
  152. // loopend:
  153. // step = stepexpr
  154. // endcond = endexpr
  155. //
  156. // curvar = load var
  157. // nextvar = curvar + step
  158. // store nextvar -> var
  159. // br endcond, loop, endloop
  160. // outloop:
  161. Value *ForExprAST::codegen() {
  162. Function *TheFunction = AstObjects::Builder.GetInsertBlock()->getParent();
  163. // Create an alloca for the variable in the entry block.
  164. AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
  165. // Emit the start code first, without 'variable' in scope.
  166. Value *StartVal = Start->codegen();
  167. if (!StartVal)
  168. return nullptr;
  169. // Store the value into the alloca.
  170. AstObjects::Builder.CreateStore(StartVal, Alloca);
  171. // Make the new basic block for the loop header, inserting after current
  172. // block.
  173. BasicBlock *LoopBB =
  174. BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
  175. // Insert an explicit fall through from the current block to the LoopBB.
  176. AstObjects::Builder.CreateBr(LoopBB);
  177. // Start insertion in LoopBB.
  178. AstObjects::Builder.SetInsertPoint(LoopBB);
  179. // Within the loop, the variable is defined equal to the PHI node. If it
  180. // shadows an existing variable, we have to restore it, so save it now.
  181. AllocaInst *OldVal = AstObjects::NamedValues[VarName];
  182. AstObjects::NamedValues[VarName] = Alloca;
  183. // Emit the body of the loop. This, like any other expr, can change the
  184. // current BB. Note that we ignore the value computed by the body, but don't
  185. // allow an error.
  186. if (!Body->codegen())
  187. return nullptr;
  188. // Emit the step value.
  189. Value *StepVal = nullptr;
  190. if (Step) {
  191. StepVal = Step->codegen();
  192. if (!StepVal)
  193. return nullptr;
  194. } else {
  195. // If not specified, use 1.0.
  196. StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
  197. }
  198. // Compute the end condition.
  199. Value *EndCond = End->codegen();
  200. if (!EndCond)
  201. return nullptr;
  202. // Reload, increment, and restore the alloca. This handles the case where
  203. // the body of the loop mutates the variable.
  204. Value *CurVar = AstObjects::Builder.CreateLoad(Alloca, VarName.c_str());
  205. Value *NextVar = AstObjects::Builder.CreateFAdd(CurVar, StepVal, "nextvar");
  206. AstObjects::Builder.CreateStore(NextVar, Alloca);
  207. // Convert condition to a bool by comparing equal to 0.0.
  208. EndCond = AstObjects::Builder.CreateFCmpONE(
  209. EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
  210. // Create the "after loop" block and insert it.
  211. BasicBlock *AfterBB =
  212. BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
  213. // Insert the conditional branch into the end of LoopEndBB.
  214. AstObjects::Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
  215. // Any new code will be inserted in AfterBB.
  216. AstObjects::Builder.SetInsertPoint(AfterBB);
  217. // Restore the unshadowed variable.
  218. if (OldVal)
  219. AstObjects::NamedValues[VarName] = OldVal;
  220. else
  221. AstObjects::NamedValues.erase(VarName);
  222. // for expr always returns 0.0.
  223. return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
  224. }
  225. Value *VarExprAST::codegen() {
  226. std::vector<AllocaInst *> OldBindings;
  227. Function *TheFunction = AstObjects::Builder.GetInsertBlock()->getParent();
  228. // Register all variables and emit their initializer.
  229. for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
  230. const std::string &VarName = VarNames[i].first;
  231. ExprAST *Init = VarNames[i].second.get();
  232. // Emit the initializer before adding the variable to scope, this prevents
  233. // the initializer from referencing the variable itself, and permits stuff
  234. // like this:
  235. // var a = 1 in
  236. // var a = a in ... # refers to outer 'a'.
  237. Value *InitVal;
  238. if (Init) {
  239. InitVal = Init->codegen();
  240. if (!InitVal)
  241. return nullptr;
  242. } else { // If not specified, use 0.0.
  243. InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
  244. }
  245. AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
  246. AstObjects::Builder.CreateStore(InitVal, Alloca);
  247. // Remember the old variable binding so that we can restore the binding when
  248. // we unrecurse.
  249. OldBindings.push_back(AstObjects::NamedValues[VarName]);
  250. // Remember this binding.
  251. AstObjects::NamedValues[VarName] = Alloca;
  252. }
  253. // Codegen the body, now that all vars are in scope.
  254. Value *BodyVal = Body->codegen();
  255. if (!BodyVal)
  256. return nullptr;
  257. // Pop all our variables from scope.
  258. for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
  259. AstObjects::NamedValues[VarNames[i].first] = OldBindings[i];
  260. // Return the body computation.
  261. return BodyVal;
  262. }
  263. Function *PrototypeAST::codegen() {
  264. // Make the function type: double(double,double) etc.
  265. std::vector<Type *> Doubles(Args.size(),
  266. Type::getDoubleTy(getGlobalContext()));
  267. FunctionType *FT = FunctionType::get(Type::getDoubleTy(
  268. getGlobalContext()), Doubles, false);
  269. Function *F = Function::Create(FT, Function::ExternalLinkage, Name,
  270. AstObjects::TheModule.get());
  271. // Set names for all arguments.
  272. unsigned Idx = 0;
  273. for (auto &Arg : F->args())
  274. Arg.setName(Args[Idx++]);
  275. return F;
  276. }
  277. Function *FunctionAST::codegen() {
  278. // Transfer ownership of the prototype to the FunctionProtos map, but keep a
  279. // reference to it for use below.
  280. auto &P = *Proto;
  281. JITObjects::FunctionProtos[Proto->getName()] = std::move(Proto);
  282. Function *TheFunction = getFunction(P.getName());
  283. if (!TheFunction)
  284. return nullptr;
  285. // If this is an operator, install it.
  286. if (P.isBinaryOp())
  287. parser::BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
  288. // Create a new basic block to start insertion into.
  289. BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
  290. AstObjects::Builder.SetInsertPoint(BB);
  291. // Record the function arguments in the NamedValues map.
  292. AstObjects::NamedValues.clear();
  293. for (auto &Arg : TheFunction->args()) {
  294. // Create an alloca for this variable.
  295. AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
  296. // Store the initial value into the alloca.
  297. AstObjects::Builder.CreateStore(&Arg, Alloca);
  298. // Add arguments to variable symbol table.
  299. AstObjects::NamedValues[Arg.getName()] = Alloca;
  300. }
  301. if (Value *RetVal = Body->codegen()) {
  302. // Finish off the function.
  303. AstObjects::Builder.CreateRet(RetVal);
  304. // Validate the generated code, checking for consistency.
  305. verifyFunction(*TheFunction);
  306. // Run the optimizer on the function.
  307. JITObjects::TheFPM->run(*TheFunction);
  308. return TheFunction;
  309. }
  310. // Error reading body, remove function.
  311. TheFunction->eraseFromParent();
  312. if (P.isBinaryOp())
  313. parser::BinopPrecedence.erase(Proto->getOperatorName());
  314. return nullptr;
  315. }
  316. /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
  317. /// the function. This is used for mutable variables etc.
  318. static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
  319. const std::string &VarName) {
  320. IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
  321. TheFunction->getEntryBlock().begin());
  322. return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), nullptr,
  323. VarName.c_str());
  324. }
  325. /*
  326. /// CreateArgumentAllocas - Create an alloca for each argument and register the
  327. /// argument in the symbol table so that references to it will succeed.
  328. void PrototypeAST::CreateArgumentAllocas(Function *F) {
  329. Function::arg_iterator AI = F->arg_begin();
  330. for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
  331. // Create an alloca for this variable.
  332. AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
  333. // Store the initial value into the alloca.
  334. AstObjects::Builder.CreateStore(AI, Alloca);
  335. // Add arguments to variable symbol table.
  336. AstObjects::NamedValues[Args[Idx]] = Alloca;
  337. }
  338. }*/
  339. }