1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/ADT/Triple.h"
3 #include "llvm/Analysis/Passes.h"
4 #include "llvm/ExecutionEngine/ExecutionEngine.h"
5 #include "llvm/ExecutionEngine/MCJIT.h"
6 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
7 #include "llvm/IR/DIBuilder.h"
8 #include "llvm/IR/DataLayout.h"
9 #include "llvm/IR/DerivedTypes.h"
10 #include "llvm/IR/IRBuilder.h"
11 #include "llvm/IR/LLVMContext.h"
12 #include "llvm/IR/LegacyPassManager.h"
13 #include "llvm/IR/Module.h"
14 #include "llvm/IR/Verifier.h"
15 #include "llvm/Support/Host.h"
16 #include "llvm/Support/TargetSelect.h"
17 #include "llvm/Transforms/Scalar.h"
26 //===----------------------------------------------------------------------===//
28 //===----------------------------------------------------------------------===//
30 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
31 // of these for known things.
58 std::string getTokName(int Tok) {
87 return std::string(1, (char)Tok);
94 static IRBuilder<> Builder(getGlobalContext());
98 std::vector<DIScope *> LexicalBlocks;
99 std::map<const PrototypeAST *, DIScope> FnScopeMap;
101 void emitLocation(ExprAST *AST);
102 DIType getDoubleTy();
105 static std::string IdentifierStr; // Filled in if tok_identifier
106 static double NumVal; // Filled in if tok_number
107 struct SourceLocation {
111 static SourceLocation CurLoc;
112 static SourceLocation LexLoc = { 1, 0 };
114 static int advance() {
115 int LastChar = getchar();
117 if (LastChar == '\n' || LastChar == '\r') {
125 /// gettok - Return the next token from standard input.
126 static int gettok() {
127 static int LastChar = ' ';
129 // Skip any whitespace.
130 while (isspace(LastChar))
131 LastChar = advance();
135 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
136 IdentifierStr = LastChar;
137 while (isalnum((LastChar = advance())))
138 IdentifierStr += LastChar;
140 if (IdentifierStr == "def")
142 if (IdentifierStr == "extern")
144 if (IdentifierStr == "if")
146 if (IdentifierStr == "then")
148 if (IdentifierStr == "else")
150 if (IdentifierStr == "for")
152 if (IdentifierStr == "in")
154 if (IdentifierStr == "binary")
156 if (IdentifierStr == "unary")
158 if (IdentifierStr == "var")
160 return tok_identifier;
163 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
167 LastChar = advance();
168 } while (isdigit(LastChar) || LastChar == '.');
170 NumVal = strtod(NumStr.c_str(), 0);
174 if (LastChar == '#') {
175 // Comment until end of line.
177 LastChar = advance();
178 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
184 // Check for end of file. Don't eat the EOF.
188 // Otherwise, just return the character as its ascii value.
189 int ThisChar = LastChar;
190 LastChar = advance();
194 //===----------------------------------------------------------------------===//
195 // Abstract Syntax Tree (aka Parse Tree)
196 //===----------------------------------------------------------------------===//
199 std::ostream &indent(std::ostream &O, int size) {
200 return O << std::string(size, ' ');
203 /// ExprAST - Base class for all expression nodes.
208 int getLine() const { return Loc.Line; }
209 int getCol() const { return Loc.Col; }
210 ExprAST(SourceLocation Loc = CurLoc) : Loc(Loc) {}
211 virtual std::ostream &dump(std::ostream &out, int ind) {
212 return out << ':' << getLine() << ':' << getCol() << '\n';
214 virtual ~ExprAST() {}
215 virtual Value *Codegen() = 0;
218 /// NumberExprAST - Expression class for numeric literals like "1.0".
219 class NumberExprAST : public ExprAST {
223 NumberExprAST(double val) : Val(val) {}
224 std::ostream &dump(std::ostream &out, int ind) override {
225 return ExprAST::dump(out << Val, ind);
227 Value *Codegen() override;
230 /// VariableExprAST - Expression class for referencing a variable, like "a".
231 class VariableExprAST : public ExprAST {
235 VariableExprAST(SourceLocation Loc, const std::string &name)
236 : ExprAST(Loc), Name(name) {}
237 const std::string &getName() const { return Name; }
238 std::ostream &dump(std::ostream &out, int ind) override {
239 return ExprAST::dump(out << Name, ind);
241 Value *Codegen() override;
244 /// UnaryExprAST - Expression class for a unary operator.
245 class UnaryExprAST : public ExprAST {
250 UnaryExprAST(char opcode, ExprAST *operand)
251 : Opcode(opcode), Operand(operand) {}
252 std::ostream &dump(std::ostream &out, int ind) override {
253 ExprAST::dump(out << "unary" << Opcode, ind);
254 Operand->dump(out, ind + 1);
257 Value *Codegen() override;
260 /// BinaryExprAST - Expression class for a binary operator.
261 class BinaryExprAST : public ExprAST {
266 BinaryExprAST(SourceLocation Loc, char op, ExprAST *lhs, ExprAST *rhs)
267 : ExprAST(Loc), Op(op), LHS(lhs), RHS(rhs) {}
268 std::ostream &dump(std::ostream &out, int ind) override {
269 ExprAST::dump(out << "binary" << Op, ind);
270 LHS->dump(indent(out, ind) << "LHS:", ind + 1);
271 RHS->dump(indent(out, ind) << "RHS:", ind + 1);
274 Value *Codegen() override;
277 /// CallExprAST - Expression class for function calls.
278 class CallExprAST : public ExprAST {
280 std::vector<ExprAST *> Args;
283 CallExprAST(SourceLocation Loc, const std::string &callee,
284 std::vector<ExprAST *> &args)
285 : ExprAST(Loc), Callee(callee), Args(args) {}
286 std::ostream &dump(std::ostream &out, int ind) override {
287 ExprAST::dump(out << "call " << Callee, ind);
288 for (ExprAST *Arg : Args)
289 Arg->dump(indent(out, ind + 1), ind + 1);
292 Value *Codegen() override;
295 /// IfExprAST - Expression class for if/then/else.
296 class IfExprAST : public ExprAST {
297 ExprAST *Cond, *Then, *Else;
300 IfExprAST(SourceLocation Loc, ExprAST *cond, ExprAST *then, ExprAST *_else)
301 : ExprAST(Loc), Cond(cond), Then(then), Else(_else) {}
302 std::ostream &dump(std::ostream &out, int ind) override {
303 ExprAST::dump(out << "if", ind);
304 Cond->dump(indent(out, ind) << "Cond:", ind + 1);
305 Then->dump(indent(out, ind) << "Then:", ind + 1);
306 Else->dump(indent(out, ind) << "Else:", ind + 1);
309 Value *Codegen() override;
312 /// ForExprAST - Expression class for for/in.
313 class ForExprAST : public ExprAST {
315 ExprAST *Start, *End, *Step, *Body;
318 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
319 ExprAST *step, ExprAST *body)
320 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
321 std::ostream &dump(std::ostream &out, int ind) override {
322 ExprAST::dump(out << "for", ind);
323 Start->dump(indent(out, ind) << "Cond:", ind + 1);
324 End->dump(indent(out, ind) << "End:", ind + 1);
325 Step->dump(indent(out, ind) << "Step:", ind + 1);
326 Body->dump(indent(out, ind) << "Body:", ind + 1);
329 Value *Codegen() override;
332 /// VarExprAST - Expression class for var/in
333 class VarExprAST : public ExprAST {
334 std::vector<std::pair<std::string, ExprAST *> > VarNames;
338 VarExprAST(const std::vector<std::pair<std::string, ExprAST *> > &varnames,
340 : VarNames(varnames), Body(body) {}
342 std::ostream &dump(std::ostream &out, int ind) override {
343 ExprAST::dump(out << "var", ind);
344 for (const auto &NamedVar : VarNames)
345 NamedVar.second->dump(indent(out, ind) << NamedVar.first << ':', ind + 1);
346 Body->dump(indent(out, ind) << "Body:", ind + 1);
349 Value *Codegen() override;
352 /// PrototypeAST - This class represents the "prototype" for a function,
353 /// which captures its argument names as well as if it is an operator.
356 std::vector<std::string> Args;
358 unsigned Precedence; // Precedence if a binary op.
362 PrototypeAST(SourceLocation Loc, const std::string &name,
363 const std::vector<std::string> &args, bool isoperator = false,
365 : Name(name), Args(args), isOperator(isoperator), Precedence(prec),
368 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
369 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
371 char getOperatorName() const {
372 assert(isUnaryOp() || isBinaryOp());
373 return Name[Name.size() - 1];
376 unsigned getBinaryPrecedence() const { return Precedence; }
380 void CreateArgumentAllocas(Function *F);
381 const std::vector<std::string> &getArgs() const { return Args; }
384 /// FunctionAST - This class represents a function definition itself.
390 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
392 std::ostream &dump(std::ostream &out, int ind) {
393 indent(out, ind) << "FunctionAST\n";
395 indent(out, ind) << "Body:";
396 return Body ? Body->dump(out, ind) : out << "null\n";
401 } // end anonymous namespace
403 //===----------------------------------------------------------------------===//
405 //===----------------------------------------------------------------------===//
407 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
408 /// token the parser is looking at. getNextToken reads another token from the
409 /// lexer and updates CurTok with its results.
411 static int getNextToken() { return CurTok = gettok(); }
413 /// BinopPrecedence - This holds the precedence for each binary operator that is
415 static std::map<char, int> BinopPrecedence;
417 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
418 static int GetTokPrecedence() {
419 if (!isascii(CurTok))
422 // Make sure it's a declared binop.
423 int TokPrec = BinopPrecedence[CurTok];
429 /// Error* - These are little helper functions for error handling.
430 ExprAST *Error(const char *Str) {
431 fprintf(stderr, "Error: %s\n", Str);
434 PrototypeAST *ErrorP(const char *Str) {
438 FunctionAST *ErrorF(const char *Str) {
443 static ExprAST *ParseExpression();
447 /// ::= identifier '(' expression* ')'
448 static ExprAST *ParseIdentifierExpr() {
449 std::string IdName = IdentifierStr;
451 SourceLocation LitLoc = CurLoc;
453 getNextToken(); // eat identifier.
455 if (CurTok != '(') // Simple variable ref.
456 return new VariableExprAST(LitLoc, IdName);
459 getNextToken(); // eat (
460 std::vector<ExprAST *> Args;
463 ExprAST *Arg = ParseExpression();
472 return Error("Expected ')' or ',' in argument list");
480 return new CallExprAST(LitLoc, IdName, Args);
483 /// numberexpr ::= number
484 static ExprAST *ParseNumberExpr() {
485 ExprAST *Result = new NumberExprAST(NumVal);
486 getNextToken(); // consume the number
490 /// parenexpr ::= '(' expression ')'
491 static ExprAST *ParseParenExpr() {
492 getNextToken(); // eat (.
493 ExprAST *V = ParseExpression();
498 return Error("expected ')'");
499 getNextToken(); // eat ).
503 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
504 static ExprAST *ParseIfExpr() {
505 SourceLocation IfLoc = CurLoc;
507 getNextToken(); // eat the if.
510 ExprAST *Cond = ParseExpression();
514 if (CurTok != tok_then)
515 return Error("expected then");
516 getNextToken(); // eat the then
518 ExprAST *Then = ParseExpression();
522 if (CurTok != tok_else)
523 return Error("expected else");
527 ExprAST *Else = ParseExpression();
531 return new IfExprAST(IfLoc, Cond, Then, Else);
534 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
535 static ExprAST *ParseForExpr() {
536 getNextToken(); // eat the for.
538 if (CurTok != tok_identifier)
539 return Error("expected identifier after for");
541 std::string IdName = IdentifierStr;
542 getNextToken(); // eat identifier.
545 return Error("expected '=' after for");
546 getNextToken(); // eat '='.
548 ExprAST *Start = ParseExpression();
552 return Error("expected ',' after for start value");
555 ExprAST *End = ParseExpression();
559 // The step value is optional.
563 Step = ParseExpression();
568 if (CurTok != tok_in)
569 return Error("expected 'in' after for");
570 getNextToken(); // eat 'in'.
572 ExprAST *Body = ParseExpression();
576 return new ForExprAST(IdName, Start, End, Step, Body);
579 /// varexpr ::= 'var' identifier ('=' expression)?
580 // (',' identifier ('=' expression)?)* 'in' expression
581 static ExprAST *ParseVarExpr() {
582 getNextToken(); // eat the var.
584 std::vector<std::pair<std::string, ExprAST *> > VarNames;
586 // At least one variable name is required.
587 if (CurTok != tok_identifier)
588 return Error("expected identifier after var");
591 std::string Name = IdentifierStr;
592 getNextToken(); // eat identifier.
594 // Read the optional initializer.
597 getNextToken(); // eat the '='.
599 Init = ParseExpression();
604 VarNames.push_back(std::make_pair(Name, Init));
606 // End of var list, exit loop.
609 getNextToken(); // eat the ','.
611 if (CurTok != tok_identifier)
612 return Error("expected identifier list after var");
615 // At this point, we have to have 'in'.
616 if (CurTok != tok_in)
617 return Error("expected 'in' keyword after 'var'");
618 getNextToken(); // eat 'in'.
620 ExprAST *Body = ParseExpression();
624 return new VarExprAST(VarNames, Body);
628 /// ::= identifierexpr
634 static ExprAST *ParsePrimary() {
637 return Error("unknown token when expecting an expression");
639 return ParseIdentifierExpr();
641 return ParseNumberExpr();
643 return ParseParenExpr();
645 return ParseIfExpr();
647 return ParseForExpr();
649 return ParseVarExpr();
656 static ExprAST *ParseUnary() {
657 // If the current token is not an operator, it must be a primary expr.
658 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
659 return ParsePrimary();
661 // If this is a unary operator, read it.
664 if (ExprAST *Operand = ParseUnary())
665 return new UnaryExprAST(Opc, Operand);
671 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
672 // If this is a binop, find its precedence.
674 int TokPrec = GetTokPrecedence();
676 // If this is a binop that binds at least as tightly as the current binop,
677 // consume it, otherwise we are done.
678 if (TokPrec < ExprPrec)
681 // Okay, we know this is a binop.
683 SourceLocation BinLoc = CurLoc;
684 getNextToken(); // eat binop
686 // Parse the unary expression after the binary operator.
687 ExprAST *RHS = ParseUnary();
691 // If BinOp binds less tightly with RHS than the operator after RHS, let
692 // the pending operator take RHS as its LHS.
693 int NextPrec = GetTokPrecedence();
694 if (TokPrec < NextPrec) {
695 RHS = ParseBinOpRHS(TokPrec + 1, RHS);
701 LHS = new BinaryExprAST(BinLoc, BinOp, LHS, RHS);
706 /// ::= unary binoprhs
708 static ExprAST *ParseExpression() {
709 ExprAST *LHS = ParseUnary();
713 return ParseBinOpRHS(0, LHS);
717 /// ::= id '(' id* ')'
718 /// ::= binary LETTER number? (id, id)
719 /// ::= unary LETTER (id)
720 static PrototypeAST *ParsePrototype() {
723 SourceLocation FnLoc = CurLoc;
725 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
726 unsigned BinaryPrecedence = 30;
730 return ErrorP("Expected function name in prototype");
732 FnName = IdentifierStr;
738 if (!isascii(CurTok))
739 return ErrorP("Expected unary operator");
741 FnName += (char)CurTok;
747 if (!isascii(CurTok))
748 return ErrorP("Expected binary operator");
750 FnName += (char)CurTok;
754 // Read the precedence if present.
755 if (CurTok == tok_number) {
756 if (NumVal < 1 || NumVal > 100)
757 return ErrorP("Invalid precedecnce: must be 1..100");
758 BinaryPrecedence = (unsigned)NumVal;
765 return ErrorP("Expected '(' in prototype");
767 std::vector<std::string> ArgNames;
768 while (getNextToken() == tok_identifier)
769 ArgNames.push_back(IdentifierStr);
771 return ErrorP("Expected ')' in prototype");
774 getNextToken(); // eat ')'.
776 // Verify right number of names for operator.
777 if (Kind && ArgNames.size() != Kind)
778 return ErrorP("Invalid number of operands for operator");
780 return new PrototypeAST(FnLoc, FnName, ArgNames, Kind != 0, BinaryPrecedence);
783 /// definition ::= 'def' prototype expression
784 static FunctionAST *ParseDefinition() {
785 getNextToken(); // eat def.
786 PrototypeAST *Proto = ParsePrototype();
790 if (ExprAST *E = ParseExpression())
791 return new FunctionAST(Proto, E);
795 /// toplevelexpr ::= expression
796 static FunctionAST *ParseTopLevelExpr() {
797 SourceLocation FnLoc = CurLoc;
798 if (ExprAST *E = ParseExpression()) {
799 // Make an anonymous proto.
800 PrototypeAST *Proto =
801 new PrototypeAST(FnLoc, "main", std::vector<std::string>());
802 return new FunctionAST(Proto, E);
807 /// external ::= 'extern' prototype
808 static PrototypeAST *ParseExtern() {
809 getNextToken(); // eat extern.
810 return ParsePrototype();
813 //===----------------------------------------------------------------------===//
814 // Debug Info Support
815 //===----------------------------------------------------------------------===//
817 static DIBuilder *DBuilder;
819 DIType DebugInfo::getDoubleTy() {
823 DblTy = DBuilder->createBasicType("double", 64, 64, dwarf::DW_ATE_float);
827 void DebugInfo::emitLocation(ExprAST *AST) {
829 return Builder.SetCurrentDebugLocation(DebugLoc());
831 if (LexicalBlocks.empty())
834 Scope = LexicalBlocks.back();
835 Builder.SetCurrentDebugLocation(
836 DebugLoc::get(AST->getLine(), AST->getCol(), DIScope(*Scope)));
839 static DICompositeType CreateFunctionType(unsigned NumArgs, DIFile Unit) {
840 SmallVector<Metadata *, 8> EltTys;
841 DIType DblTy = KSDbgInfo.getDoubleTy();
843 // Add the result type.
844 EltTys.push_back(DblTy);
846 for (unsigned i = 0, e = NumArgs; i != e; ++i)
847 EltTys.push_back(DblTy);
849 DITypeArray EltTypeArray = DBuilder->getOrCreateTypeArray(EltTys);
850 return DBuilder->createSubroutineType(Unit, EltTypeArray);
853 //===----------------------------------------------------------------------===//
855 //===----------------------------------------------------------------------===//
857 static Module *TheModule;
858 static std::map<std::string, AllocaInst *> NamedValues;
859 static legacy::FunctionPassManager *TheFPM;
861 Value *ErrorV(const char *Str) {
866 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
867 /// the function. This is used for mutable variables etc.
868 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
869 const std::string &VarName) {
870 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
871 TheFunction->getEntryBlock().begin());
872 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
876 Value *NumberExprAST::Codegen() {
877 KSDbgInfo.emitLocation(this);
878 return ConstantFP::get(getGlobalContext(), APFloat(Val));
881 Value *VariableExprAST::Codegen() {
882 // Look this variable up in the function.
883 Value *V = NamedValues[Name];
885 return ErrorV("Unknown variable name");
887 KSDbgInfo.emitLocation(this);
889 return Builder.CreateLoad(V, Name.c_str());
892 Value *UnaryExprAST::Codegen() {
893 Value *OperandV = Operand->Codegen();
897 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
899 return ErrorV("Unknown unary operator");
901 KSDbgInfo.emitLocation(this);
902 return Builder.CreateCall(F, OperandV, "unop");
905 Value *BinaryExprAST::Codegen() {
906 KSDbgInfo.emitLocation(this);
908 // Special case '=' because we don't want to emit the LHS as an expression.
910 // Assignment requires the LHS to be an identifier.
911 VariableExprAST *LHSE = dynamic_cast<VariableExprAST *>(LHS);
913 return ErrorV("destination of '=' must be a variable");
915 Value *Val = RHS->Codegen();
920 Value *Variable = NamedValues[LHSE->getName()];
922 return ErrorV("Unknown variable name");
924 Builder.CreateStore(Val, Variable);
928 Value *L = LHS->Codegen();
929 Value *R = RHS->Codegen();
930 if (L == 0 || R == 0)
935 return Builder.CreateFAdd(L, R, "addtmp");
937 return Builder.CreateFSub(L, R, "subtmp");
939 return Builder.CreateFMul(L, R, "multmp");
941 L = Builder.CreateFCmpULT(L, R, "cmptmp");
942 // Convert bool 0/1 to double 0.0 or 1.0
943 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
949 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
951 Function *F = TheModule->getFunction(std::string("binary") + Op);
952 assert(F && "binary operator not found!");
954 Value *Ops[] = { L, R };
955 return Builder.CreateCall(F, Ops, "binop");
958 Value *CallExprAST::Codegen() {
959 KSDbgInfo.emitLocation(this);
961 // Look up the name in the global module table.
962 Function *CalleeF = TheModule->getFunction(Callee);
964 return ErrorV("Unknown function referenced");
966 // If argument mismatch error.
967 if (CalleeF->arg_size() != Args.size())
968 return ErrorV("Incorrect # arguments passed");
970 std::vector<Value *> ArgsV;
971 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
972 ArgsV.push_back(Args[i]->Codegen());
973 if (ArgsV.back() == 0)
977 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
980 Value *IfExprAST::Codegen() {
981 KSDbgInfo.emitLocation(this);
983 Value *CondV = Cond->Codegen();
987 // Convert condition to a bool by comparing equal to 0.0.
988 CondV = Builder.CreateFCmpONE(
989 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
991 Function *TheFunction = Builder.GetInsertBlock()->getParent();
993 // Create blocks for the then and else cases. Insert the 'then' block at the
994 // end of the function.
996 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
997 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
998 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
1000 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
1003 Builder.SetInsertPoint(ThenBB);
1005 Value *ThenV = Then->Codegen();
1009 Builder.CreateBr(MergeBB);
1010 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
1011 ThenBB = Builder.GetInsertBlock();
1014 TheFunction->getBasicBlockList().push_back(ElseBB);
1015 Builder.SetInsertPoint(ElseBB);
1017 Value *ElseV = Else->Codegen();
1021 Builder.CreateBr(MergeBB);
1022 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
1023 ElseBB = Builder.GetInsertBlock();
1025 // Emit merge block.
1026 TheFunction->getBasicBlockList().push_back(MergeBB);
1027 Builder.SetInsertPoint(MergeBB);
1029 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
1031 PN->addIncoming(ThenV, ThenBB);
1032 PN->addIncoming(ElseV, ElseBB);
1036 Value *ForExprAST::Codegen() {
1038 // var = alloca double
1040 // start = startexpr
1041 // store start -> var
1049 // endcond = endexpr
1051 // curvar = load var
1052 // nextvar = curvar + step
1053 // store nextvar -> var
1054 // br endcond, loop, endloop
1057 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1059 // Create an alloca for the variable in the entry block.
1060 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1062 KSDbgInfo.emitLocation(this);
1064 // Emit the start code first, without 'variable' in scope.
1065 Value *StartVal = Start->Codegen();
1069 // Store the value into the alloca.
1070 Builder.CreateStore(StartVal, Alloca);
1072 // Make the new basic block for the loop header, inserting after current
1074 BasicBlock *LoopBB =
1075 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
1077 // Insert an explicit fall through from the current block to the LoopBB.
1078 Builder.CreateBr(LoopBB);
1080 // Start insertion in LoopBB.
1081 Builder.SetInsertPoint(LoopBB);
1083 // Within the loop, the variable is defined equal to the PHI node. If it
1084 // shadows an existing variable, we have to restore it, so save it now.
1085 AllocaInst *OldVal = NamedValues[VarName];
1086 NamedValues[VarName] = Alloca;
1088 // Emit the body of the loop. This, like any other expr, can change the
1089 // current BB. Note that we ignore the value computed by the body, but don't
1091 if (Body->Codegen() == 0)
1094 // Emit the step value.
1097 StepVal = Step->Codegen();
1101 // If not specified, use 1.0.
1102 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
1105 // Compute the end condition.
1106 Value *EndCond = End->Codegen();
1110 // Reload, increment, and restore the alloca. This handles the case where
1111 // the body of the loop mutates the variable.
1112 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
1113 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
1114 Builder.CreateStore(NextVar, Alloca);
1116 // Convert condition to a bool by comparing equal to 0.0.
1117 EndCond = Builder.CreateFCmpONE(
1118 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
1120 // Create the "after loop" block and insert it.
1121 BasicBlock *AfterBB =
1122 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
1124 // Insert the conditional branch into the end of LoopEndBB.
1125 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
1127 // Any new code will be inserted in AfterBB.
1128 Builder.SetInsertPoint(AfterBB);
1130 // Restore the unshadowed variable.
1132 NamedValues[VarName] = OldVal;
1134 NamedValues.erase(VarName);
1136 // for expr always returns 0.0.
1137 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
1140 Value *VarExprAST::Codegen() {
1141 std::vector<AllocaInst *> OldBindings;
1143 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1145 // Register all variables and emit their initializer.
1146 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
1147 const std::string &VarName = VarNames[i].first;
1148 ExprAST *Init = VarNames[i].second;
1150 // Emit the initializer before adding the variable to scope, this prevents
1151 // the initializer from referencing the variable itself, and permits stuff
1154 // var a = a in ... # refers to outer 'a'.
1157 InitVal = Init->Codegen();
1160 } else { // If not specified, use 0.0.
1161 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1164 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1165 Builder.CreateStore(InitVal, Alloca);
1167 // Remember the old variable binding so that we can restore the binding when
1169 OldBindings.push_back(NamedValues[VarName]);
1171 // Remember this binding.
1172 NamedValues[VarName] = Alloca;
1175 KSDbgInfo.emitLocation(this);
1177 // Codegen the body, now that all vars are in scope.
1178 Value *BodyVal = Body->Codegen();
1182 // Pop all our variables from scope.
1183 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1184 NamedValues[VarNames[i].first] = OldBindings[i];
1186 // Return the body computation.
1190 Function *PrototypeAST::Codegen() {
1191 // Make the function type: double(double,double) etc.
1192 std::vector<Type *> Doubles(Args.size(),
1193 Type::getDoubleTy(getGlobalContext()));
1195 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
1198 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
1200 // If F conflicted, there was already something named 'Name'. If it has a
1201 // body, don't allow redefinition or reextern.
1202 if (F->getName() != Name) {
1203 // Delete the one we just made and get the existing one.
1204 F->eraseFromParent();
1205 F = TheModule->getFunction(Name);
1207 // If F already has a body, reject this.
1209 ErrorF("redefinition of function");
1213 // If F took a different number of args, reject.
1214 if (F->arg_size() != Args.size()) {
1215 ErrorF("redefinition of function with different # args");
1220 // Set names for all arguments.
1222 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1224 AI->setName(Args[Idx]);
1226 // Create a subprogram DIE for this function.
1227 DIFile Unit = DBuilder->createFile(KSDbgInfo.TheCU.getFilename(),
1228 KSDbgInfo.TheCU.getDirectory());
1229 DIDescriptor FContext(Unit);
1230 unsigned LineNo = Line;
1231 unsigned ScopeLine = Line;
1232 DISubprogram SP = DBuilder->createFunction(
1233 FContext, Name, StringRef(), Unit, LineNo,
1234 CreateFunctionType(Args.size(), Unit), false /* internal linkage */,
1235 true /* definition */, ScopeLine, DIDescriptor::FlagPrototyped, false, F);
1237 KSDbgInfo.FnScopeMap[this] = (DIScope)SP;
1241 /// CreateArgumentAllocas - Create an alloca for each argument and register the
1242 /// argument in the symbol table so that references to it will succeed.
1243 void PrototypeAST::CreateArgumentAllocas(Function *F) {
1244 Function::arg_iterator AI = F->arg_begin();
1245 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1246 // Create an alloca for this variable.
1247 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1249 // Create a debug descriptor for the variable.
1250 DIScope *Scope = KSDbgInfo.LexicalBlocks.back();
1251 DIFile Unit = DBuilder->createFile(KSDbgInfo.TheCU.getFilename(),
1252 KSDbgInfo.TheCU.getDirectory());
1253 DIVariable D = DBuilder->createLocalVariable(dwarf::DW_TAG_arg_variable,
1254 *Scope, Args[Idx], Unit, Line,
1255 KSDbgInfo.getDoubleTy(), Idx);
1257 Instruction *Call = DBuilder->insertDeclare(
1258 Alloca, D, DBuilder->createExpression(), Builder.GetInsertBlock());
1259 Call->setDebugLoc(DebugLoc::get(Line, 0, *Scope));
1261 // Store the initial value into the alloca.
1262 Builder.CreateStore(AI, Alloca);
1264 // Add arguments to variable symbol table.
1265 NamedValues[Args[Idx]] = Alloca;
1269 Function *FunctionAST::Codegen() {
1270 NamedValues.clear();
1272 Function *TheFunction = Proto->Codegen();
1273 if (TheFunction == 0)
1276 // Push the current scope.
1277 KSDbgInfo.LexicalBlocks.push_back(&KSDbgInfo.FnScopeMap[Proto]);
1279 // Unset the location for the prologue emission (leading instructions with no
1280 // location in a function are considered part of the prologue and the debugger
1281 // will run past them when breaking on a function)
1282 KSDbgInfo.emitLocation(nullptr);
1284 // If this is an operator, install it.
1285 if (Proto->isBinaryOp())
1286 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
1288 // Create a new basic block to start insertion into.
1289 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1290 Builder.SetInsertPoint(BB);
1292 // Add all arguments to the symbol table and create their allocas.
1293 Proto->CreateArgumentAllocas(TheFunction);
1295 KSDbgInfo.emitLocation(Body);
1297 if (Value *RetVal = Body->Codegen()) {
1298 // Finish off the function.
1299 Builder.CreateRet(RetVal);
1301 // Pop off the lexical block for the function.
1302 KSDbgInfo.LexicalBlocks.pop_back();
1304 // Validate the generated code, checking for consistency.
1305 verifyFunction(*TheFunction);
1307 // Optimize the function.
1308 TheFPM->run(*TheFunction);
1313 // Error reading body, remove function.
1314 TheFunction->eraseFromParent();
1316 if (Proto->isBinaryOp())
1317 BinopPrecedence.erase(Proto->getOperatorName());
1319 // Pop off the lexical block for the function since we added it
1321 KSDbgInfo.LexicalBlocks.pop_back();
1326 //===----------------------------------------------------------------------===//
1327 // Top-Level parsing and JIT Driver
1328 //===----------------------------------------------------------------------===//
1330 static ExecutionEngine *TheExecutionEngine;
1332 static void HandleDefinition() {
1333 if (FunctionAST *F = ParseDefinition()) {
1334 if (!F->Codegen()) {
1335 fprintf(stderr, "Error reading function definition:");
1338 // Skip token for error recovery.
1343 static void HandleExtern() {
1344 if (PrototypeAST *P = ParseExtern()) {
1345 if (!P->Codegen()) {
1346 fprintf(stderr, "Error reading extern");
1349 // Skip token for error recovery.
1354 static void HandleTopLevelExpression() {
1355 // Evaluate a top-level expression into an anonymous function.
1356 if (FunctionAST *F = ParseTopLevelExpr()) {
1357 if (!F->Codegen()) {
1358 fprintf(stderr, "Error generating code for top level expr");
1361 // Skip token for error recovery.
1366 /// top ::= definition | external | expression | ';'
1367 static void MainLoop() {
1374 break; // ignore top-level semicolons.
1382 HandleTopLevelExpression();
1388 //===----------------------------------------------------------------------===//
1389 // "Library" functions that can be "extern'd" from user code.
1390 //===----------------------------------------------------------------------===//
1392 /// putchard - putchar that takes a double and returns 0.
1393 extern "C" double putchard(double X) {
1398 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1399 extern "C" double printd(double X) {
1404 //===----------------------------------------------------------------------===//
1405 // Main driver code.
1406 //===----------------------------------------------------------------------===//
1409 InitializeNativeTarget();
1410 InitializeNativeTargetAsmPrinter();
1411 InitializeNativeTargetAsmParser();
1412 LLVMContext &Context = getGlobalContext();
1414 // Install standard binary operators.
1415 // 1 is lowest precedence.
1416 BinopPrecedence['='] = 2;
1417 BinopPrecedence['<'] = 10;
1418 BinopPrecedence['+'] = 20;
1419 BinopPrecedence['-'] = 20;
1420 BinopPrecedence['*'] = 40; // highest.
1422 // Prime the first token.
1425 // Make the module, which holds all the code.
1426 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1427 TheModule = Owner.get();
1429 // Add the current debug info version into the module.
1430 TheModule->addModuleFlag(Module::Warning, "Debug Info Version",
1431 DEBUG_METADATA_VERSION);
1433 // Darwin only supports dwarf2.
1434 if (Triple(sys::getProcessTriple()).isOSDarwin())
1435 TheModule->addModuleFlag(llvm::Module::Warning, "Dwarf Version", 2);
1437 // Construct the DIBuilder, we do this here because we need the module.
1438 DBuilder = new DIBuilder(*TheModule);
1440 // Create the compile unit for the module.
1441 // Currently down as "fib.ks" as a filename since we're redirecting stdin
1442 // but we'd like actual source locations.
1443 KSDbgInfo.TheCU = DBuilder->createCompileUnit(
1444 dwarf::DW_LANG_C, "fib.ks", ".", "Kaleidoscope Compiler", 0, "", 0);
1446 // Create the JIT. This takes ownership of the module.
1448 TheExecutionEngine =
1449 EngineBuilder(std::move(Owner))
1450 .setErrorStr(&ErrStr)
1451 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1453 if (!TheExecutionEngine) {
1454 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1458 legacy::FunctionPassManager OurFPM(TheModule);
1460 // Set up the optimizer pipeline. Start with registering info about how the
1461 // target lays out data structures.
1462 TheModule->setDataLayout(*TheExecutionEngine->getDataLayout());
1464 // Provide basic AliasAnalysis support for GVN.
1465 OurFPM.add(createBasicAliasAnalysisPass());
1466 // Promote allocas to registers.
1467 OurFPM.add(createPromoteMemoryToRegisterPass());
1468 // Do simple "peephole" optimizations and bit-twiddling optzns.
1469 OurFPM.add(createInstructionCombiningPass());
1470 // Reassociate expressions.
1471 OurFPM.add(createReassociatePass());
1472 // Eliminate Common SubExpressions.
1473 OurFPM.add(createGVNPass());
1474 // Simplify the control flow graph (deleting unreachable blocks, etc).
1475 OurFPM.add(createCFGSimplificationPass());
1477 OurFPM.doInitialization();
1479 // Set the global so the code gen can use this.
1482 // Run the main "interpreter loop" now.
1487 // Finalize the debug info.
1488 DBuilder->finalize();
1490 // Print out all of the generated code.