1 #include "llvm/Analysis/Passes.h"
2 #include "llvm/ExecutionEngine/Orc/CompileUtils.h"
3 #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
4 #include "llvm/ExecutionEngine/Orc/LambdaResolver.h"
5 #include "llvm/ExecutionEngine/Orc/LazyEmittingLayer.h"
6 #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
7 #include "llvm/IR/DataLayout.h"
8 #include "llvm/IR/DerivedTypes.h"
9 #include "llvm/IR/IRBuilder.h"
10 #include "llvm/IR/LegacyPassManager.h"
11 #include "llvm/IR/LLVMContext.h"
12 #include "llvm/IR/Module.h"
13 #include "llvm/IR/Verifier.h"
14 #include "llvm/Support/TargetSelect.h"
15 #include "llvm/Transforms/Scalar.h"
25 using namespace llvm::orc;
27 //===----------------------------------------------------------------------===//
29 //===----------------------------------------------------------------------===//
31 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
32 // of these for known things.
37 tok_def = -2, tok_extern = -3,
40 tok_identifier = -4, tok_number = -5,
43 tok_if = -6, tok_then = -7, tok_else = -8,
44 tok_for = -9, tok_in = -10,
47 tok_binary = -11, tok_unary = -12,
53 static std::string IdentifierStr; // Filled in if tok_identifier
54 static double NumVal; // Filled in if tok_number
56 /// gettok - Return the next token from standard input.
58 static int LastChar = ' ';
60 // Skip any whitespace.
61 while (isspace(LastChar))
64 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
65 IdentifierStr = LastChar;
66 while (isalnum((LastChar = getchar())))
67 IdentifierStr += LastChar;
69 if (IdentifierStr == "def") return tok_def;
70 if (IdentifierStr == "extern") return tok_extern;
71 if (IdentifierStr == "if") return tok_if;
72 if (IdentifierStr == "then") return tok_then;
73 if (IdentifierStr == "else") return tok_else;
74 if (IdentifierStr == "for") return tok_for;
75 if (IdentifierStr == "in") return tok_in;
76 if (IdentifierStr == "binary") return tok_binary;
77 if (IdentifierStr == "unary") return tok_unary;
78 if (IdentifierStr == "var") return tok_var;
79 return tok_identifier;
82 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
87 } while (isdigit(LastChar) || LastChar == '.');
89 NumVal = strtod(NumStr.c_str(), 0);
93 if (LastChar == '#') {
94 // Comment until end of line.
95 do LastChar = getchar();
96 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
102 // Check for end of file. Don't eat the EOF.
106 // Otherwise, just return the character as its ascii value.
107 int ThisChar = LastChar;
108 LastChar = getchar();
112 //===----------------------------------------------------------------------===//
113 // Abstract Syntax Tree (aka Parse Tree)
114 //===----------------------------------------------------------------------===//
118 /// ExprAST - Base class for all expression nodes.
120 virtual ~ExprAST() {}
121 virtual Value *IRGen(IRGenContext &C) const = 0;
124 /// NumberExprAST - Expression class for numeric literals like "1.0".
125 struct NumberExprAST : public ExprAST {
126 NumberExprAST(double Val) : Val(Val) {}
127 Value *IRGen(IRGenContext &C) const override;
132 /// VariableExprAST - Expression class for referencing a variable, like "a".
133 struct VariableExprAST : public ExprAST {
134 VariableExprAST(std::string Name) : Name(std::move(Name)) {}
135 Value *IRGen(IRGenContext &C) const override;
140 /// UnaryExprAST - Expression class for a unary operator.
141 struct UnaryExprAST : public ExprAST {
142 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
143 : Opcode(std::move(Opcode)), Operand(std::move(Operand)) {}
145 Value *IRGen(IRGenContext &C) const override;
148 std::unique_ptr<ExprAST> Operand;
151 /// BinaryExprAST - Expression class for a binary operator.
152 struct BinaryExprAST : public ExprAST {
153 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
154 std::unique_ptr<ExprAST> RHS)
155 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
157 Value *IRGen(IRGenContext &C) const override;
160 std::unique_ptr<ExprAST> LHS, RHS;
163 /// CallExprAST - Expression class for function calls.
164 struct CallExprAST : public ExprAST {
165 CallExprAST(std::string CalleeName,
166 std::vector<std::unique_ptr<ExprAST>> Args)
167 : CalleeName(std::move(CalleeName)), Args(std::move(Args)) {}
169 Value *IRGen(IRGenContext &C) const override;
171 std::string CalleeName;
172 std::vector<std::unique_ptr<ExprAST>> Args;
175 /// IfExprAST - Expression class for if/then/else.
176 struct IfExprAST : public ExprAST {
177 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
178 std::unique_ptr<ExprAST> Else)
179 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
180 Value *IRGen(IRGenContext &C) const override;
182 std::unique_ptr<ExprAST> Cond, Then, Else;
185 /// ForExprAST - Expression class for for/in.
186 struct ForExprAST : public ExprAST {
187 ForExprAST(std::string VarName, std::unique_ptr<ExprAST> Start,
188 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
189 std::unique_ptr<ExprAST> Body)
190 : VarName(std::move(VarName)), Start(std::move(Start)), End(std::move(End)),
191 Step(std::move(Step)), Body(std::move(Body)) {}
193 Value *IRGen(IRGenContext &C) const override;
196 std::unique_ptr<ExprAST> Start, End, Step, Body;
199 /// VarExprAST - Expression class for var/in
200 struct VarExprAST : public ExprAST {
201 typedef std::pair<std::string, std::unique_ptr<ExprAST>> Binding;
202 typedef std::vector<Binding> BindingList;
204 VarExprAST(BindingList VarBindings, std::unique_ptr<ExprAST> Body)
205 : VarBindings(std::move(VarBindings)), Body(std::move(Body)) {}
207 Value *IRGen(IRGenContext &C) const override;
209 BindingList VarBindings;
210 std::unique_ptr<ExprAST> Body;
213 /// PrototypeAST - This class represents the "prototype" for a function,
214 /// which captures its argument names as well as if it is an operator.
215 struct PrototypeAST {
216 PrototypeAST(std::string Name, std::vector<std::string> Args,
217 bool IsOperator = false, unsigned Precedence = 0)
218 : Name(std::move(Name)), Args(std::move(Args)), IsOperator(IsOperator),
219 Precedence(Precedence) {}
221 Function *IRGen(IRGenContext &C) const;
222 void CreateArgumentAllocas(Function *F, IRGenContext &C);
224 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
225 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
227 char getOperatorName() const {
228 assert(isUnaryOp() || isBinaryOp());
229 return Name[Name.size()-1];
233 std::vector<std::string> Args;
235 unsigned Precedence; // Precedence if a binary op.
238 /// FunctionAST - This class represents a function definition itself.
240 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
241 std::unique_ptr<ExprAST> Body)
242 : Proto(std::move(Proto)), Body(std::move(Body)) {}
244 Function *IRGen(IRGenContext &C) const;
246 std::unique_ptr<PrototypeAST> Proto;
247 std::unique_ptr<ExprAST> Body;
250 //===----------------------------------------------------------------------===//
252 //===----------------------------------------------------------------------===//
254 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
255 /// token the parser is looking at. getNextToken reads another token from the
256 /// lexer and updates CurTok with its results.
258 static int getNextToken() {
259 return CurTok = gettok();
262 /// BinopPrecedence - This holds the precedence for each binary operator that is
264 static std::map<char, int> BinopPrecedence;
266 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
267 static int GetTokPrecedence() {
268 if (!isascii(CurTok))
271 // Make sure it's a declared binop.
272 int TokPrec = BinopPrecedence[CurTok];
273 if (TokPrec <= 0) return -1;
277 template <typename T>
278 std::unique_ptr<T> ErrorU(const std::string &Str) {
279 std::cerr << "Error: " << Str << "\n";
283 template <typename T>
284 T* ErrorP(const std::string &Str) {
285 std::cerr << "Error: " << Str << "\n";
289 static std::unique_ptr<ExprAST> ParseExpression();
293 /// ::= identifier '(' expression* ')'
294 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
295 std::string IdName = IdentifierStr;
297 getNextToken(); // eat identifier.
299 if (CurTok != '(') // Simple variable ref.
300 return llvm::make_unique<VariableExprAST>(IdName);
303 getNextToken(); // eat (
304 std::vector<std::unique_ptr<ExprAST>> Args;
307 auto Arg = ParseExpression();
308 if (!Arg) return nullptr;
309 Args.push_back(std::move(Arg));
311 if (CurTok == ')') break;
314 return ErrorU<CallExprAST>("Expected ')' or ',' in argument list");
322 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
325 /// numberexpr ::= number
326 static std::unique_ptr<NumberExprAST> ParseNumberExpr() {
327 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
328 getNextToken(); // consume the number
332 /// parenexpr ::= '(' expression ')'
333 static std::unique_ptr<ExprAST> ParseParenExpr() {
334 getNextToken(); // eat (.
335 auto V = ParseExpression();
340 return ErrorU<ExprAST>("expected ')'");
341 getNextToken(); // eat ).
345 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
346 static std::unique_ptr<ExprAST> ParseIfExpr() {
347 getNextToken(); // eat the if.
350 auto Cond = ParseExpression();
354 if (CurTok != tok_then)
355 return ErrorU<ExprAST>("expected then");
356 getNextToken(); // eat the then
358 auto Then = ParseExpression();
362 if (CurTok != tok_else)
363 return ErrorU<ExprAST>("expected else");
367 auto Else = ParseExpression();
371 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
375 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
376 static std::unique_ptr<ForExprAST> ParseForExpr() {
377 getNextToken(); // eat the for.
379 if (CurTok != tok_identifier)
380 return ErrorU<ForExprAST>("expected identifier after for");
382 std::string IdName = IdentifierStr;
383 getNextToken(); // eat identifier.
386 return ErrorU<ForExprAST>("expected '=' after for");
387 getNextToken(); // eat '='.
390 auto Start = ParseExpression();
394 return ErrorU<ForExprAST>("expected ',' after for start value");
397 auto End = ParseExpression();
401 // The step value is optional.
402 std::unique_ptr<ExprAST> Step;
405 Step = ParseExpression();
410 if (CurTok != tok_in)
411 return ErrorU<ForExprAST>("expected 'in' after for");
412 getNextToken(); // eat 'in'.
414 auto Body = ParseExpression();
418 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
419 std::move(Step), std::move(Body));
422 /// varexpr ::= 'var' identifier ('=' expression)?
423 // (',' identifier ('=' expression)?)* 'in' expression
424 static std::unique_ptr<VarExprAST> ParseVarExpr() {
425 getNextToken(); // eat the var.
427 VarExprAST::BindingList VarBindings;
429 // At least one variable name is required.
430 if (CurTok != tok_identifier)
431 return ErrorU<VarExprAST>("expected identifier after var");
434 std::string Name = IdentifierStr;
435 getNextToken(); // eat identifier.
437 // Read the optional initializer.
438 std::unique_ptr<ExprAST> Init;
440 getNextToken(); // eat the '='.
442 Init = ParseExpression();
447 VarBindings.push_back(VarExprAST::Binding(Name, std::move(Init)));
449 // End of var list, exit loop.
450 if (CurTok != ',') break;
451 getNextToken(); // eat the ','.
453 if (CurTok != tok_identifier)
454 return ErrorU<VarExprAST>("expected identifier list after var");
457 // At this point, we have to have 'in'.
458 if (CurTok != tok_in)
459 return ErrorU<VarExprAST>("expected 'in' keyword after 'var'");
460 getNextToken(); // eat 'in'.
462 auto Body = ParseExpression();
466 return llvm::make_unique<VarExprAST>(std::move(VarBindings), std::move(Body));
470 /// ::= identifierexpr
476 static std::unique_ptr<ExprAST> ParsePrimary() {
478 default: return ErrorU<ExprAST>("unknown token when expecting an expression");
479 case tok_identifier: return ParseIdentifierExpr();
480 case tok_number: return ParseNumberExpr();
481 case '(': return ParseParenExpr();
482 case tok_if: return ParseIfExpr();
483 case tok_for: return ParseForExpr();
484 case tok_var: return ParseVarExpr();
491 static std::unique_ptr<ExprAST> ParseUnary() {
492 // If the current token is not an operator, it must be a primary expr.
493 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
494 return ParsePrimary();
496 // If this is a unary operator, read it.
499 if (auto Operand = ParseUnary())
500 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
506 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
507 std::unique_ptr<ExprAST> LHS) {
508 // If this is a binop, find its precedence.
510 int TokPrec = GetTokPrecedence();
512 // If this is a binop that binds at least as tightly as the current binop,
513 // consume it, otherwise we are done.
514 if (TokPrec < ExprPrec)
517 // Okay, we know this is a binop.
519 getNextToken(); // eat binop
521 // Parse the unary expression after the binary operator.
522 auto RHS = ParseUnary();
526 // If BinOp binds less tightly with RHS than the operator after RHS, let
527 // the pending operator take RHS as its LHS.
528 int NextPrec = GetTokPrecedence();
529 if (TokPrec < NextPrec) {
530 RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
536 LHS = llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
541 /// ::= unary binoprhs
543 static std::unique_ptr<ExprAST> ParseExpression() {
544 auto LHS = ParseUnary();
548 return ParseBinOpRHS(0, std::move(LHS));
552 /// ::= id '(' id* ')'
553 /// ::= binary LETTER number? (id, id)
554 /// ::= unary LETTER (id)
555 static std::unique_ptr<PrototypeAST> ParsePrototype() {
558 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
559 unsigned BinaryPrecedence = 30;
563 return ErrorU<PrototypeAST>("Expected function name in prototype");
565 FnName = IdentifierStr;
571 if (!isascii(CurTok))
572 return ErrorU<PrototypeAST>("Expected unary operator");
574 FnName += (char)CurTok;
580 if (!isascii(CurTok))
581 return ErrorU<PrototypeAST>("Expected binary operator");
583 FnName += (char)CurTok;
587 // Read the precedence if present.
588 if (CurTok == tok_number) {
589 if (NumVal < 1 || NumVal > 100)
590 return ErrorU<PrototypeAST>("Invalid precedecnce: must be 1..100");
591 BinaryPrecedence = (unsigned)NumVal;
598 return ErrorU<PrototypeAST>("Expected '(' in prototype");
600 std::vector<std::string> ArgNames;
601 while (getNextToken() == tok_identifier)
602 ArgNames.push_back(IdentifierStr);
604 return ErrorU<PrototypeAST>("Expected ')' in prototype");
607 getNextToken(); // eat ')'.
609 // Verify right number of names for operator.
610 if (Kind && ArgNames.size() != Kind)
611 return ErrorU<PrototypeAST>("Invalid number of operands for operator");
613 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames), Kind != 0,
617 /// definition ::= 'def' prototype expression
618 static std::unique_ptr<FunctionAST> ParseDefinition() {
619 getNextToken(); // eat def.
620 auto Proto = ParsePrototype();
624 if (auto Body = ParseExpression())
625 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(Body));
629 /// toplevelexpr ::= expression
630 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
631 if (auto E = ParseExpression()) {
632 // Make an anonymous proto.
634 llvm::make_unique<PrototypeAST>("__anon_expr", std::vector<std::string>());
635 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
640 /// external ::= 'extern' prototype
641 static std::unique_ptr<PrototypeAST> ParseExtern() {
642 getNextToken(); // eat extern.
643 return ParsePrototype();
646 //===----------------------------------------------------------------------===//
648 //===----------------------------------------------------------------------===//
650 // FIXME: Obviously we can do better than this
651 std::string GenerateUniqueName(const std::string &Root) {
653 std::ostringstream NameStream;
654 NameStream << Root << ++i;
655 return NameStream.str();
658 std::string MakeLegalFunctionName(std::string Name)
661 assert(!Name.empty() && "Base name must not be empty");
663 // Start with what we have
666 // Look for a numberic first character
667 if (NewName.find_first_of("0123456789") == 0) {
668 NewName.insert(0, 1, 'n');
671 // Replace illegal characters with their ASCII equivalent
672 std::string legal_elements = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
674 while ((pos = NewName.find_first_not_of(legal_elements)) != std::string::npos) {
675 std::ostringstream NumStream;
676 NumStream << (int)NewName.at(pos);
677 NewName = NewName.replace(pos, 1, NumStream.str());
683 class SessionContext {
685 SessionContext(LLVMContext &C)
686 : Context(C), TM(EngineBuilder().selectTarget()) {}
687 LLVMContext& getLLVMContext() const { return Context; }
688 TargetMachine& getTarget() { return *TM; }
689 void addPrototypeAST(std::unique_ptr<PrototypeAST> P);
690 PrototypeAST* getPrototypeAST(const std::string &Name);
692 typedef std::map<std::string, std::unique_ptr<PrototypeAST>> PrototypeMap;
694 LLVMContext &Context;
695 std::unique_ptr<TargetMachine> TM;
697 PrototypeMap Prototypes;
700 void SessionContext::addPrototypeAST(std::unique_ptr<PrototypeAST> P) {
701 Prototypes[P->Name] = std::move(P);
704 PrototypeAST* SessionContext::getPrototypeAST(const std::string &Name) {
705 PrototypeMap::iterator I = Prototypes.find(Name);
706 if (I != Prototypes.end())
707 return I->second.get();
714 IRGenContext(SessionContext &S)
716 M(new Module(GenerateUniqueName("jit_module_"),
717 Session.getLLVMContext())),
718 Builder(Session.getLLVMContext()) {
719 M->setDataLayout(Session.getTarget().createDataLayout());
722 SessionContext& getSession() { return Session; }
723 Module& getM() const { return *M; }
724 std::unique_ptr<Module> takeM() { return std::move(M); }
725 IRBuilder<>& getBuilder() { return Builder; }
726 LLVMContext& getLLVMContext() { return Session.getLLVMContext(); }
727 Function* getPrototype(const std::string &Name);
729 std::map<std::string, AllocaInst*> NamedValues;
731 SessionContext &Session;
732 std::unique_ptr<Module> M;
736 Function* IRGenContext::getPrototype(const std::string &Name) {
737 if (Function *ExistingProto = M->getFunction(Name))
738 return ExistingProto;
739 if (PrototypeAST *ProtoAST = Session.getPrototypeAST(Name))
740 return ProtoAST->IRGen(*this);
744 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
745 /// the function. This is used for mutable variables etc.
746 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
747 const std::string &VarName) {
748 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
749 TheFunction->getEntryBlock().begin());
750 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
754 Value *NumberExprAST::IRGen(IRGenContext &C) const {
755 return ConstantFP::get(C.getLLVMContext(), APFloat(Val));
758 Value *VariableExprAST::IRGen(IRGenContext &C) const {
759 // Look this variable up in the function.
760 Value *V = C.NamedValues[Name];
763 return ErrorP<Value>("Unknown variable name '" + Name + "'");
766 return C.getBuilder().CreateLoad(V, Name.c_str());
769 Value *UnaryExprAST::IRGen(IRGenContext &C) const {
770 if (Value *OperandV = Operand->IRGen(C)) {
771 std::string FnName = MakeLegalFunctionName(std::string("unary")+Opcode);
772 if (Function *F = C.getPrototype(FnName))
773 return C.getBuilder().CreateCall(F, OperandV, "unop");
774 return ErrorP<Value>("Unknown unary operator");
777 // Could not codegen operand - return null.
781 Value *BinaryExprAST::IRGen(IRGenContext &C) const {
782 // Special case '=' because we don't want to emit the LHS as an expression.
784 // Assignment requires the LHS to be an identifier.
785 auto LHSVar = static_cast<VariableExprAST&>(*LHS);
787 Value *Val = RHS->IRGen(C);
788 if (!Val) return nullptr;
791 if (auto Variable = C.NamedValues[LHSVar.Name]) {
792 C.getBuilder().CreateStore(Val, Variable);
795 return ErrorP<Value>("Unknown variable name");
798 Value *L = LHS->IRGen(C);
799 Value *R = RHS->IRGen(C);
800 if (!L || !R) return nullptr;
803 case '+': return C.getBuilder().CreateFAdd(L, R, "addtmp");
804 case '-': return C.getBuilder().CreateFSub(L, R, "subtmp");
805 case '*': return C.getBuilder().CreateFMul(L, R, "multmp");
806 case '/': return C.getBuilder().CreateFDiv(L, R, "divtmp");
808 L = C.getBuilder().CreateFCmpULT(L, R, "cmptmp");
809 // Convert bool 0/1 to double 0.0 or 1.0
810 return C.getBuilder().CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
815 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
817 std::string FnName = MakeLegalFunctionName(std::string("binary")+Op);
818 if (Function *F = C.getPrototype(FnName)) {
819 Value *Ops[] = { L, R };
820 return C.getBuilder().CreateCall(F, Ops, "binop");
823 return ErrorP<Value>("Unknown binary operator");
826 Value *CallExprAST::IRGen(IRGenContext &C) const {
827 // Look up the name in the global module table.
828 if (auto CalleeF = C.getPrototype(CalleeName)) {
829 // If argument mismatch error.
830 if (CalleeF->arg_size() != Args.size())
831 return ErrorP<Value>("Incorrect # arguments passed");
833 std::vector<Value*> ArgsV;
834 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
835 ArgsV.push_back(Args[i]->IRGen(C));
836 if (!ArgsV.back()) return nullptr;
839 return C.getBuilder().CreateCall(CalleeF, ArgsV, "calltmp");
842 return ErrorP<Value>("Unknown function referenced");
845 Value *IfExprAST::IRGen(IRGenContext &C) const {
846 Value *CondV = Cond->IRGen(C);
847 if (!CondV) return nullptr;
849 // Convert condition to a bool by comparing equal to 0.0.
851 ConstantFP::get(C.getLLVMContext(), APFloat(0.0));
852 CondV = C.getBuilder().CreateFCmpONE(CondV, FPZero, "ifcond");
854 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
856 // Create blocks for the then and else cases. Insert the 'then' block at the
857 // end of the function.
858 BasicBlock *ThenBB = BasicBlock::Create(C.getLLVMContext(), "then", TheFunction);
859 BasicBlock *ElseBB = BasicBlock::Create(C.getLLVMContext(), "else");
860 BasicBlock *MergeBB = BasicBlock::Create(C.getLLVMContext(), "ifcont");
862 C.getBuilder().CreateCondBr(CondV, ThenBB, ElseBB);
865 C.getBuilder().SetInsertPoint(ThenBB);
867 Value *ThenV = Then->IRGen(C);
868 if (!ThenV) return nullptr;
870 C.getBuilder().CreateBr(MergeBB);
871 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
872 ThenBB = C.getBuilder().GetInsertBlock();
875 TheFunction->getBasicBlockList().push_back(ElseBB);
876 C.getBuilder().SetInsertPoint(ElseBB);
878 Value *ElseV = Else->IRGen(C);
879 if (!ElseV) return nullptr;
881 C.getBuilder().CreateBr(MergeBB);
882 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
883 ElseBB = C.getBuilder().GetInsertBlock();
886 TheFunction->getBasicBlockList().push_back(MergeBB);
887 C.getBuilder().SetInsertPoint(MergeBB);
888 PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
891 PN->addIncoming(ThenV, ThenBB);
892 PN->addIncoming(ElseV, ElseBB);
896 Value *ForExprAST::IRGen(IRGenContext &C) const {
898 // var = alloca double
901 // store start -> var
912 // nextvar = curvar + step
913 // store nextvar -> var
914 // br endcond, loop, endloop
917 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
919 // Create an alloca for the variable in the entry block.
920 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
922 // Emit the start code first, without 'variable' in scope.
923 Value *StartVal = Start->IRGen(C);
924 if (!StartVal) return nullptr;
926 // Store the value into the alloca.
927 C.getBuilder().CreateStore(StartVal, Alloca);
929 // Make the new basic block for the loop header, inserting after current
931 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
933 // Insert an explicit fall through from the current block to the LoopBB.
934 C.getBuilder().CreateBr(LoopBB);
936 // Start insertion in LoopBB.
937 C.getBuilder().SetInsertPoint(LoopBB);
939 // Within the loop, the variable is defined equal to the PHI node. If it
940 // shadows an existing variable, we have to restore it, so save it now.
941 AllocaInst *OldVal = C.NamedValues[VarName];
942 C.NamedValues[VarName] = Alloca;
944 // Emit the body of the loop. This, like any other expr, can change the
945 // current BB. Note that we ignore the value computed by the body, but don't
950 // Emit the step value.
953 StepVal = Step->IRGen(C);
954 if (!StepVal) return nullptr;
956 // If not specified, use 1.0.
957 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
960 // Compute the end condition.
961 Value *EndCond = End->IRGen(C);
962 if (EndCond == 0) return EndCond;
964 // Reload, increment, and restore the alloca. This handles the case where
965 // the body of the loop mutates the variable.
966 Value *CurVar = C.getBuilder().CreateLoad(Alloca, VarName.c_str());
967 Value *NextVar = C.getBuilder().CreateFAdd(CurVar, StepVal, "nextvar");
968 C.getBuilder().CreateStore(NextVar, Alloca);
970 // Convert condition to a bool by comparing equal to 0.0.
971 EndCond = C.getBuilder().CreateFCmpONE(EndCond,
972 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
975 // Create the "after loop" block and insert it.
976 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
978 // Insert the conditional branch into the end of LoopEndBB.
979 C.getBuilder().CreateCondBr(EndCond, LoopBB, AfterBB);
981 // Any new code will be inserted in AfterBB.
982 C.getBuilder().SetInsertPoint(AfterBB);
984 // Restore the unshadowed variable.
986 C.NamedValues[VarName] = OldVal;
988 C.NamedValues.erase(VarName);
991 // for expr always returns 0.0.
992 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
995 Value *VarExprAST::IRGen(IRGenContext &C) const {
996 std::vector<AllocaInst *> OldBindings;
998 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
1000 // Register all variables and emit their initializer.
1001 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i) {
1002 auto &VarName = VarBindings[i].first;
1003 auto &Init = VarBindings[i].second;
1005 // Emit the initializer before adding the variable to scope, this prevents
1006 // the initializer from referencing the variable itself, and permits stuff
1009 // var a = a in ... # refers to outer 'a'.
1012 InitVal = Init->IRGen(C);
1013 if (!InitVal) return nullptr;
1014 } else // If not specified, use 0.0.
1015 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1017 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1018 C.getBuilder().CreateStore(InitVal, Alloca);
1020 // Remember the old variable binding so that we can restore the binding when
1022 OldBindings.push_back(C.NamedValues[VarName]);
1024 // Remember this binding.
1025 C.NamedValues[VarName] = Alloca;
1028 // Codegen the body, now that all vars are in scope.
1029 Value *BodyVal = Body->IRGen(C);
1030 if (!BodyVal) return nullptr;
1032 // Pop all our variables from scope.
1033 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i)
1034 C.NamedValues[VarBindings[i].first] = OldBindings[i];
1036 // Return the body computation.
1040 Function *PrototypeAST::IRGen(IRGenContext &C) const {
1041 std::string FnName = MakeLegalFunctionName(Name);
1043 // Make the function type: double(double,double) etc.
1044 std::vector<Type*> Doubles(Args.size(),
1045 Type::getDoubleTy(getGlobalContext()));
1046 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
1048 Function *F = Function::Create(FT, Function::ExternalLinkage, FnName,
1051 // If F conflicted, there was already something named 'FnName'. If it has a
1052 // body, don't allow redefinition or reextern.
1053 if (F->getName() != FnName) {
1054 // Delete the one we just made and get the existing one.
1055 F->eraseFromParent();
1056 F = C.getM().getFunction(Name);
1058 // If F already has a body, reject this.
1060 ErrorP<Function>("redefinition of function");
1064 // If F took a different number of args, reject.
1065 if (F->arg_size() != Args.size()) {
1066 ErrorP<Function>("redefinition of function with different # args");
1071 // Set names for all arguments.
1073 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1075 AI->setName(Args[Idx]);
1080 /// CreateArgumentAllocas - Create an alloca for each argument and register the
1081 /// argument in the symbol table so that references to it will succeed.
1082 void PrototypeAST::CreateArgumentAllocas(Function *F, IRGenContext &C) {
1083 Function::arg_iterator AI = F->arg_begin();
1084 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1085 // Create an alloca for this variable.
1086 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1088 // Store the initial value into the alloca.
1089 C.getBuilder().CreateStore(AI, Alloca);
1091 // Add arguments to variable symbol table.
1092 C.NamedValues[Args[Idx]] = Alloca;
1096 Function *FunctionAST::IRGen(IRGenContext &C) const {
1097 C.NamedValues.clear();
1099 Function *TheFunction = Proto->IRGen(C);
1103 // If this is an operator, install it.
1104 if (Proto->isBinaryOp())
1105 BinopPrecedence[Proto->getOperatorName()] = Proto->Precedence;
1107 // Create a new basic block to start insertion into.
1108 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1109 C.getBuilder().SetInsertPoint(BB);
1111 // Add all arguments to the symbol table and create their allocas.
1112 Proto->CreateArgumentAllocas(TheFunction, C);
1114 if (Value *RetVal = Body->IRGen(C)) {
1115 // Finish off the function.
1116 C.getBuilder().CreateRet(RetVal);
1118 // Validate the generated code, checking for consistency.
1119 verifyFunction(*TheFunction);
1124 // Error reading body, remove function.
1125 TheFunction->eraseFromParent();
1127 if (Proto->isBinaryOp())
1128 BinopPrecedence.erase(Proto->getOperatorName());
1132 //===----------------------------------------------------------------------===//
1133 // Top-Level parsing and JIT Driver
1134 //===----------------------------------------------------------------------===//
1136 static std::unique_ptr<llvm::Module> IRGen(SessionContext &S,
1137 const FunctionAST &F) {
1139 auto LF = F.IRGen(C);
1142 #ifndef MINIMAL_STDERR_OUTPUT
1143 fprintf(stderr, "Read function definition:");
1149 template <typename T>
1150 static std::vector<T> singletonSet(T t) {
1152 Vec.push_back(std::move(t));
1156 class KaleidoscopeJIT {
1158 typedef ObjectLinkingLayer<> ObjLayerT;
1159 typedef IRCompileLayer<ObjLayerT> CompileLayerT;
1160 typedef LazyEmittingLayer<CompileLayerT> LazyEmitLayerT;
1161 typedef LazyEmitLayerT::ModuleSetHandleT ModuleHandleT;
1163 KaleidoscopeJIT(SessionContext &Session)
1165 CompileLayer(ObjectLayer, SimpleCompiler(Session.getTarget())),
1166 LazyEmitLayer(CompileLayer) {}
1168 std::string mangle(const std::string &Name) {
1169 std::string MangledName;
1171 raw_string_ostream MangledNameStream(MangledName);
1172 Mangler::getNameWithPrefix(MangledNameStream, Name,
1173 Session.getTarget().createDataLayout());
1178 void addFunctionAST(std::unique_ptr<FunctionAST> FnAST) {
1179 std::cerr << "Adding AST: " << FnAST->Proto->Name << "\n";
1180 FunctionDefs[mangle(FnAST->Proto->Name)] = std::move(FnAST);
1183 ModuleHandleT addModule(std::unique_ptr<Module> M) {
1184 // We need a memory manager to allocate memory and resolve symbols for this
1185 // new module. Create one that resolves symbols by looking back into the
1187 auto Resolver = createLambdaResolver(
1188 [&](const std::string &Name) {
1189 // First try to find 'Name' within the JIT.
1190 if (auto Symbol = findSymbol(Name))
1191 return RuntimeDyld::SymbolInfo(Symbol.getAddress(),
1194 // If we don't already have a definition of 'Name' then search
1196 return searchFunctionASTs(Name);
1198 [](const std::string &S) { return nullptr; } );
1200 return LazyEmitLayer.addModuleSet(singletonSet(std::move(M)),
1201 make_unique<SectionMemoryManager>(),
1202 std::move(Resolver));
1205 void removeModule(ModuleHandleT H) { LazyEmitLayer.removeModuleSet(H); }
1207 JITSymbol findSymbol(const std::string &Name) {
1208 return LazyEmitLayer.findSymbol(Name, true);
1211 JITSymbol findSymbolIn(ModuleHandleT H, const std::string &Name) {
1212 return LazyEmitLayer.findSymbolIn(H, Name, true);
1215 JITSymbol findUnmangledSymbol(const std::string &Name) {
1216 return findSymbol(mangle(Name));
1221 // This method searches the FunctionDefs map for a definition of 'Name'. If it
1222 // finds one it generates a stub for it and returns the address of the stub.
1223 RuntimeDyld::SymbolInfo searchFunctionASTs(const std::string &Name) {
1224 auto DefI = FunctionDefs.find(Name);
1225 if (DefI == FunctionDefs.end())
1228 // Take the FunctionAST out of the map.
1229 auto FnAST = std::move(DefI->second);
1230 FunctionDefs.erase(DefI);
1232 // IRGen the AST, add it to the JIT, and return the address for it.
1233 auto H = addModule(IRGen(Session, *FnAST));
1234 auto Sym = findSymbolIn(H, Name);
1235 return RuntimeDyld::SymbolInfo(Sym.getAddress(), Sym.getFlags());
1238 SessionContext &Session;
1239 ObjLayerT ObjectLayer;
1240 CompileLayerT CompileLayer;
1241 LazyEmitLayerT LazyEmitLayer;
1243 std::map<std::string, std::unique_ptr<FunctionAST>> FunctionDefs;
1246 static void HandleDefinition(SessionContext &S, KaleidoscopeJIT &J) {
1247 if (auto F = ParseDefinition()) {
1248 S.addPrototypeAST(llvm::make_unique<PrototypeAST>(*F->Proto));
1249 J.addFunctionAST(std::move(F));
1251 // Skip token for error recovery.
1256 static void HandleExtern(SessionContext &S) {
1257 if (auto P = ParseExtern())
1258 S.addPrototypeAST(std::move(P));
1260 // Skip token for error recovery.
1265 static void HandleTopLevelExpression(SessionContext &S, KaleidoscopeJIT &J) {
1266 // Evaluate a top-level expression into an anonymous function.
1267 if (auto F = ParseTopLevelExpr()) {
1269 if (auto ExprFunc = F->IRGen(C)) {
1270 #ifndef MINIMAL_STDERR_OUTPUT
1271 std::cerr << "Expression function:\n";
1274 // Add the CodeGen'd module to the JIT. Keep a handle to it: We can remove
1275 // this module as soon as we've executed Function ExprFunc.
1276 auto H = J.addModule(C.takeM());
1278 // Get the address of the JIT'd function in memory.
1279 auto ExprSymbol = J.findUnmangledSymbol("__anon_expr");
1281 // Cast it to the right type (takes no arguments, returns a double) so we
1282 // can call it as a native function.
1283 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
1284 #ifdef MINIMAL_STDERR_OUTPUT
1287 std::cerr << "Evaluated to " << FP() << "\n";
1290 // Remove the function.
1294 // Skip token for error recovery.
1299 /// top ::= definition | external | expression | ';'
1300 static void MainLoop() {
1301 SessionContext S(getGlobalContext());
1302 KaleidoscopeJIT J(S);
1306 case tok_eof: return;
1307 case ';': getNextToken(); continue; // ignore top-level semicolons.
1308 case tok_def: HandleDefinition(S, J); break;
1309 case tok_extern: HandleExtern(S); break;
1310 default: HandleTopLevelExpression(S, J); break;
1312 #ifndef MINIMAL_STDERR_OUTPUT
1313 std::cerr << "ready> ";
1318 //===----------------------------------------------------------------------===//
1319 // "Library" functions that can be "extern'd" from user code.
1320 //===----------------------------------------------------------------------===//
1322 /// putchard - putchar that takes a double and returns 0.
1324 double putchard(double X) {
1329 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1331 double printd(double X) {
1342 //===----------------------------------------------------------------------===//
1343 // Main driver code.
1344 //===----------------------------------------------------------------------===//
1347 InitializeNativeTarget();
1348 InitializeNativeTargetAsmPrinter();
1349 InitializeNativeTargetAsmParser();
1351 // Install standard binary operators.
1352 // 1 is lowest precedence.
1353 BinopPrecedence['='] = 2;
1354 BinopPrecedence['<'] = 10;
1355 BinopPrecedence['+'] = 20;
1356 BinopPrecedence['-'] = 20;
1357 BinopPrecedence['/'] = 40;
1358 BinopPrecedence['*'] = 40; // highest.
1360 // Prime the first token.
1361 #ifndef MINIMAL_STDERR_OUTPUT
1362 std::cerr << "ready> ";
1366 std::cerr << std::fixed;
1368 // Run the main "interpreter loop" now.