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(), Scope));
839 static DISubroutineType *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 return DBuilder->createSubroutineType(Unit,
850 DBuilder->getOrCreateTypeArray(EltTys));
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 // This assume we're building without RTTI because LLVM builds that way by
912 // default. If you build LLVM with RTTI this can be changed to a
913 // dynamic_cast for automatic error checking.
914 VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS);
916 return ErrorV("destination of '=' must be a variable");
918 Value *Val = RHS->Codegen();
923 Value *Variable = NamedValues[LHSE->getName()];
925 return ErrorV("Unknown variable name");
927 Builder.CreateStore(Val, Variable);
931 Value *L = LHS->Codegen();
932 Value *R = RHS->Codegen();
933 if (L == 0 || R == 0)
938 return Builder.CreateFAdd(L, R, "addtmp");
940 return Builder.CreateFSub(L, R, "subtmp");
942 return Builder.CreateFMul(L, R, "multmp");
944 L = Builder.CreateFCmpULT(L, R, "cmptmp");
945 // Convert bool 0/1 to double 0.0 or 1.0
946 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
952 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
954 Function *F = TheModule->getFunction(std::string("binary") + Op);
955 assert(F && "binary operator not found!");
957 Value *Ops[] = { L, R };
958 return Builder.CreateCall(F, Ops, "binop");
961 Value *CallExprAST::Codegen() {
962 KSDbgInfo.emitLocation(this);
964 // Look up the name in the global module table.
965 Function *CalleeF = TheModule->getFunction(Callee);
967 return ErrorV("Unknown function referenced");
969 // If argument mismatch error.
970 if (CalleeF->arg_size() != Args.size())
971 return ErrorV("Incorrect # arguments passed");
973 std::vector<Value *> ArgsV;
974 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
975 ArgsV.push_back(Args[i]->Codegen());
976 if (ArgsV.back() == 0)
980 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
983 Value *IfExprAST::Codegen() {
984 KSDbgInfo.emitLocation(this);
986 Value *CondV = Cond->Codegen();
990 // Convert condition to a bool by comparing equal to 0.0.
991 CondV = Builder.CreateFCmpONE(
992 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
994 Function *TheFunction = Builder.GetInsertBlock()->getParent();
996 // Create blocks for the then and else cases. Insert the 'then' block at the
997 // end of the function.
999 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
1000 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
1001 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
1003 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
1006 Builder.SetInsertPoint(ThenBB);
1008 Value *ThenV = Then->Codegen();
1012 Builder.CreateBr(MergeBB);
1013 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
1014 ThenBB = Builder.GetInsertBlock();
1017 TheFunction->getBasicBlockList().push_back(ElseBB);
1018 Builder.SetInsertPoint(ElseBB);
1020 Value *ElseV = Else->Codegen();
1024 Builder.CreateBr(MergeBB);
1025 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
1026 ElseBB = Builder.GetInsertBlock();
1028 // Emit merge block.
1029 TheFunction->getBasicBlockList().push_back(MergeBB);
1030 Builder.SetInsertPoint(MergeBB);
1032 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
1034 PN->addIncoming(ThenV, ThenBB);
1035 PN->addIncoming(ElseV, ElseBB);
1039 Value *ForExprAST::Codegen() {
1041 // var = alloca double
1043 // start = startexpr
1044 // store start -> var
1052 // endcond = endexpr
1054 // curvar = load var
1055 // nextvar = curvar + step
1056 // store nextvar -> var
1057 // br endcond, loop, endloop
1060 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1062 // Create an alloca for the variable in the entry block.
1063 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1065 KSDbgInfo.emitLocation(this);
1067 // Emit the start code first, without 'variable' in scope.
1068 Value *StartVal = Start->Codegen();
1072 // Store the value into the alloca.
1073 Builder.CreateStore(StartVal, Alloca);
1075 // Make the new basic block for the loop header, inserting after current
1077 BasicBlock *LoopBB =
1078 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
1080 // Insert an explicit fall through from the current block to the LoopBB.
1081 Builder.CreateBr(LoopBB);
1083 // Start insertion in LoopBB.
1084 Builder.SetInsertPoint(LoopBB);
1086 // Within the loop, the variable is defined equal to the PHI node. If it
1087 // shadows an existing variable, we have to restore it, so save it now.
1088 AllocaInst *OldVal = NamedValues[VarName];
1089 NamedValues[VarName] = Alloca;
1091 // Emit the body of the loop. This, like any other expr, can change the
1092 // current BB. Note that we ignore the value computed by the body, but don't
1094 if (Body->Codegen() == 0)
1097 // Emit the step value.
1100 StepVal = Step->Codegen();
1104 // If not specified, use 1.0.
1105 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
1108 // Compute the end condition.
1109 Value *EndCond = End->Codegen();
1113 // Reload, increment, and restore the alloca. This handles the case where
1114 // the body of the loop mutates the variable.
1115 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
1116 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
1117 Builder.CreateStore(NextVar, Alloca);
1119 // Convert condition to a bool by comparing equal to 0.0.
1120 EndCond = Builder.CreateFCmpONE(
1121 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
1123 // Create the "after loop" block and insert it.
1124 BasicBlock *AfterBB =
1125 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
1127 // Insert the conditional branch into the end of LoopEndBB.
1128 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
1130 // Any new code will be inserted in AfterBB.
1131 Builder.SetInsertPoint(AfterBB);
1133 // Restore the unshadowed variable.
1135 NamedValues[VarName] = OldVal;
1137 NamedValues.erase(VarName);
1139 // for expr always returns 0.0.
1140 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
1143 Value *VarExprAST::Codegen() {
1144 std::vector<AllocaInst *> OldBindings;
1146 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1148 // Register all variables and emit their initializer.
1149 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
1150 const std::string &VarName = VarNames[i].first;
1151 ExprAST *Init = VarNames[i].second;
1153 // Emit the initializer before adding the variable to scope, this prevents
1154 // the initializer from referencing the variable itself, and permits stuff
1157 // var a = a in ... # refers to outer 'a'.
1160 InitVal = Init->Codegen();
1163 } else { // If not specified, use 0.0.
1164 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1167 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1168 Builder.CreateStore(InitVal, Alloca);
1170 // Remember the old variable binding so that we can restore the binding when
1172 OldBindings.push_back(NamedValues[VarName]);
1174 // Remember this binding.
1175 NamedValues[VarName] = Alloca;
1178 KSDbgInfo.emitLocation(this);
1180 // Codegen the body, now that all vars are in scope.
1181 Value *BodyVal = Body->Codegen();
1185 // Pop all our variables from scope.
1186 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1187 NamedValues[VarNames[i].first] = OldBindings[i];
1189 // Return the body computation.
1193 Function *PrototypeAST::Codegen() {
1194 // Make the function type: double(double,double) etc.
1195 std::vector<Type *> Doubles(Args.size(),
1196 Type::getDoubleTy(getGlobalContext()));
1198 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
1201 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
1203 // If F conflicted, there was already something named 'Name'. If it has a
1204 // body, don't allow redefinition or reextern.
1205 if (F->getName() != Name) {
1206 // Delete the one we just made and get the existing one.
1207 F->eraseFromParent();
1208 F = TheModule->getFunction(Name);
1210 // If F already has a body, reject this.
1212 ErrorF("redefinition of function");
1216 // If F took a different number of args, reject.
1217 if (F->arg_size() != Args.size()) {
1218 ErrorF("redefinition of function with different # args");
1223 // Set names for all arguments.
1225 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1227 AI->setName(Args[Idx]);
1229 // Create a subprogram DIE for this function.
1230 DIFile *Unit = DBuilder->createFile(KSDbgInfo.TheCU->getFilename(),
1231 KSDbgInfo.TheCU->getDirectory());
1232 DIScope *FContext = Unit;
1233 unsigned LineNo = Line;
1234 unsigned ScopeLine = Line;
1235 DISubprogram *SP = DBuilder->createFunction(
1236 FContext, Name, StringRef(), Unit, LineNo,
1237 CreateFunctionType(Args.size(), Unit), false /* internal linkage */,
1238 true /* definition */, ScopeLine, DINode::FlagPrototyped, false, F);
1240 KSDbgInfo.FnScopeMap[this] = SP;
1244 /// CreateArgumentAllocas - Create an alloca for each argument and register the
1245 /// argument in the symbol table so that references to it will succeed.
1246 void PrototypeAST::CreateArgumentAllocas(Function *F) {
1247 Function::arg_iterator AI = F->arg_begin();
1248 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1249 // Create an alloca for this variable.
1250 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1252 // Create a debug descriptor for the variable.
1253 DIScope *Scope = KSDbgInfo.LexicalBlocks.back();
1254 DIFile *Unit = DBuilder->createFile(KSDbgInfo.TheCU->getFilename(),
1255 KSDbgInfo.TheCU->getDirectory());
1256 DILocalVariable *D = DBuilder->createLocalVariable(
1257 dwarf::DW_TAG_arg_variable, Scope, Args[Idx], Unit, Line,
1258 KSDbgInfo.getDoubleTy(), true, 0, Idx + 1);
1260 DBuilder->insertDeclare(Alloca, D, DBuilder->createExpression(),
1261 DebugLoc::get(Line, 0, Scope),
1262 Builder.GetInsertBlock());
1264 // Store the initial value into the alloca.
1265 Builder.CreateStore(AI, Alloca);
1267 // Add arguments to variable symbol table.
1268 NamedValues[Args[Idx]] = Alloca;
1272 Function *FunctionAST::Codegen() {
1273 NamedValues.clear();
1275 Function *TheFunction = Proto->Codegen();
1276 if (TheFunction == 0)
1279 // Push the current scope.
1280 KSDbgInfo.LexicalBlocks.push_back(KSDbgInfo.FnScopeMap[Proto]);
1282 // Unset the location for the prologue emission (leading instructions with no
1283 // location in a function are considered part of the prologue and the debugger
1284 // will run past them when breaking on a function)
1285 KSDbgInfo.emitLocation(nullptr);
1287 // If this is an operator, install it.
1288 if (Proto->isBinaryOp())
1289 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
1291 // Create a new basic block to start insertion into.
1292 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1293 Builder.SetInsertPoint(BB);
1295 // Add all arguments to the symbol table and create their allocas.
1296 Proto->CreateArgumentAllocas(TheFunction);
1298 KSDbgInfo.emitLocation(Body);
1300 if (Value *RetVal = Body->Codegen()) {
1301 // Finish off the function.
1302 Builder.CreateRet(RetVal);
1304 // Pop off the lexical block for the function.
1305 KSDbgInfo.LexicalBlocks.pop_back();
1307 // Validate the generated code, checking for consistency.
1308 verifyFunction(*TheFunction);
1310 // Optimize the function.
1311 TheFPM->run(*TheFunction);
1316 // Error reading body, remove function.
1317 TheFunction->eraseFromParent();
1319 if (Proto->isBinaryOp())
1320 BinopPrecedence.erase(Proto->getOperatorName());
1322 // Pop off the lexical block for the function since we added it
1324 KSDbgInfo.LexicalBlocks.pop_back();
1329 //===----------------------------------------------------------------------===//
1330 // Top-Level parsing and JIT Driver
1331 //===----------------------------------------------------------------------===//
1333 static ExecutionEngine *TheExecutionEngine;
1335 static void HandleDefinition() {
1336 if (FunctionAST *F = ParseDefinition()) {
1337 if (!F->Codegen()) {
1338 fprintf(stderr, "Error reading function definition:");
1341 // Skip token for error recovery.
1346 static void HandleExtern() {
1347 if (PrototypeAST *P = ParseExtern()) {
1348 if (!P->Codegen()) {
1349 fprintf(stderr, "Error reading extern");
1352 // Skip token for error recovery.
1357 static void HandleTopLevelExpression() {
1358 // Evaluate a top-level expression into an anonymous function.
1359 if (FunctionAST *F = ParseTopLevelExpr()) {
1360 if (!F->Codegen()) {
1361 fprintf(stderr, "Error generating code for top level expr");
1364 // Skip token for error recovery.
1369 /// top ::= definition | external | expression | ';'
1370 static void MainLoop() {
1377 break; // ignore top-level semicolons.
1385 HandleTopLevelExpression();
1391 //===----------------------------------------------------------------------===//
1392 // "Library" functions that can be "extern'd" from user code.
1393 //===----------------------------------------------------------------------===//
1395 /// putchard - putchar that takes a double and returns 0.
1396 extern "C" double putchard(double X) {
1401 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1402 extern "C" double printd(double X) {
1407 //===----------------------------------------------------------------------===//
1408 // Main driver code.
1409 //===----------------------------------------------------------------------===//
1412 InitializeNativeTarget();
1413 InitializeNativeTargetAsmPrinter();
1414 InitializeNativeTargetAsmParser();
1415 LLVMContext &Context = getGlobalContext();
1417 // Install standard binary operators.
1418 // 1 is lowest precedence.
1419 BinopPrecedence['='] = 2;
1420 BinopPrecedence['<'] = 10;
1421 BinopPrecedence['+'] = 20;
1422 BinopPrecedence['-'] = 20;
1423 BinopPrecedence['*'] = 40; // highest.
1425 // Prime the first token.
1428 // Make the module, which holds all the code.
1429 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1430 TheModule = Owner.get();
1432 // Add the current debug info version into the module.
1433 TheModule->addModuleFlag(Module::Warning, "Debug Info Version",
1434 DEBUG_METADATA_VERSION);
1436 // Darwin only supports dwarf2.
1437 if (Triple(sys::getProcessTriple()).isOSDarwin())
1438 TheModule->addModuleFlag(llvm::Module::Warning, "Dwarf Version", 2);
1440 // Construct the DIBuilder, we do this here because we need the module.
1441 DBuilder = new DIBuilder(*TheModule);
1443 // Create the compile unit for the module.
1444 // Currently down as "fib.ks" as a filename since we're redirecting stdin
1445 // but we'd like actual source locations.
1446 KSDbgInfo.TheCU = DBuilder->createCompileUnit(
1447 dwarf::DW_LANG_C, "fib.ks", ".", "Kaleidoscope Compiler", 0, "", 0);
1449 // Create the JIT. This takes ownership of the module.
1451 TheExecutionEngine =
1452 EngineBuilder(std::move(Owner))
1453 .setErrorStr(&ErrStr)
1454 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1456 if (!TheExecutionEngine) {
1457 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1461 legacy::FunctionPassManager OurFPM(TheModule);
1463 // Set up the optimizer pipeline. Start with registering info about how the
1464 // target lays out data structures.
1465 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
1467 // Provide basic AliasAnalysis support for GVN.
1468 OurFPM.add(createBasicAliasAnalysisPass());
1469 // Promote allocas to registers.
1470 OurFPM.add(createPromoteMemoryToRegisterPass());
1471 // Do simple "peephole" optimizations and bit-twiddling optzns.
1472 OurFPM.add(createInstructionCombiningPass());
1473 // Reassociate expressions.
1474 OurFPM.add(createReassociatePass());
1475 // Eliminate Common SubExpressions.
1476 OurFPM.add(createGVNPass());
1477 // Simplify the control flow graph (deleting unreachable blocks, etc).
1478 OurFPM.add(createCFGSimplificationPass());
1480 OurFPM.doInitialization();
1482 // Set the global so the code gen can use this.
1485 // Run the main "interpreter loop" now.
1490 // Finalize the debug info.
1491 DBuilder->finalize();
1493 // Print out all of the generated code.