llvm.org GIT mirror llvm / fc85502
Remove trailing whitespace from the old Orc Kaleidoscope examples. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@247971 91177308-0d34-0410-b5e6-96231b3b80d8 Lang Hames 4 years ago
4 changed file(s) with 444 addition(s) and 448 deletion(s). Raw diff Collapse all Expand all
3838
3939 // primary
4040 tok_identifier = -4, tok_number = -5,
41
41
4242 // control
4343 tok_if = -6, tok_then = -7, tok_else = -8,
4444 tok_for = -9, tok_in = -10,
45
45
4646 // operators
4747 tok_binary = -11, tok_unary = -12,
48
48
4949 // var definition
5050 tok_var = -13
5151 };
9494 // Comment until end of line.
9595 do LastChar = getchar();
9696 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
97
97
9898 if (LastChar != EOF)
9999 return gettok();
100100 }
101
101
102102 // Check for end of file. Don't eat the EOF.
103103 if (LastChar == EOF)
104104 return tok_eof;
139139
140140 /// UnaryExprAST - Expression class for a unary operator.
141141 struct UnaryExprAST : public ExprAST {
142 UnaryExprAST(char Opcode, std::unique_ptr Operand)
142 UnaryExprAST(char Opcode, std::unique_ptr Operand)
143143 : Opcode(std::move(Opcode)), Operand(std::move(Operand)) {}
144144
145145 Value *IRGen(IRGenContext &C) const override;
151151 /// BinaryExprAST - Expression class for a binary operator.
152152 struct BinaryExprAST : public ExprAST {
153153 BinaryExprAST(char Op, std::unique_ptr LHS,
154 std::unique_ptr RHS)
154 std::unique_ptr RHS)
155155 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
156156
157157 Value *IRGen(IRGenContext &C) const override;
223223
224224 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
225225 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
226
226
227227 char getOperatorName() const {
228228 assert(isUnaryOp() || isBinaryOp());
229229 return Name[Name.size()-1];
267267 static int GetTokPrecedence() {
268268 if (!isascii(CurTok))
269269 return -1;
270
270
271271 // Make sure it's a declared binop.
272272 int TokPrec = BinopPrecedence[CurTok];
273273 if (TokPrec <= 0) return -1;
293293 /// ::= identifier '(' expression* ')'
294294 static std::unique_ptr ParseIdentifierExpr() {
295295 std::string IdName = IdentifierStr;
296
296
297297 getNextToken(); // eat identifier.
298
298
299299 if (CurTok != '(') // Simple variable ref.
300300 return llvm::make_unique(IdName);
301
301
302302 // Call.
303303 getNextToken(); // eat (
304304 std::vector> Args;
318318
319319 // Eat the ')'.
320320 getNextToken();
321
321
322322 return llvm::make_unique(IdName, std::move(Args));
323323 }
324324
335335 auto V = ParseExpression();
336336 if (!V)
337337 return nullptr;
338
338
339339 if (CurTok != ')')
340340 return ErrorU("expected ')'");
341341 getNextToken(); // eat ).
345345 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
346346 static std::unique_ptr ParseIfExpr() {
347347 getNextToken(); // eat the if.
348
348
349349 // condition.
350350 auto Cond = ParseExpression();
351351 if (!Cond)
352352 return nullptr;
353
353
354354 if (CurTok != tok_then)
355355 return ErrorU("expected then");
356356 getNextToken(); // eat the then
357
357
358358 auto Then = ParseExpression();
359359 if (!Then)
360360 return nullptr;
361
361
362362 if (CurTok != tok_else)
363363 return ErrorU("expected else");
364
364
365365 getNextToken();
366
366
367367 auto Else = ParseExpression();
368368 if (!Else)
369369 return nullptr;
370
370
371371 return llvm::make_unique(std::move(Cond), std::move(Then),
372372 std::move(Else));
373373 }
378378
379379 if (CurTok != tok_identifier)
380380 return ErrorU("expected identifier after for");
381
381
382382 std::string IdName = IdentifierStr;
383383 getNextToken(); // eat identifier.
384
384
385385 if (CurTok != '=')
386386 return ErrorU("expected '=' after for");
387387 getNextToken(); // eat '='.
388
389
388
389
390390 auto Start = ParseExpression();
391391 if (!Start)
392392 return nullptr;
393393 if (CurTok != ',')
394394 return ErrorU("expected ',' after for start value");
395395 getNextToken();
396
396
397397 auto End = ParseExpression();
398398 if (!End)
399399 return nullptr;
400
400
401401 // The step value is optional.
402402 std::unique_ptr Step;
403403 if (CurTok == ',') {
406406 if (!Step)
407407 return nullptr;
408408 }
409
409
410410 if (CurTok != tok_in)
411411 return ErrorU("expected 'in' after for");
412412 getNextToken(); // eat 'in'.
413
413
414414 auto Body = ParseExpression();
415415 if (Body)
416416 return nullptr;
419419 std::move(Step), std::move(Body));
420420 }
421421
422 /// varexpr ::= 'var' identifier ('=' expression)?
422 /// varexpr ::= 'var' identifier ('=' expression)?
423423 // (',' identifier ('=' expression)?)* 'in' expression
424424 static std::unique_ptr ParseVarExpr() {
425425 getNextToken(); // eat the var.
429429 // At least one variable name is required.
430430 if (CurTok != tok_identifier)
431431 return ErrorU("expected identifier after var");
432
432
433433 while (1) {
434434 std::string Name = IdentifierStr;
435435 getNextToken(); // eat identifier.
438438 std::unique_ptr Init;
439439 if (CurTok == '=') {
440440 getNextToken(); // eat the '='.
441
441
442442 Init = ParseExpression();
443443 if (!Init)
444444 return nullptr;
445445 }
446
446
447447 VarBindings.push_back(VarExprAST::Binding(Name, std::move(Init)));
448
448
449449 // End of var list, exit loop.
450450 if (CurTok != ',') break;
451451 getNextToken(); // eat the ','.
452
452
453453 if (CurTok != tok_identifier)
454454 return ErrorU("expected identifier list after var");
455455 }
456
456
457457 // At this point, we have to have 'in'.
458458 if (CurTok != tok_in)
459459 return ErrorU("expected 'in' keyword after 'var'");
460460 getNextToken(); // eat 'in'.
461
461
462462 auto Body = ParseExpression();
463463 if (!Body)
464464 return nullptr;
465
465
466466 return llvm::make_unique(std::move(VarBindings), std::move(Body));
467467 }
468468
492492 // If the current token is not an operator, it must be a primary expr.
493493 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
494494 return ParsePrimary();
495
495
496496 // If this is a unary operator, read it.
497497 int Opc = CurTok;
498498 getNextToken();
508508 // If this is a binop, find its precedence.
509509 while (1) {
510510 int TokPrec = GetTokPrecedence();
511
511
512512 // If this is a binop that binds at least as tightly as the current binop,
513513 // consume it, otherwise we are done.
514514 if (TokPrec < ExprPrec)
515515 return LHS;
516
516
517517 // Okay, we know this is a binop.
518518 int BinOp = CurTok;
519519 getNextToken(); // eat binop
520
520
521521 // Parse the unary expression after the binary operator.
522522 auto RHS = ParseUnary();
523523 if (!RHS)
524524 return nullptr;
525
525
526526 // If BinOp binds less tightly with RHS than the operator after RHS, let
527527 // the pending operator take RHS as its LHS.
528528 int NextPrec = GetTokPrecedence();
531531 if (!RHS)
532532 return nullptr;
533533 }
534
534
535535 // Merge LHS/RHS.
536536 LHS = llvm::make_unique(BinOp, std::move(LHS), std::move(RHS));
537537 }
544544 auto LHS = ParseUnary();
545545 if (!LHS)
546546 return nullptr;
547
547
548548 return ParseBinOpRHS(0, std::move(LHS));
549549 }
550550
554554 /// ::= unary LETTER (id)
555555 static std::unique_ptr ParsePrototype() {
556556 std::string FnName;
557
557
558558 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
559559 unsigned BinaryPrecedence = 30;
560
560
561561 switch (CurTok) {
562562 default:
563563 return ErrorU("Expected function name in prototype");
583583 FnName += (char)CurTok;
584584 Kind = 2;
585585 getNextToken();
586
586
587587 // Read the precedence if present.
588588 if (CurTok == tok_number) {
589589 if (NumVal < 1 || NumVal > 100)
593593 }
594594 break;
595595 }
596
596
597597 if (CurTok != '(')
598598 return ErrorU("Expected '(' in prototype");
599
599
600600 std::vector ArgNames;
601601 while (getNextToken() == tok_identifier)
602602 ArgNames.push_back(IdentifierStr);
603603 if (CurTok != ')')
604604 return ErrorU("Expected ')' in prototype");
605
605
606606 // success.
607607 getNextToken(); // eat ')'.
608
608
609609 // Verify right number of names for operator.
610610 if (Kind && ArgNames.size() != Kind)
611611 return ErrorU("Invalid number of operands for operator");
612
612
613613 return llvm::make_unique(FnName, std::move(ArgNames), Kind != 0,
614614 BinaryPrecedence);
615615 }
690690 PrototypeAST* getPrototypeAST(const std::string &Name);
691691 private:
692692 typedef std::map> PrototypeMap;
693
693
694694 LLVMContext &Context;
695695 std::unique_ptr TM;
696
696
697697 PrototypeMap Prototypes;
698698 };
699699
794794 }
795795 return ErrorP("Unknown variable name");
796796 }
797
797
798798 Value *L = LHS->IRGen(C);
799799 Value *R = RHS->IRGen(C);
800800 if (!L || !R) return nullptr;
801
801
802802 switch (Op) {
803803 case '+': return C.getBuilder().CreateFAdd(L, R, "addtmp");
804804 case '-': return C.getBuilder().CreateFSub(L, R, "subtmp");
811811 "booltmp");
812812 default: break;
813813 }
814
814
815815 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
816816 // a call to it.
817817 std::string FnName = MakeLegalFunctionName(std::string("binary")+Op);
819819 Value *Ops[] = { L, R };
820820 return C.getBuilder().CreateCall(F, Ops, "binop");
821821 }
822
822
823823 return ErrorP("Unknown binary operator");
824824 }
825825
835835 ArgsV.push_back(Args[i]->IRGen(C));
836836 if (!ArgsV.back()) return nullptr;
837837 }
838
838
839839 return C.getBuilder().CreateCall(CalleeF, ArgsV, "calltmp");
840840 }
841841
845845 Value *IfExprAST::IRGen(IRGenContext &C) const {
846846 Value *CondV = Cond->IRGen(C);
847847 if (!CondV) return nullptr;
848
848
849849 // Convert condition to a bool by comparing equal to 0.0.
850 ConstantFP *FPZero =
850 ConstantFP *FPZero =
851851 ConstantFP::get(C.getLLVMContext(), APFloat(0.0));
852852 CondV = C.getBuilder().CreateFCmpONE(CondV, FPZero, "ifcond");
853
853
854854 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
855
855
856856 // Create blocks for the then and else cases. Insert the 'then' block at the
857857 // end of the function.
858858 BasicBlock *ThenBB = BasicBlock::Create(C.getLLVMContext(), "then", TheFunction);
859859 BasicBlock *ElseBB = BasicBlock::Create(C.getLLVMContext(), "else");
860860 BasicBlock *MergeBB = BasicBlock::Create(C.getLLVMContext(), "ifcont");
861
861
862862 C.getBuilder().CreateCondBr(CondV, ThenBB, ElseBB);
863
863
864864 // Emit then value.
865865 C.getBuilder().SetInsertPoint(ThenBB);
866
866
867867 Value *ThenV = Then->IRGen(C);
868868 if (!ThenV) return nullptr;
869
869
870870 C.getBuilder().CreateBr(MergeBB);
871871 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
872872 ThenBB = C.getBuilder().GetInsertBlock();
873
873
874874 // Emit else block.
875875 TheFunction->getBasicBlockList().push_back(ElseBB);
876876 C.getBuilder().SetInsertPoint(ElseBB);
877
877
878878 Value *ElseV = Else->IRGen(C);
879879 if (!ElseV) return nullptr;
880
880
881881 C.getBuilder().CreateBr(MergeBB);
882882 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
883883 ElseBB = C.getBuilder().GetInsertBlock();
884
884
885885 // Emit merge block.
886886 TheFunction->getBasicBlockList().push_back(MergeBB);
887887 C.getBuilder().SetInsertPoint(MergeBB);
888888 PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
889889 "iftmp");
890
890
891891 PN->addIncoming(ThenV, ThenBB);
892892 PN->addIncoming(ElseV, ElseBB);
893893 return PN;
900900 // start = startexpr
901901 // store start -> var
902902 // goto loop
903 // loop:
903 // loop:
904904 // ...
905905 // bodyexpr
906906 // ...
913913 // store nextvar -> var
914914 // br endcond, loop, endloop
915915 // outloop:
916
916
917917 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
918918
919919 // Create an alloca for the variable in the entry block.
920920 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
921
921
922922 // Emit the start code first, without 'variable' in scope.
923923 Value *StartVal = Start->IRGen(C);
924924 if (!StartVal) return nullptr;
925
925
926926 // Store the value into the alloca.
927927 C.getBuilder().CreateStore(StartVal, Alloca);
928
928
929929 // Make the new basic block for the loop header, inserting after current
930930 // block.
931931 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
932
932
933933 // Insert an explicit fall through from the current block to the LoopBB.
934934 C.getBuilder().CreateBr(LoopBB);
935935
936936 // Start insertion in LoopBB.
937937 C.getBuilder().SetInsertPoint(LoopBB);
938
938
939939 // Within the loop, the variable is defined equal to the PHI node. If it
940940 // shadows an existing variable, we have to restore it, so save it now.
941941 AllocaInst *OldVal = C.NamedValues[VarName];
942942 C.NamedValues[VarName] = Alloca;
943
943
944944 // Emit the body of the loop. This, like any other expr, can change the
945945 // current BB. Note that we ignore the value computed by the body, but don't
946946 // allow an error.
947947 if (!Body->IRGen(C))
948948 return nullptr;
949
949
950950 // Emit the step value.
951951 Value *StepVal;
952952 if (Step) {
956956 // If not specified, use 1.0.
957957 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
958958 }
959
959
960960 // Compute the end condition.
961961 Value *EndCond = End->IRGen(C);
962962 if (EndCond == 0) return EndCond;
963
963
964964 // Reload, increment, and restore the alloca. This handles the case where
965965 // the body of the loop mutates the variable.
966966 Value *CurVar = C.getBuilder().CreateLoad(Alloca, VarName.c_str());
967967 Value *NextVar = C.getBuilder().CreateFAdd(CurVar, StepVal, "nextvar");
968968 C.getBuilder().CreateStore(NextVar, Alloca);
969
969
970970 // Convert condition to a bool by comparing equal to 0.0.
971 EndCond = C.getBuilder().CreateFCmpONE(EndCond,
971 EndCond = C.getBuilder().CreateFCmpONE(EndCond,
972972 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
973973 "loopcond");
974
974
975975 // Create the "after loop" block and insert it.
976976 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
977
977
978978 // Insert the conditional branch into the end of LoopEndBB.
979979 C.getBuilder().CreateCondBr(EndCond, LoopBB, AfterBB);
980
980
981981 // Any new code will be inserted in AfterBB.
982982 C.getBuilder().SetInsertPoint(AfterBB);
983
983
984984 // Restore the unshadowed variable.
985985 if (OldVal)
986986 C.NamedValues[VarName] = OldVal;
987987 else
988988 C.NamedValues.erase(VarName);
989989
990
990
991991 // for expr always returns 0.0.
992992 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
993993 }
994994
995995 Value *VarExprAST::IRGen(IRGenContext &C) const {
996996 std::vector OldBindings;
997
997
998998 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
999999
10001000 // Register all variables and emit their initializer.
10011001 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i) {
10021002 auto &VarName = VarBindings[i].first;
10031003 auto &Init = VarBindings[i].second;
1004
1004
10051005 // Emit the initializer before adding the variable to scope, this prevents
10061006 // the initializer from referencing the variable itself, and permits stuff
10071007 // like this:
10131013 if (!InitVal) return nullptr;
10141014 } else // If not specified, use 0.0.
10151015 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1016
1016
10171017 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
10181018 C.getBuilder().CreateStore(InitVal, Alloca);
10191019
10201020 // Remember the old variable binding so that we can restore the binding when
10211021 // we unrecurse.
10221022 OldBindings.push_back(C.NamedValues[VarName]);
1023
1023
10241024 // Remember this binding.
10251025 C.NamedValues[VarName] = Alloca;
10261026 }
1027
1027
10281028 // Codegen the body, now that all vars are in scope.
10291029 Value *BodyVal = Body->IRGen(C);
10301030 if (!BodyVal) return nullptr;
1031
1031
10321032 // Pop all our variables from scope.
10331033 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i)
10341034 C.NamedValues[VarBindings[i].first] = OldBindings[i];
10411041 std::string FnName = MakeLegalFunctionName(Name);
10421042
10431043 // Make the function type: double(double,double) etc.
1044 std::vector Doubles(Args.size(),
1044 std::vector Doubles(Args.size(),
10451045 Type::getDoubleTy(getGlobalContext()));
10461046 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
10471047 Doubles, false);
10541054 // Delete the one we just made and get the existing one.
10551055 F->eraseFromParent();
10561056 F = C.getM().getFunction(Name);
1057
1057
10581058 // If F already has a body, reject this.
10591059 if (!F->empty()) {
10601060 ErrorP("redefinition of function");
10611061 return nullptr;
10621062 }
1063
1063
10641064 // If F took a different number of args, reject.
10651065 if (F->arg_size() != Args.size()) {
10661066 ErrorP("redefinition of function with different # args");
10671067 return nullptr;
10681068 }
10691069 }
1070
1070
10711071 // Set names for all arguments.
10721072 unsigned Idx = 0;
10731073 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
10741074 ++AI, ++Idx)
10751075 AI->setName(Args[Idx]);
1076
1076
10771077 return F;
10781078 }
10791079
10951095
10961096 Function *FunctionAST::IRGen(IRGenContext &C) const {
10971097 C.NamedValues.clear();
1098
1098
10991099 Function *TheFunction = Proto->IRGen(C);
11001100 if (!TheFunction)
11011101 return nullptr;
1102
1102
11031103 // If this is an operator, install it.
11041104 if (Proto->isBinaryOp())
11051105 BinopPrecedence[Proto->getOperatorName()] = Proto->Precedence;
1106
1106
11071107 // Create a new basic block to start insertion into.
11081108 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
11091109 C.getBuilder().SetInsertPoint(BB);
1110
1110
11111111 // Add all arguments to the symbol table and create their allocas.
11121112 Proto->CreateArgumentAllocas(TheFunction, C);
11131113
11201120
11211121 return TheFunction;
11221122 }
1123
1123
11241124 // Error reading body, remove function.
11251125 TheFunction->eraseFromParent();
11261126
13491349
13501350 // Get the address of the JIT'd function in memory.
13511351 auto ExprSymbol = J.findUnmangledSymbol("__anon_expr");
1352
1352
13531353 // Cast it to the right type (takes no arguments, returns a double) so we
13541354 // can call it as a native function.
13551355 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
13921392 //===----------------------------------------------------------------------===//
13931393
13941394 /// putchard - putchar that takes a double and returns 0.
1395 extern "C"
1395 extern "C"
13961396 double putchard(double X) {
13971397 putchar((char)X);
13981398 return 0;
13991399 }
14001400
14011401 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1402 extern "C"
1402 extern "C"
14031403 double printd(double X) {
14041404 printf("%f", X);
14051405 return 0;
14061406 }
14071407
1408 extern "C"
1408 extern "C"
14091409 double printlf() {
14101410 printf("\n");
14111411 return 0;
14421442
14431443 return 0;
14441444 }
1445
3737
3838 // primary
3939 tok_identifier = -4, tok_number = -5,
40
40
4141 // control
4242 tok_if = -6, tok_then = -7, tok_else = -8,
4343 tok_for = -9, tok_in = -10,
44
44
4545 // operators
4646 tok_binary = -11, tok_unary = -12,
47
47
4848 // var definition
4949 tok_var = -13
5050 };
9393 // Comment until end of line.
9494 do LastChar = getchar();
9595 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
96
96
9797 if (LastChar != EOF)
9898 return gettok();
9999 }
100
100
101101 // Check for end of file. Don't eat the EOF.
102102 if (LastChar == EOF)
103103 return tok_eof;
138138
139139 /// UnaryExprAST - Expression class for a unary operator.
140140 struct UnaryExprAST : public ExprAST {
141 UnaryExprAST(char Opcode, std::unique_ptr Operand)
141 UnaryExprAST(char Opcode, std::unique_ptr Operand)
142142 : Opcode(std::move(Opcode)), Operand(std::move(Operand)) {}
143143
144144 Value *IRGen(IRGenContext &C) const override;
150150 /// BinaryExprAST - Expression class for a binary operator.
151151 struct BinaryExprAST : public ExprAST {
152152 BinaryExprAST(char Op, std::unique_ptr LHS,
153 std::unique_ptr RHS)
153 std::unique_ptr RHS)
154154 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
155155
156156 Value *IRGen(IRGenContext &C) const override;
222222
223223 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
224224 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
225
225
226226 char getOperatorName() const {
227227 assert(isUnaryOp() || isBinaryOp());
228228 return Name[Name.size()-1];
266266 static int GetTokPrecedence() {
267267 if (!isascii(CurTok))
268268 return -1;
269
269
270270 // Make sure it's a declared binop.
271271 int TokPrec = BinopPrecedence[CurTok];
272272 if (TokPrec <= 0) return -1;
292292 /// ::= identifier '(' expression* ')'
293293 static std::unique_ptr ParseIdentifierExpr() {
294294 std::string IdName = IdentifierStr;
295
295
296296 getNextToken(); // eat identifier.
297
297
298298 if (CurTok != '(') // Simple variable ref.
299299 return llvm::make_unique(IdName);
300
300
301301 // Call.
302302 getNextToken(); // eat (
303303 std::vector> Args;
317317
318318 // Eat the ')'.
319319 getNextToken();
320
320
321321 return llvm::make_unique(IdName, std::move(Args));
322322 }
323323
334334 auto V = ParseExpression();
335335 if (!V)
336336 return nullptr;
337
337
338338 if (CurTok != ')')
339339 return ErrorU("expected ')'");
340340 getNextToken(); // eat ).
344344 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
345345 static std::unique_ptr ParseIfExpr() {
346346 getNextToken(); // eat the if.
347
347
348348 // condition.
349349 auto Cond = ParseExpression();
350350 if (!Cond)
351351 return nullptr;
352
352
353353 if (CurTok != tok_then)
354354 return ErrorU("expected then");
355355 getNextToken(); // eat the then
356
356
357357 auto Then = ParseExpression();
358358 if (!Then)
359359 return nullptr;
360
360
361361 if (CurTok != tok_else)
362362 return ErrorU("expected else");
363
363
364364 getNextToken();
365
365
366366 auto Else = ParseExpression();
367367 if (!Else)
368368 return nullptr;
369
369
370370 return llvm::make_unique(std::move(Cond), std::move(Then),
371371 std::move(Else));
372372 }
377377
378378 if (CurTok != tok_identifier)
379379 return ErrorU("expected identifier after for");
380
380
381381 std::string IdName = IdentifierStr;
382382 getNextToken(); // eat identifier.
383
383
384384 if (CurTok != '=')
385385 return ErrorU("expected '=' after for");
386386 getNextToken(); // eat '='.
387
388
387
388
389389 auto Start = ParseExpression();
390390 if (!Start)
391391 return nullptr;
392392 if (CurTok != ',')
393393 return ErrorU("expected ',' after for start value");
394394 getNextToken();
395
395
396396 auto End = ParseExpression();
397397 if (!End)
398398 return nullptr;
399
399
400400 // The step value is optional.
401401 std::unique_ptr Step;
402402 if (CurTok == ',') {
405405 if (!Step)
406406 return nullptr;
407407 }
408
408
409409 if (CurTok != tok_in)
410410 return ErrorU("expected 'in' after for");
411411 getNextToken(); // eat 'in'.
412
412
413413 auto Body = ParseExpression();
414414 if (Body)
415415 return nullptr;
418418 std::move(Step), std::move(Body));
419419 }
420420
421 /// varexpr ::= 'var' identifier ('=' expression)?
421 /// varexpr ::= 'var' identifier ('=' expression)?
422422 // (',' identifier ('=' expression)?)* 'in' expression
423423 static std::unique_ptr ParseVarExpr() {
424424 getNextToken(); // eat the var.
428428 // At least one variable name is required.
429429 if (CurTok != tok_identifier)
430430 return ErrorU("expected identifier after var");
431
431
432432 while (1) {
433433 std::string Name = IdentifierStr;
434434 getNextToken(); // eat identifier.
437437 std::unique_ptr Init;
438438 if (CurTok == '=') {
439439 getNextToken(); // eat the '='.
440
440
441441 Init = ParseExpression();
442442 if (!Init)
443443 return nullptr;
444444 }
445
445
446446 VarBindings.push_back(VarExprAST::Binding(Name, std::move(Init)));
447
447
448448 // End of var list, exit loop.
449449 if (CurTok != ',') break;
450450 getNextToken(); // eat the ','.
451
451
452452 if (CurTok != tok_identifier)
453453 return ErrorU("expected identifier list after var");
454454 }
455
455
456456 // At this point, we have to have 'in'.
457457 if (CurTok != tok_in)
458458 return ErrorU("expected 'in' keyword after 'var'");
459459 getNextToken(); // eat 'in'.
460
460
461461 auto Body = ParseExpression();
462462 if (!Body)
463463 return nullptr;
464
464
465465 return llvm::make_unique(std::move(VarBindings), std::move(Body));
466466 }
467467
491491 // If the current token is not an operator, it must be a primary expr.
492492 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
493493 return ParsePrimary();
494
494
495495 // If this is a unary operator, read it.
496496 int Opc = CurTok;
497497 getNextToken();
507507 // If this is a binop, find its precedence.
508508 while (1) {
509509 int TokPrec = GetTokPrecedence();
510
510
511511 // If this is a binop that binds at least as tightly as the current binop,
512512 // consume it, otherwise we are done.
513513 if (TokPrec < ExprPrec)
514514 return LHS;
515
515
516516 // Okay, we know this is a binop.
517517 int BinOp = CurTok;
518518 getNextToken(); // eat binop
519
519
520520 // Parse the unary expression after the binary operator.
521521 auto RHS = ParseUnary();
522522 if (!RHS)
523523 return nullptr;
524
524
525525 // If BinOp binds less tightly with RHS than the operator after RHS, let
526526 // the pending operator take RHS as its LHS.
527527 int NextPrec = GetTokPrecedence();
530530 if (!RHS)
531531 return nullptr;
532532 }
533
533
534534 // Merge LHS/RHS.
535535 LHS = llvm::make_unique(BinOp, std::move(LHS), std::move(RHS));
536536 }
543543 auto LHS = ParseUnary();
544544 if (!LHS)
545545 return nullptr;
546
546
547547 return ParseBinOpRHS(0, std::move(LHS));
548548 }
549549
553553 /// ::= unary LETTER (id)
554554 static std::unique_ptr ParsePrototype() {
555555 std::string FnName;
556
556
557557 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
558558 unsigned BinaryPrecedence = 30;
559
559
560560 switch (CurTok) {
561561 default:
562562 return ErrorU("Expected function name in prototype");
582582 FnName += (char)CurTok;
583583 Kind = 2;
584584 getNextToken();
585
585
586586 // Read the precedence if present.
587587 if (CurTok == tok_number) {
588588 if (NumVal < 1 || NumVal > 100)
592592 }
593593 break;
594594 }
595
595
596596 if (CurTok != '(')
597597 return ErrorU("Expected '(' in prototype");
598
598
599599 std::vector ArgNames;
600600 while (getNextToken() == tok_identifier)
601601 ArgNames.push_back(IdentifierStr);
602602 if (CurTok != ')')
603603 return ErrorU("Expected ')' in prototype");
604
604
605605 // success.
606606 getNextToken(); // eat ')'.
607
607
608608 // Verify right number of names for operator.
609609 if (Kind && ArgNames.size() != Kind)
610610 return ErrorU("Invalid number of operands for operator");
611
611
612612 return llvm::make_unique(FnName, std::move(ArgNames), Kind != 0,
613613 BinaryPrecedence);
614614 }
689689 PrototypeAST* getPrototypeAST(const std::string &Name);
690690 private:
691691 typedef std::map> PrototypeMap;
692
692
693693 LLVMContext &Context;
694694 std::unique_ptr TM;
695
695
696696 PrototypeMap Prototypes;
697697 };
698698
793793 }
794794 return ErrorP("Unknown variable name");
795795 }
796
796
797797 Value *L = LHS->IRGen(C);
798798 Value *R = RHS->IRGen(C);
799799 if (!L || !R) return nullptr;
800
800
801801 switch (Op) {
802802 case '+': return C.getBuilder().CreateFAdd(L, R, "addtmp");
803803 case '-': return C.getBuilder().CreateFSub(L, R, "subtmp");
810810 "booltmp");
811811 default: break;
812812 }
813
813
814814 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
815815 // a call to it.
816816 std::string FnName = MakeLegalFunctionName(std::string("binary")+Op);
818818 Value *Ops[] = { L, R };
819819 return C.getBuilder().CreateCall(F, Ops, "binop");
820820 }
821
821
822822 return ErrorP("Unknown binary operator");
823823 }
824824
834834 ArgsV.push_back(Args[i]->IRGen(C));
835835 if (!ArgsV.back()) return nullptr;
836836 }
837
837
838838 return C.getBuilder().CreateCall(CalleeF, ArgsV, "calltmp");
839839 }
840840
844844 Value *IfExprAST::IRGen(IRGenContext &C) const {
845845 Value *CondV = Cond->IRGen(C);
846846 if (!CondV) return nullptr;
847
847
848848 // Convert condition to a bool by comparing equal to 0.0.
849 ConstantFP *FPZero =
849 ConstantFP *FPZero =
850850 ConstantFP::get(C.getLLVMContext(), APFloat(0.0));
851851 CondV = C.getBuilder().CreateFCmpONE(CondV, FPZero, "ifcond");
852
852
853853 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
854
854
855855 // Create blocks for the then and else cases. Insert the 'then' block at the
856856 // end of the function.
857857 BasicBlock *ThenBB = BasicBlock::Create(C.getLLVMContext(), "then", TheFunction);
858858 BasicBlock *ElseBB = BasicBlock::Create(C.getLLVMContext(), "else");
859859 BasicBlock *MergeBB = BasicBlock::Create(C.getLLVMContext(), "ifcont");
860
860
861861 C.getBuilder().CreateCondBr(CondV, ThenBB, ElseBB);
862
862
863863 // Emit then value.
864864 C.getBuilder().SetInsertPoint(ThenBB);
865
865
866866 Value *ThenV = Then->IRGen(C);
867867 if (!ThenV) return nullptr;
868
868
869869 C.getBuilder().CreateBr(MergeBB);
870870 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
871871 ThenBB = C.getBuilder().GetInsertBlock();
872
872
873873 // Emit else block.
874874 TheFunction->getBasicBlockList().push_back(ElseBB);
875875 C.getBuilder().SetInsertPoint(ElseBB);
876
876
877877 Value *ElseV = Else->IRGen(C);
878878 if (!ElseV) return nullptr;
879
879
880880 C.getBuilder().CreateBr(MergeBB);
881881 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
882882 ElseBB = C.getBuilder().GetInsertBlock();
883
883
884884 // Emit merge block.
885885 TheFunction->getBasicBlockList().push_back(MergeBB);
886886 C.getBuilder().SetInsertPoint(MergeBB);
887887 PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
888888 "iftmp");
889
889
890890 PN->addIncoming(ThenV, ThenBB);
891891 PN->addIncoming(ElseV, ElseBB);
892892 return PN;
899899 // start = startexpr
900900 // store start -> var
901901 // goto loop
902 // loop:
902 // loop:
903903 // ...
904904 // bodyexpr
905905 // ...
912912 // store nextvar -> var
913913 // br endcond, loop, endloop
914914 // outloop:
915
915
916916 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
917917
918918 // Create an alloca for the variable in the entry block.
919919 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
920
920
921921 // Emit the start code first, without 'variable' in scope.
922922 Value *StartVal = Start->IRGen(C);
923923 if (!StartVal) return nullptr;
924
924
925925 // Store the value into the alloca.
926926 C.getBuilder().CreateStore(StartVal, Alloca);
927
927
928928 // Make the new basic block for the loop header, inserting after current
929929 // block.
930930 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
931
931
932932 // Insert an explicit fall through from the current block to the LoopBB.
933933 C.getBuilder().CreateBr(LoopBB);
934934
935935 // Start insertion in LoopBB.
936936 C.getBuilder().SetInsertPoint(LoopBB);
937
937
938938 // Within the loop, the variable is defined equal to the PHI node. If it
939939 // shadows an existing variable, we have to restore it, so save it now.
940940 AllocaInst *OldVal = C.NamedValues[VarName];
941941 C.NamedValues[VarName] = Alloca;
942
942
943943 // Emit the body of the loop. This, like any other expr, can change the
944944 // current BB. Note that we ignore the value computed by the body, but don't
945945 // allow an error.
946946 if (!Body->IRGen(C))
947947 return nullptr;
948
948
949949 // Emit the step value.
950950 Value *StepVal;
951951 if (Step) {
955955 // If not specified, use 1.0.
956956 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
957957 }
958
958
959959 // Compute the end condition.
960960 Value *EndCond = End->IRGen(C);
961961 if (EndCond == 0) return EndCond;
962
962
963963 // Reload, increment, and restore the alloca. This handles the case where
964964 // the body of the loop mutates the variable.
965965 Value *CurVar = C.getBuilder().CreateLoad(Alloca, VarName.c_str());
966966 Value *NextVar = C.getBuilder().CreateFAdd(CurVar, StepVal, "nextvar");
967967 C.getBuilder().CreateStore(NextVar, Alloca);
968
968
969969 // Convert condition to a bool by comparing equal to 0.0.
970 EndCond = C.getBuilder().CreateFCmpONE(EndCond,
970 EndCond = C.getBuilder().CreateFCmpONE(EndCond,
971971 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
972972 "loopcond");
973
973
974974 // Create the "after loop" block and insert it.
975975 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
976
976
977977 // Insert the conditional branch into the end of LoopEndBB.
978978 C.getBuilder().CreateCondBr(EndCond, LoopBB, AfterBB);
979
979
980980 // Any new code will be inserted in AfterBB.
981981 C.getBuilder().SetInsertPoint(AfterBB);
982
982
983983 // Restore the unshadowed variable.
984984 if (OldVal)
985985 C.NamedValues[VarName] = OldVal;
986986 else
987987 C.NamedValues.erase(VarName);
988988
989
989
990990 // for expr always returns 0.0.
991991 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
992992 }
993993
994994 Value *VarExprAST::IRGen(IRGenContext &C) const {
995995 std::vector OldBindings;
996
996
997997 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
998998
999999 // Register all variables and emit their initializer.
10001000 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i) {
10011001 auto &VarName = VarBindings[i].first;
10021002 auto &Init = VarBindings[i].second;
1003
1003
10041004 // Emit the initializer before adding the variable to scope, this prevents
10051005 // the initializer from referencing the variable itself, and permits stuff
10061006 // like this:
10121012 if (!InitVal) return nullptr;
10131013 } else // If not specified, use 0.0.
10141014 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1015
1015
10161016 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
10171017 C.getBuilder().CreateStore(InitVal, Alloca);
10181018
10191019 // Remember the old variable binding so that we can restore the binding when
10201020 // we unrecurse.
10211021 OldBindings.push_back(C.NamedValues[VarName]);
1022
1022
10231023 // Remember this binding.
10241024 C.NamedValues[VarName] = Alloca;
10251025 }
1026
1026
10271027 // Codegen the body, now that all vars are in scope.
10281028 Value *BodyVal = Body->IRGen(C);
10291029 if (!BodyVal) return nullptr;
1030
1030
10311031 // Pop all our variables from scope.
10321032 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i)
10331033 C.NamedValues[VarBindings[i].first] = OldBindings[i];
10401040 std::string FnName = MakeLegalFunctionName(Name);
10411041
10421042 // Make the function type: double(double,double) etc.
1043 std::vector Doubles(Args.size(),
1043 std::vector Doubles(Args.size(),
10441044 Type::getDoubleTy(getGlobalContext()));
10451045 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
10461046 Doubles, false);
10531053 // Delete the one we just made and get the existing one.
10541054 F->eraseFromParent();
10551055 F = C.getM().getFunction(Name);
1056
1056
10571057 // If F already has a body, reject this.
10581058 if (!F->empty()) {
10591059 ErrorP("redefinition of function");
10601060 return nullptr;
10611061 }
1062
1062
10631063 // If F took a different number of args, reject.
10641064 if (F->arg_size() != Args.size()) {
10651065 ErrorP("redefinition of function with different # args");
10661066 return nullptr;
10671067 }
10681068 }
1069
1069
10701070 // Set names for all arguments.
10711071 unsigned Idx = 0;
10721072 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
10731073 ++AI, ++Idx)
10741074 AI->setName(Args[Idx]);
1075
1075
10761076 return F;
10771077 }
10781078
10941094
10951095 Function *FunctionAST::IRGen(IRGenContext &C) const {
10961096 C.NamedValues.clear();
1097
1097
10981098 Function *TheFunction = Proto->IRGen(C);
10991099 if (!TheFunction)
11001100 return nullptr;
1101
1101
11021102 // If this is an operator, install it.
11031103 if (Proto->isBinaryOp())
11041104 BinopPrecedence[Proto->getOperatorName()] = Proto->Precedence;
1105
1105
11061106 // Create a new basic block to start insertion into.
11071107 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
11081108 C.getBuilder().SetInsertPoint(BB);
1109
1109
11101110 // Add all arguments to the symbol table and create their allocas.
11111111 Proto->CreateArgumentAllocas(TheFunction, C);
11121112
11191119
11201120 return TheFunction;
11211121 }
1122
1122
11231123 // Error reading body, remove function.
11241124 TheFunction->eraseFromParent();
11251125
12411241
12421242 // Get the address of the JIT'd function in memory.
12431243 auto ExprSymbol = J.findUnmangledSymbol("__anon_expr");
1244
1244
12451245 // Cast it to the right type (takes no arguments, returns a double) so we
12461246 // can call it as a native function.
12471247 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
12841284 //===----------------------------------------------------------------------===//
12851285
12861286 /// putchard - putchar that takes a double and returns 0.
1287 extern "C"
1287 extern "C"
12881288 double putchard(double X) {
12891289 putchar((char)X);
12901290 return 0;
12911291 }
12921292
12931293 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1294 extern "C"
1294 extern "C"
12951295 double printd(double X) {
12961296 printf("%f", X);
12971297 return 0;
12981298 }
12991299
1300 extern "C"
1300 extern "C"
13011301 double printlf() {
13021302 printf("\n");
13031303 return 0;
13341334
13351335 return 0;
13361336 }
1337
3737
3838 // primary
3939 tok_identifier = -4, tok_number = -5,
40
40
4141 // control
4242 tok_if = -6, tok_then = -7, tok_else = -8,
4343 tok_for = -9, tok_in = -10,
44
44
4545 // operators
4646 tok_binary = -11, tok_unary = -12,
47
47
4848 // var definition
4949 tok_var = -13
5050 };
9393 // Comment until end of line.
9494 do LastChar = getchar();
9595 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
96
96
9797 if (LastChar != EOF)
9898 return gettok();
9999 }
100
100
101101 // Check for end of file. Don't eat the EOF.
102102 if (LastChar == EOF)
103103 return tok_eof;
138138
139139 /// UnaryExprAST - Expression class for a unary operator.
140140 struct UnaryExprAST : public ExprAST {
141 UnaryExprAST(char Opcode, std::unique_ptr Operand)
141 UnaryExprAST(char Opcode, std::unique_ptr Operand)
142142 : Opcode(std::move(Opcode)), Operand(std::move(Operand)) {}
143143
144144 Value *IRGen(IRGenContext &C) const override;
150150 /// BinaryExprAST - Expression class for a binary operator.
151151 struct BinaryExprAST : public ExprAST {
152152 BinaryExprAST(char Op, std::unique_ptr LHS,
153 std::unique_ptr RHS)
153 std::unique_ptr RHS)
154154 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
155155
156156 Value *IRGen(IRGenContext &C) const override;
222222
223223 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
224224 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
225
225
226226 char getOperatorName() const {
227227 assert(isUnaryOp() || isBinaryOp());
228228 return Name[Name.size()-1];
266266 static int GetTokPrecedence() {
267267 if (!isascii(CurTok))
268268 return -1;
269
269
270270 // Make sure it's a declared binop.
271271 int TokPrec = BinopPrecedence[CurTok];
272272 if (TokPrec <= 0) return -1;
292292 /// ::= identifier '(' expression* ')'
293293 static std::unique_ptr ParseIdentifierExpr() {
294294 std::string IdName = IdentifierStr;
295
295
296296 getNextToken(); // eat identifier.
297
297
298298 if (CurTok != '(') // Simple variable ref.
299299 return llvm::make_unique(IdName);
300
300
301301 // Call.
302302 getNextToken(); // eat (
303303 std::vector> Args;
317317
318318 // Eat the ')'.
319319 getNextToken();
320
320
321321 return llvm::make_unique(IdName, std::move(Args));
322322 }
323323
334334 auto V = ParseExpression();
335335 if (!V)
336336 return nullptr;
337
337
338338 if (CurTok != ')')
339339 return ErrorU("expected ')'");
340340 getNextToken(); // eat ).
344344 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
345345 static std::unique_ptr ParseIfExpr() {
346346 getNextToken(); // eat the if.
347
347
348348 // condition.
349349 auto Cond = ParseExpression();
350350 if (!Cond)
351351 return nullptr;
352
352
353353 if (CurTok != tok_then)
354354 return ErrorU("expected then");
355355 getNextToken(); // eat the then
356
356
357357 auto Then = ParseExpression();
358358 if (!Then)
359359 return nullptr;
360
360
361361 if (CurTok != tok_else)
362362 return ErrorU("expected else");
363
363
364364 getNextToken();
365
365
366366 auto Else = ParseExpression();
367367 if (!Else)
368368 return nullptr;
369
369
370370 return llvm::make_unique(std::move(Cond), std::move(Then),
371371 std::move(Else));
372372 }
377377
378378 if (CurTok != tok_identifier)
379379 return ErrorU("expected identifier after for");
380
380
381381 std::string IdName = IdentifierStr;
382382 getNextToken(); // eat identifier.
383
383
384384 if (CurTok != '=')
385385 return ErrorU("expected '=' after for");
386386 getNextToken(); // eat '='.
387
388
387
388
389389 auto Start = ParseExpression();
390390 if (!Start)
391391 return nullptr;
392392 if (CurTok != ',')
393393 return ErrorU("expected ',' after for start value");
394394 getNextToken();
395
395
396396 auto End = ParseExpression();
397397 if (!End)
398398 return nullptr;
399
399
400400 // The step value is optional.
401401 std::unique_ptr Step;
402402 if (CurTok == ',') {
405405 if (!Step)
406406 return nullptr;
407407 }
408
408
409409 if (CurTok != tok_in)
410410 return ErrorU("expected 'in' after for");
411411 getNextToken(); // eat 'in'.
412
412
413413 auto Body = ParseExpression();
414414 if (Body)
415415 return nullptr;
418418 std::move(Step), std::move(Body));
419419 }
420420
421 /// varexpr ::= 'var' identifier ('=' expression)?
421 /// varexpr ::= 'var' identifier ('=' expression)?
422422 // (',' identifier ('=' expression)?)* 'in' expression
423423 static std::unique_ptr ParseVarExpr() {
424424 getNextToken(); // eat the var.
428428 // At least one variable name is required.
429429 if (CurTok != tok_identifier)
430430 return ErrorU("expected identifier after var");
431
431
432432 while (1) {
433433 std::string Name = IdentifierStr;
434434 getNextToken(); // eat identifier.
437437 std::unique_ptr Init;
438438 if (CurTok == '=') {
439439 getNextToken(); // eat the '='.
440
440
441441 Init = ParseExpression();
442442 if (!Init)
443443 return nullptr;
444444 }
445
445
446446 VarBindings.push_back(VarExprAST::Binding(Name, std::move(Init)));
447
447
448448 // End of var list, exit loop.
449449 if (CurTok != ',') break;
450450 getNextToken(); // eat the ','.
451
451
452452 if (CurTok != tok_identifier)
453453 return ErrorU("expected identifier list after var");
454454 }
455
455
456456 // At this point, we have to have 'in'.
457457 if (CurTok != tok_in)
458458 return ErrorU("expected 'in' keyword after 'var'");
459459 getNextToken(); // eat 'in'.
460
460
461461 auto Body = ParseExpression();
462462 if (!Body)
463463 return nullptr;
464
464
465465 return llvm::make_unique(std::move(VarBindings), std::move(Body));
466466 }
467467
491491 // If the current token is not an operator, it must be a primary expr.
492492 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
493493 return ParsePrimary();
494
494
495495 // If this is a unary operator, read it.
496496 int Opc = CurTok;
497497 getNextToken();
507507 // If this is a binop, find its precedence.
508508 while (1) {
509509 int TokPrec = GetTokPrecedence();
510
510
511511 // If this is a binop that binds at least as tightly as the current binop,
512512 // consume it, otherwise we are done.
513513 if (TokPrec < ExprPrec)
514514 return LHS;
515
515
516516 // Okay, we know this is a binop.
517517 int BinOp = CurTok;
518518 getNextToken(); // eat binop
519
519
520520 // Parse the unary expression after the binary operator.
521521 auto RHS = ParseUnary();
522522 if (!RHS)
523523 return nullptr;
524
524
525525 // If BinOp binds less tightly with RHS than the operator after RHS, let
526526 // the pending operator take RHS as its LHS.
527527 int NextPrec = GetTokPrecedence();
530530 if (!RHS)
531531 return nullptr;
532532 }
533
533
534534 // Merge LHS/RHS.
535535 LHS = llvm::make_unique(BinOp, std::move(LHS), std::move(RHS));
536536 }
543543 auto LHS = ParseUnary();
544544 if (!LHS)
545545 return nullptr;
546
546
547547 return ParseBinOpRHS(0, std::move(LHS));
548548 }
549549
553553 /// ::= unary LETTER (id)
554554 static std::unique_ptr ParsePrototype() {
555555 std::string FnName;
556
556
557557 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
558558 unsigned BinaryPrecedence = 30;
559
559
560560 switch (CurTok) {
561561 default:
562562 return ErrorU("Expected function name in prototype");
582582 FnName += (char)CurTok;
583583 Kind = 2;
584584 getNextToken();
585
585
586586 // Read the precedence if present.
587587 if (CurTok == tok_number) {
588588 if (NumVal < 1 || NumVal > 100)
592592 }
593593 break;
594594 }
595
595
596596 if (CurTok != '(')
597597 return ErrorU("Expected '(' in prototype");
598
598
599599 std::vector ArgNames;
600600 while (getNextToken() == tok_identifier)
601601 ArgNames.push_back(IdentifierStr);
602602 if (CurTok != ')')
603603 return ErrorU("Expected ')' in prototype");
604
604
605605 // success.
606606 getNextToken(); // eat ')'.
607
607
608608 // Verify right number of names for operator.
609609 if (Kind && ArgNames.size() != Kind)
610610 return ErrorU("Invalid number of operands for operator");
611
611
612612 return llvm::make_unique(FnName, std::move(ArgNames), Kind != 0,
613613 BinaryPrecedence);
614614 }
689689 PrototypeAST* getPrototypeAST(const std::string &Name);
690690 private:
691691 typedef std::map> PrototypeMap;
692
692
693693 LLVMContext &Context;
694694 std::unique_ptr TM;
695
695
696696 PrototypeMap Prototypes;
697697 };
698698
793793 }
794794 return ErrorP("Unknown variable name");
795795 }
796
796
797797 Value *L = LHS->IRGen(C);
798798 Value *R = RHS->IRGen(C);
799799 if (!L || !R) return nullptr;
800
800
801801 switch (Op) {
802802 case '+': return C.getBuilder().CreateFAdd(L, R, "addtmp");
803803 case '-': return C.getBuilder().CreateFSub(L, R, "subtmp");
810810 "booltmp");
811811 default: break;
812812 }
813
813
814814 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
815815 // a call to it.
816816 std::string FnName = MakeLegalFunctionName(std::string("binary")+Op);
818818 Value *Ops[] = { L, R };
819819 return C.getBuilder().CreateCall(F, Ops, "binop");
820820 }
821
821
822822 return ErrorP("Unknown binary operator");
823823 }
824824
834834 ArgsV.push_back(Args[i]->IRGen(C));
835835 if (!ArgsV.back()) return nullptr;
836836 }
837
837
838838 return C.getBuilder().CreateCall(CalleeF, ArgsV, "calltmp");
839839 }
840840
844844 Value *IfExprAST::IRGen(IRGenContext &C) const {
845845 Value *CondV = Cond->IRGen(C);
846846 if (!CondV) return nullptr;
847
847
848848 // Convert condition to a bool by comparing equal to 0.0.
849 ConstantFP *FPZero =
849 ConstantFP *FPZero =
850850 ConstantFP::get(C.getLLVMContext(), APFloat(0.0));
851851 CondV = C.getBuilder().CreateFCmpONE(CondV, FPZero, "ifcond");
852
852
853853 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
854
854
855855 // Create blocks for the then and else cases. Insert the 'then' block at the
856856 // end of the function.
857857 BasicBlock *ThenBB = BasicBlock::Create(C.getLLVMContext(), "then", TheFunction);
858858 BasicBlock *ElseBB = BasicBlock::Create(C.getLLVMContext(), "else");
859859 BasicBlock *MergeBB = BasicBlock::Create(C.getLLVMContext(), "ifcont");
860
860
861861 C.getBuilder().CreateCondBr(CondV, ThenBB, ElseBB);
862
862
863863 // Emit then value.
864864 C.getBuilder().SetInsertPoint(ThenBB);
865
865
866866 Value *ThenV = Then->IRGen(C);
867867 if (!ThenV) return nullptr;
868
868
869869 C.getBuilder().CreateBr(MergeBB);
870870 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
871871 ThenBB = C.getBuilder().GetInsertBlock();
872
872
873873 // Emit else block.
874874 TheFunction->getBasicBlockList().push_back(ElseBB);
875875 C.getBuilder().SetInsertPoint(ElseBB);
876
876
877877 Value *ElseV = Else->IRGen(C);
878878 if (!ElseV) return nullptr;
879
879
880880 C.getBuilder().CreateBr(MergeBB);
881881 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
882882 ElseBB = C.getBuilder().GetInsertBlock();
883
883
884884 // Emit merge block.
885885 TheFunction->getBasicBlockList().push_back(MergeBB);
886886 C.getBuilder().SetInsertPoint(MergeBB);
887887 PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
888888 "iftmp");
889
889
890890 PN->addIncoming(ThenV, ThenBB);
891891 PN->addIncoming(ElseV, ElseBB);
892892 return PN;
899899 // start = startexpr
900900 // store start -> var
901901 // goto loop
902 // loop:
902 // loop:
903903 // ...
904904 // bodyexpr
905905 // ...
912912 // store nextvar -> var
913913 // br endcond, loop, endloop
914914 // outloop:
915
915
916916 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
917917
918918 // Create an alloca for the variable in the entry block.
919919 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
920
920
921921 // Emit the start code first, without 'variable' in scope.
922922 Value *StartVal = Start->IRGen(C);
923923 if (!StartVal) return nullptr;
924
924
925925 // Store the value into the alloca.
926926 C.getBuilder().CreateStore(StartVal, Alloca);
927
927
928928 // Make the new basic block for the loop header, inserting after current
929929 // block.
930930 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
931
931
932932 // Insert an explicit fall through from the current block to the LoopBB.
933933 C.getBuilder().CreateBr(LoopBB);
934934
935935 // Start insertion in LoopBB.
936936 C.getBuilder().SetInsertPoint(LoopBB);
937
937
938938 // Within the loop, the variable is defined equal to the PHI node. If it
939939 // shadows an existing variable, we have to restore it, so save it now.
940940 AllocaInst *OldVal = C.NamedValues[VarName];
941941 C.NamedValues[VarName] = Alloca;
942
942
943943 // Emit the body of the loop. This, like any other expr, can change the
944944 // current BB. Note that we ignore the value computed by the body, but don't
945945 // allow an error.
946946 if (!Body->IRGen(C))
947947 return nullptr;
948
948
949949 // Emit the step value.
950950 Value *StepVal;
951951 if (Step) {
955955 // If not specified, use 1.0.
956956 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
957957 }
958
958
959959 // Compute the end condition.
960960 Value *EndCond = End->IRGen(C);
961961 if (EndCond == 0) return EndCond;
962
962
963963 // Reload, increment, and restore the alloca. This handles the case where
964964 // the body of the loop mutates the variable.
965965 Value *CurVar = C.getBuilder().CreateLoad(Alloca, VarName.c_str());
966966 Value *NextVar = C.getBuilder().CreateFAdd(CurVar, StepVal, "nextvar");
967967 C.getBuilder().CreateStore(NextVar, Alloca);
968
968
969969 // Convert condition to a bool by comparing equal to 0.0.
970 EndCond = C.getBuilder().CreateFCmpONE(EndCond,
970 EndCond = C.getBuilder().CreateFCmpONE(EndCond,
971971 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
972972 "loopcond");
973
973
974974 // Create the "after loop" block and insert it.
975975 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
976
976
977977 // Insert the conditional branch into the end of LoopEndBB.
978978 C.getBuilder().CreateCondBr(EndCond, LoopBB, AfterBB);
979
979
980980 // Any new code will be inserted in AfterBB.
981981 C.getBuilder().SetInsertPoint(AfterBB);
982
982
983983 // Restore the unshadowed variable.
984984 if (OldVal)
985985 C.NamedValues[VarName] = OldVal;
986986 else
987987 C.NamedValues.erase(VarName);
988988
989
989
990990 // for expr always returns 0.0.
991991 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
992992 }
993993
994994 Value *VarExprAST::IRGen(IRGenContext &C) const {
995995 std::vector OldBindings;
996
996
997997 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
998998
999999 // Register all variables and emit their initializer.
10001000 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i) {
10011001 auto &VarName = VarBindings[i].first;
10021002 auto &Init = VarBindings[i].second;
1003
1003
10041004 // Emit the initializer before adding the variable to scope, this prevents
10051005 // the initializer from referencing the variable itself, and permits stuff
10061006 // like this:
10121012 if (!InitVal) return nullptr;
10131013 } else // If not specified, use 0.0.
10141014 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1015
1015
10161016 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
10171017 C.getBuilder().CreateStore(InitVal, Alloca);
10181018
10191019 // Remember the old variable binding so that we can restore the binding when
10201020 // we unrecurse.
10211021 OldBindings.push_back(C.NamedValues[VarName]);
1022
1022
10231023 // Remember this binding.
10241024 C.NamedValues[VarName] = Alloca;
10251025 }
1026
1026
10271027 // Codegen the body, now that all vars are in scope.
10281028 Value *BodyVal = Body->IRGen(C);
10291029 if (!BodyVal) return nullptr;
1030
1030
10311031 // Pop all our variables from scope.
10321032 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i)
10331033 C.NamedValues[VarBindings[i].first] = OldBindings[i];
10401040 std::string FnName = MakeLegalFunctionName(Name);
10411041
10421042 // Make the function type: double(double,double) etc.
1043 std::vector Doubles(Args.size(),
1043 std::vector Doubles(Args.size(),
10441044 Type::getDoubleTy(getGlobalContext()));
10451045 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
10461046 Doubles, false);
10531053 // Delete the one we just made and get the existing one.
10541054 F->eraseFromParent();
10551055 F = C.getM().getFunction(Name);
1056
1056
10571057 // If F already has a body, reject this.
10581058 if (!F->empty()) {
10591059 ErrorP("redefinition of function");
10601060 return nullptr;
10611061 }
1062
1062
10631063 // If F took a different number of args, reject.
10641064 if (F->arg_size() != Args.size()) {
10651065 ErrorP("redefinition of function with different # args");
10661066 return nullptr;
10671067 }
10681068 }
1069
1069
10701070 // Set names for all arguments.
10711071 unsigned Idx = 0;
10721072 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
10731073 ++AI, ++Idx)
10741074 AI->setName(Args[Idx]);
1075
1075
10761076 return F;
10771077 }
10781078
10941094
10951095 Function *FunctionAST::IRGen(IRGenContext &C) const {
10961096 C.NamedValues.clear();
1097
1097
10981098 Function *TheFunction = Proto->IRGen(C);
10991099 if (!TheFunction)
11001100 return nullptr;
1101
1101
11021102 // If this is an operator, install it.
11031103 if (Proto->isBinaryOp())
11041104 BinopPrecedence[Proto->getOperatorName()] = Proto->Precedence;
1105
1105
11061106 // Create a new basic block to start insertion into.
11071107 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
11081108 C.getBuilder().SetInsertPoint(BB);
1109
1109
11101110 // Add all arguments to the symbol table and create their allocas.
11111111 Proto->CreateArgumentAllocas(TheFunction, C);
11121112
11191119
11201120 return TheFunction;
11211121 }
1122
1122
11231123 // Error reading body, remove function.
11241124 TheFunction->eraseFromParent();
11251125
12451245
12461246 // Get the address of the JIT'd function in memory.
12471247 auto ExprSymbol = J.findUnmangledSymbol("__anon_expr");
1248
1248
12491249 // Cast it to the right type (takes no arguments, returns a double) so we
12501250 // can call it as a native function.
12511251 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
12881288 //===----------------------------------------------------------------------===//
12891289
12901290 /// putchard - putchar that takes a double and returns 0.
1291 extern "C"
1291 extern "C"
12921292 double putchard(double X) {
12931293 putchar((char)X);
12941294 return 0;
12951295 }
12961296
12971297 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1298 extern "C"
1298 extern "C"
12991299 double printd(double X) {
13001300 printf("%f", X);
13011301 return 0;
13021302 }
13031303
1304 extern "C"
1304 extern "C"
13051305 double printlf() {
13061306 printf("\n");
13071307 return 0;
13381338
13391339 return 0;
13401340 }
1341
3737
3838 // primary
3939 tok_identifier = -4, tok_number = -5,
40
40
4141 // control
4242 tok_if = -6, tok_then = -7, tok_else = -8,
4343 tok_for = -9, tok_in = -10,
44
44
4545 // operators
4646 tok_binary = -11, tok_unary = -12,
47
47
4848 // var definition
4949 tok_var = -13
5050 };
9393 // Comment until end of line.
9494 do LastChar = getchar();
9595 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
96
96
9797 if (LastChar != EOF)
9898 return gettok();
9999 }
100
100
101101 // Check for end of file. Don't eat the EOF.
102102 if (LastChar == EOF)
103103 return tok_eof;
138138
139139 /// UnaryExprAST - Expression class for a unary operator.
140140 struct UnaryExprAST : public ExprAST {
141 UnaryExprAST(char Opcode, std::unique_ptr Operand)
141 UnaryExprAST(char Opcode, std::unique_ptr Operand)
142142 : Opcode(std::move(Opcode)), Operand(std::move(Operand)) {}
143143
144144 Value *IRGen(IRGenContext &C) const override;
150150 /// BinaryExprAST - Expression class for a binary operator.
151151 struct BinaryExprAST : public ExprAST {
152152 BinaryExprAST(char Op, std::unique_ptr LHS,
153 std::unique_ptr RHS)
153 std::unique_ptr RHS)
154154 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
155155
156156 Value *IRGen(IRGenContext &C) const override;
222222
223223 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
224224 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
225
225
226226 char getOperatorName() const {
227227 assert(isUnaryOp() || isBinaryOp());
228228 return Name[Name.size()-1];
266266 static int GetTokPrecedence() {
267267 if (!isascii(CurTok))
268268 return -1;
269
269
270270 // Make sure it's a declared binop.
271271 int TokPrec = BinopPrecedence[CurTok];
272272 if (TokPrec <= 0) return -1;
292292 /// ::= identifier '(' expression* ')'
293293 static std::unique_ptr ParseIdentifierExpr() {
294294 std::string IdName = IdentifierStr;
295
295
296296 getNextToken(); // eat identifier.
297
297
298298 if (CurTok != '(') // Simple variable ref.
299299 return llvm::make_unique(IdName);
300
300
301301 // Call.
302302 getNextToken(); // eat (
303303 std::vector> Args;
317317
318318 // Eat the ')'.
319319 getNextToken();
320
320
321321 return llvm::make_unique(IdName, std::move(Args));
322322 }
323323
334334 auto V = ParseExpression();
335335 if (!V)
336336 return nullptr;
337
337
338338 if (CurTok != ')')
339339 return ErrorU("expected ')'");
340340 getNextToken(); // eat ).
344344 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
345345 static std::unique_ptr ParseIfExpr() {
346346 getNextToken(); // eat the if.
347
347
348348 // condition.
349349 auto Cond = ParseExpression();
350350 if (!Cond)
351351 return nullptr;
352
352
353353 if (CurTok != tok_then)
354354 return ErrorU("expected then");
355355 getNextToken(); // eat the then
356
356
357357 auto Then = ParseExpression();
358358 if (!Then)
359359 return nullptr;
360
360
361361 if (CurTok != tok_else)
362362 return ErrorU("expected else");
363
363
364364 getNextToken();
365
365
366366 auto Else = ParseExpression();
367367 if (!Else)
368368 return nullptr;
369
369
370370 return llvm::make_unique(std::move(Cond), std::move(Then),
371371 std::move(Else));
372372 }
377377
378378 if (CurTok != tok_identifier)
379379 return ErrorU("expected identifier after for");
380
380
381381 std::string IdName = IdentifierStr;
382382 getNextToken(); // eat identifier.
383
383
384384 if (CurTok != '=')
385385 return ErrorU("expected '=' after for");
386386 getNextToken(); // eat '='.
387
388
387
388
389389 auto Start = ParseExpression();
390390 if (!Start)
391391 return nullptr;
392392 if (CurTok != ',')
393393 return ErrorU("expected ',' after for start value");
394394 getNextToken();
395
395
396396 auto End = ParseExpression();
397397 if (!End)
398398 return nullptr;
399
399
400400 // The step value is optional.
401401 std::unique_ptr Step;
402402 if (CurTok == ',') {
405405 if (!Step)
406406 return nullptr;
407407 }
408
408
409409 if (CurTok != tok_in)
410410 return ErrorU("expected 'in' after for");
411411 getNextToken(); // eat 'in'.
412
412
413413 auto Body = ParseExpression();
414414 if (Body)
415415 return nullptr;
418418 std::move(Step), std::move(Body));
419419 }
420420
421 /// varexpr ::= 'var' identifier ('=' expression)?
421 /// varexpr ::= 'var' identifier ('=' expression)?
422422 // (',' identifier ('=' expression)?)* 'in' expression
423423 static std::unique_ptr ParseVarExpr() {
424424 getNextToken(); // eat the var.
428428 // At least one variable name is required.
429429 if (CurTok != tok_identifier)
430430 return ErrorU("expected identifier after var");
431
431
432432 while (1) {
433433 std::string Name = IdentifierStr;
434434 getNextToken(); // eat identifier.
437437 std::unique_ptr Init;
438438 if (CurTok == '=') {
439439 getNextToken(); // eat the '='.
440
440
441441 Init = ParseExpression();
442442 if (!Init)
443443 return nullptr;
444444 }
445
445
446446 VarBindings.push_back(VarExprAST::Binding(Name, std::move(Init)));
447
447
448448 // End of var list, exit loop.
449449 if (CurTok != ',') break;
450450 getNextToken(); // eat the ','.
451
451
452452 if (CurTok != tok_identifier)
453453 return ErrorU("expected identifier list after var");
454454 }
455
455
456456 // At this point, we have to have 'in'.
457457 if (CurTok != tok_in)
458458 return ErrorU("expected 'in' keyword after 'var'");
459459 getNextToken(); // eat 'in'.
460
460
461461 auto Body = ParseExpression();
462462 if (!Body)
463463 return nullptr;
464
464
465465 return llvm::make_unique(std::move(VarBindings), std::move(Body));
466466 }
467467
491491 // If the current token is not an operator, it must be a primary expr.
492492 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
493493 return ParsePrimary();
494
494
495495 // If this is a unary operator, read it.
496496 int Opc = CurTok;
497497 getNextToken();
507507 // If this is a binop, find its precedence.
508508 while (1) {
509509 int TokPrec = GetTokPrecedence();
510
510
511511 // If this is a binop that binds at least as tightly as the current binop,
512512 // consume it, otherwise we are done.
513513 if (TokPrec < ExprPrec)
514514 return LHS;
515
515
516516 // Okay, we know this is a binop.
517517 int BinOp = CurTok;
518518 getNextToken(); // eat binop
519
519
520520 // Parse the unary expression after the binary operator.
521521 auto RHS = ParseUnary();
522522 if (!RHS)
523523 return nullptr;
524
524
525525 // If BinOp binds less tightly with RHS than the operator after RHS, let
526526 // the pending operator take RHS as its LHS.
527527 int NextPrec = GetTokPrecedence();
530530 if (!RHS)
531531 return nullptr;
532532 }
533
533
534534 // Merge LHS/RHS.
535535 LHS = llvm::make_unique(BinOp, std::move(LHS), std::move(RHS));
536536 }
543543 auto LHS = ParseUnary();
544544 if (!LHS)
545545 return nullptr;
546
546
547547 return ParseBinOpRHS(0, std::move(LHS));
548548 }
549549
553553 /// ::= unary LETTER (id)
554554 static std::unique_ptr ParsePrototype() {
555555 std::string FnName;
556
556
557557 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
558558 unsigned BinaryPrecedence = 30;
559
559
560560 switch (CurTok) {
561561 default:
562562 return ErrorU("Expected function name in prototype");
582582 FnName += (char)CurTok;
583583 Kind = 2;
584584 getNextToken();
585
585
586586 // Read the precedence if present.
587587 if (CurTok == tok_number) {
588588 if (NumVal < 1 || NumVal > 100)
592592 }
593593 break;
594594 }
595
595
596596 if (CurTok != '(')
597597 return ErrorU("Expected '(' in prototype");
598
598
599599 std::vector ArgNames;
600600 while (getNextToken() == tok_identifier)
601601 ArgNames.push_back(IdentifierStr);
602602 if (CurTok != ')')
603603 return ErrorU("Expected ')' in prototype");
604
604
605605 // success.
606606 getNextToken(); // eat ')'.
607
607
608608 // Verify right number of names for operator.
609609 if (Kind && ArgNames.size() != Kind)
610610 return ErrorU("Invalid number of operands for operator");
611
611
612612 return llvm::make_unique(FnName, std::move(ArgNames), Kind != 0,
613613 BinaryPrecedence);
614614 }
689689 PrototypeAST* getPrototypeAST(const std::string &Name);
690690 private:
691691 typedef std::map> PrototypeMap;
692
692
693693 LLVMContext &Context;
694694 std::unique_ptr TM;
695
695
696696 PrototypeMap Prototypes;
697697 };
698698
793793 }
794794 return ErrorP("Unknown variable name");
795795 }
796
796
797797 Value *L = LHS->IRGen(C);
798798 Value *R = RHS->IRGen(C);
799799 if (!L || !R) return nullptr;
800
800
801801 switch (Op) {
802802 case '+': return C.getBuilder().CreateFAdd(L, R, "addtmp");
803803 case '-': return C.getBuilder().CreateFSub(L, R, "subtmp");
810810 "booltmp");
811811 default: break;
812812 }
813
813
814814 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
815815 // a call to it.
816816 std::string FnName = MakeLegalFunctionName(std::string("binary")+Op);
818818 Value *Ops[] = { L, R };
819819 return C.getBuilder().CreateCall(F, Ops, "binop");
820820 }
821
821
822822 return ErrorP("Unknown binary operator");
823823 }
824824
834834 ArgsV.push_back(Args[i]->IRGen(C));
835835 if (!ArgsV.back()) return nullptr;
836836 }
837
837
838838 return C.getBuilder().CreateCall(CalleeF, ArgsV, "calltmp");
839839 }
840840
844844 Value *IfExprAST::IRGen(IRGenContext &C) const {
845845 Value *CondV = Cond->IRGen(C);
846846 if (!CondV) return nullptr;
847
847
848848 // Convert condition to a bool by comparing equal to 0.0.
849 ConstantFP *FPZero =
849 ConstantFP *FPZero =
850850 ConstantFP::get(C.getLLVMContext(), APFloat(0.0));
851851 CondV = C.getBuilder().CreateFCmpONE(CondV, FPZero, "ifcond");
852
852
853853 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
854
854
855855 // Create blocks for the then and else cases. Insert the 'then' block at the
856856 // end of the function.
857857 BasicBlock *ThenBB = BasicBlock::Create(C.getLLVMContext(), "then", TheFunction);
858858 BasicBlock *ElseBB = BasicBlock::Create(C.getLLVMContext(), "else");
859859 BasicBlock *MergeBB = BasicBlock::Create(C.getLLVMContext(), "ifcont");
860
860
861861 C.getBuilder().CreateCondBr(CondV, ThenBB, ElseBB);
862
862
863863 // Emit then value.
864864 C.getBuilder().SetInsertPoint(ThenBB);
865
865
866866 Value *ThenV = Then->IRGen(C);
867867 if (!ThenV) return nullptr;
868
868
869869 C.getBuilder().CreateBr(MergeBB);
870870 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
871871 ThenBB = C.getBuilder().GetInsertBlock();
872
872
873873 // Emit else block.
874874 TheFunction->getBasicBlockList().push_back(ElseBB);
875875 C.getBuilder().SetInsertPoint(ElseBB);
876
876
877877 Value *ElseV = Else->IRGen(C);
878878 if (!ElseV) return nullptr;
879
879
880880 C.getBuilder().CreateBr(MergeBB);
881881 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
882882 ElseBB = C.getBuilder().GetInsertBlock();
883
883
884884 // Emit merge block.
885885 TheFunction->getBasicBlockList().push_back(MergeBB);
886886 C.getBuilder().SetInsertPoint(MergeBB);
887887 PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
888888 "iftmp");
889
889
890890 PN->addIncoming(ThenV, ThenBB);
891891 PN->addIncoming(ElseV, ElseBB);
892892 return PN;
899899 // start = startexpr
900900 // store start -> var
901901 // goto loop
902 // loop:
902 // loop:
903903 // ...
904904 // bodyexpr
905905 // ...
912912 // store nextvar -> var
913913 // br endcond, loop, endloop
914914 // outloop:
915
915
916916 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
917917
918918 // Create an alloca for the variable in the entry block.
919919 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
920
920
921921 // Emit the start code first, without 'variable' in scope.
922922 Value *StartVal = Start->IRGen(C);
923923 if (!StartVal) return nullptr;
924
924
925925 // Store the value into the alloca.
926926 C.getBuilder().CreateStore(StartVal, Alloca);
927
927
928928 // Make the new basic block for the loop header, inserting after current
929929 // block.
930930 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
931
931
932932 // Insert an explicit fall through from the current block to the LoopBB.
933933 C.getBuilder().CreateBr(LoopBB);
934934
935935 // Start insertion in LoopBB.
936936 C.getBuilder().SetInsertPoint(LoopBB);
937
937
938938 // Within the loop, the variable is defined equal to the PHI node. If it
939939 // shadows an existing variable, we have to restore it, so save it now.
940940 AllocaInst *OldVal = C.NamedValues[VarName];
941941 C.NamedValues[VarName] = Alloca;
942
942
943943 // Emit the body of the loop. This, like any other expr, can change the
944944 // current BB. Note that we ignore the value computed by the body, but don't
945945 // allow an error.
946946 if (!Body->IRGen(C))
947947 return nullptr;
948
948
949949 // Emit the step value.
950950 Value *StepVal;
951951 if (Step) {
955955 // If not specified, use 1.0.
956956 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
957957 }
958
958
959959 // Compute the end condition.
960960 Value *EndCond = End->IRGen(C);
961961 if (EndCond == 0) return EndCond;
962
962
963963 // Reload, increment, and restore the alloca. This handles the case where
964964 // the body of the loop mutates the variable.
965965 Value *CurVar = C.getBuilder().CreateLoad(Alloca, VarName.c_str());
966966 Value *NextVar = C.getBuilder().CreateFAdd(CurVar, StepVal, "nextvar");
967967 C.getBuilder().CreateStore(NextVar, Alloca);
968
968
969969 // Convert condition to a bool by comparing equal to 0.0.
970 EndCond = C.getBuilder().CreateFCmpONE(EndCond,
970 EndCond = C.getBuilder().CreateFCmpONE(EndCond,
971971 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
972972 "loopcond");
973
973
974974 // Create the "after loop" block and insert it.
975975 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
976
976
977977 // Insert the conditional branch into the end of LoopEndBB.
978978 C.getBuilder().CreateCondBr(EndCond, LoopBB, AfterBB);
979
979
980980 // Any new code will be inserted in AfterBB.
981981 C.getBuilder().SetInsertPoint(AfterBB);
982
982
983983 // Restore the unshadowed variable.
984984 if (OldVal)
985985 C.NamedValues[VarName] = OldVal;
986986 else
987987 C.NamedValues.erase(VarName);
988988
989
989
990990 // for expr always returns 0.0.
991991 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
992992 }
993993
994994 Value *VarExprAST::IRGen(IRGenContext &C) const {
995995 std::vector OldBindings;
996
996
997997 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
998998
999999 // Register all variables and emit their initializer.
10001000 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i) {
10011001 auto &VarName = VarBindings[i].first;
10021002 auto &Init = VarBindings[i].second;
1003
1003
10041004 // Emit the initializer before adding the variable to scope, this prevents
10051005 // the initializer from referencing the variable itself, and permits stuff
10061006 // like this:
10121012 if (!InitVal) return nullptr;
10131013 } else // If not specified, use 0.0.
10141014 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1015
1015
10161016 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
10171017 C.getBuilder().CreateStore(InitVal, Alloca);
10181018
10191019 // Remember the old variable binding so that we can restore the binding when
10201020 // we unrecurse.
10211021 OldBindings.push_back(C.NamedValues[VarName]);
1022
1022
10231023 // Remember this binding.
10241024 C.NamedValues[VarName] = Alloca;
10251025 }
1026
1026
10271027 // Codegen the body, now that all vars are in scope.
10281028 Value *BodyVal = Body->IRGen(C);
10291029 if (!BodyVal) return nullptr;
1030
1030
10311031 // Pop all our variables from scope.
10321032 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i)
10331033 C.NamedValues[VarBindings[i].first] = OldBindings[i];
10401040 std::string FnName = MakeLegalFunctionName(Name);
10411041
10421042 // Make the function type: double(double,double) etc.
1043 std::vector Doubles(Args.size(),
1043 std::vector Doubles(Args.size(),
10441044 Type::getDoubleTy(getGlobalContext()));
10451045 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
10461046 Doubles, false);
10531053 // Delete the one we just made and get the existing one.
10541054 F->eraseFromParent();
10551055 F = C.getM().getFunction(Name);
1056
1056
10571057 // If F already has a body, reject this.
10581058 if (!F->empty()) {
10591059 ErrorP("redefinition of function");
10601060 return nullptr;
10611061 }
1062
1062
10631063 // If F took a different number of args, reject.
10641064 if (F->arg_size() != Args.size()) {
10651065 ErrorP("redefinition of function with different # args");
10661066 return nullptr;
10671067 }
10681068 }
1069
1069
10701070 // Set names for all arguments.
10711071 unsigned Idx = 0;
10721072 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
10731073 ++AI, ++Idx)
10741074 AI->setName(Args[Idx]);
1075
1075
10761076 return F;
10771077 }
10781078
10941094
10951095 Function *FunctionAST::IRGen(IRGenContext &C) const {
10961096 C.NamedValues.clear();
1097
1097
10981098 Function *TheFunction = Proto->IRGen(C);
10991099 if (!TheFunction)
11001100 return nullptr;
1101
1101
11021102 // If this is an operator, install it.
11031103 if (Proto->isBinaryOp())
11041104 BinopPrecedence[Proto->getOperatorName()] = Proto->Precedence;
1105
1105
11061106 // Create a new basic block to start insertion into.
11071107 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
11081108 C.getBuilder().SetInsertPoint(BB);
1109
1109
11101110 // Add all arguments to the symbol table and create their allocas.
11111111 Proto->CreateArgumentAllocas(TheFunction, C);
11121112
11191119
11201120 return TheFunction;
11211121 }
1122
1122
11231123 // Error reading body, remove function.
11241124 TheFunction->eraseFromParent();
11251125
12761276
12771277 // Get the address of the JIT'd function in memory.
12781278 auto ExprSymbol = J.findUnmangledSymbol("__anon_expr");
1279
1279
12801280 // Cast it to the right type (takes no arguments, returns a double) so we
12811281 // can call it as a native function.
12821282 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
13191319 //===----------------------------------------------------------------------===//
13201320
13211321 /// putchard - putchar that takes a double and returns 0.
1322 extern "C"
1322 extern "C"
13231323 double putchard(double X) {
13241324 putchar((char)X);
13251325 return 0;
13261326 }
13271327
13281328 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1329 extern "C"
1329 extern "C"
13301330 double printd(double X) {
13311331 printf("%f", X);
13321332 return 0;
13331333 }
13341334
1335 extern "C"
1335 extern "C"
13361336 double printlf() {
13371337 printf("\n");
13381338 return 0;
13691369
13701370 return 0;
13711371 }
1372