1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/Analysis/BasicAliasAnalysis.h"
3 #include "llvm/Analysis/Passes.h"
4 #include "llvm/IR/IRBuilder.h"
5 #include "llvm/IR/LLVMContext.h"
6 #include "llvm/IR/LegacyPassManager.h"
7 #include "llvm/IR/Module.h"
8 #include "llvm/IR/Verifier.h"
9 #include "llvm/Support/TargetSelect.h"
10 #include "llvm/Transforms/Scalar.h"
16 #include "../include/KaleidoscopeJIT.h"
19 using namespace llvm::orc;
21 //===----------------------------------------------------------------------===//
23 //===----------------------------------------------------------------------===//
25 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
26 // of these for known things.
39 static std::string IdentifierStr; // Filled in if tok_identifier
40 static double NumVal; // Filled in if tok_number
42 /// gettok - Return the next token from standard input.
44 static int LastChar = ' ';
46 // Skip any whitespace.
47 while (isspace(LastChar))
50 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
51 IdentifierStr = LastChar;
52 while (isalnum((LastChar = getchar())))
53 IdentifierStr += LastChar;
55 if (IdentifierStr == "def")
57 if (IdentifierStr == "extern")
59 return tok_identifier;
62 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
67 } while (isdigit(LastChar) || LastChar == '.');
69 NumVal = strtod(NumStr.c_str(), 0);
73 if (LastChar == '#') {
74 // Comment until end of line.
77 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
83 // Check for end of file. Don't eat the EOF.
87 // Otherwise, just return the character as its ascii value.
88 int ThisChar = LastChar;
93 //===----------------------------------------------------------------------===//
94 // Abstract Syntax Tree (aka Parse Tree)
95 //===----------------------------------------------------------------------===//
97 /// ExprAST - Base class for all expression nodes.
100 virtual ~ExprAST() {}
101 virtual Value *codegen() = 0;
104 /// NumberExprAST - Expression class for numeric literals like "1.0".
105 class NumberExprAST : public ExprAST {
109 NumberExprAST(double Val) : Val(Val) {}
110 Value *codegen() override;
113 /// VariableExprAST - Expression class for referencing a variable, like "a".
114 class VariableExprAST : public ExprAST {
118 VariableExprAST(const std::string &Name) : Name(Name) {}
119 Value *codegen() override;
122 /// BinaryExprAST - Expression class for a binary operator.
123 class BinaryExprAST : public ExprAST {
125 std::unique_ptr<ExprAST> LHS, RHS;
128 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
129 std::unique_ptr<ExprAST> RHS)
130 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
131 Value *codegen() override;
134 /// CallExprAST - Expression class for function calls.
135 class CallExprAST : public ExprAST {
137 std::vector<std::unique_ptr<ExprAST>> Args;
140 CallExprAST(const std::string &Callee,
141 std::vector<std::unique_ptr<ExprAST>> Args)
142 : Callee(Callee), Args(std::move(Args)) {}
143 Value *codegen() override;
146 /// PrototypeAST - This class represents the "prototype" for a function,
147 /// which captures its name, and its argument names (thus implicitly the number
148 /// of arguments the function takes).
151 std::vector<std::string> Args;
154 PrototypeAST(const std::string &Name, std::vector<std::string> Args)
155 : Name(Name), Args(std::move(Args)) {}
157 const std::string &getName() const { return Name; }
160 /// FunctionAST - This class represents a function definition itself.
162 std::unique_ptr<PrototypeAST> Proto;
163 std::unique_ptr<ExprAST> Body;
166 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
167 std::unique_ptr<ExprAST> Body)
168 : Proto(std::move(Proto)), Body(std::move(Body)) {}
171 } // end anonymous namespace
173 //===----------------------------------------------------------------------===//
175 //===----------------------------------------------------------------------===//
177 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
178 /// token the parser is looking at. getNextToken reads another token from the
179 /// lexer and updates CurTok with its results.
181 static int getNextToken() { return CurTok = gettok(); }
183 /// BinopPrecedence - This holds the precedence for each binary operator that is
185 static std::map<char, int> BinopPrecedence;
187 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
188 static int GetTokPrecedence() {
189 if (!isascii(CurTok))
192 // Make sure it's a declared binop.
193 int TokPrec = BinopPrecedence[CurTok];
199 /// Error* - These are little helper functions for error handling.
200 std::unique_ptr<ExprAST> Error(const char *Str) {
201 fprintf(stderr, "Error: %s\n", Str);
204 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
209 static std::unique_ptr<ExprAST> ParseExpression();
211 /// numberexpr ::= number
212 static std::unique_ptr<ExprAST> ParseNumberExpr() {
213 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
214 getNextToken(); // consume the number
215 return std::move(Result);
218 /// parenexpr ::= '(' expression ')'
219 static std::unique_ptr<ExprAST> ParseParenExpr() {
220 getNextToken(); // eat (.
221 auto V = ParseExpression();
226 return Error("expected ')'");
227 getNextToken(); // eat ).
233 /// ::= identifier '(' expression* ')'
234 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
235 std::string IdName = IdentifierStr;
237 getNextToken(); // eat identifier.
239 if (CurTok != '(') // Simple variable ref.
240 return llvm::make_unique<VariableExprAST>(IdName);
243 getNextToken(); // eat (
244 std::vector<std::unique_ptr<ExprAST>> Args;
247 if (auto Arg = ParseExpression())
248 Args.push_back(std::move(Arg));
256 return Error("Expected ')' or ',' in argument list");
264 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
268 /// ::= identifierexpr
271 static std::unique_ptr<ExprAST> ParsePrimary() {
274 return Error("unknown token when expecting an expression");
276 return ParseIdentifierExpr();
278 return ParseNumberExpr();
280 return ParseParenExpr();
285 /// ::= ('+' primary)*
286 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
287 std::unique_ptr<ExprAST> LHS) {
288 // If this is a binop, find its precedence.
290 int TokPrec = GetTokPrecedence();
292 // If this is a binop that binds at least as tightly as the current binop,
293 // consume it, otherwise we are done.
294 if (TokPrec < ExprPrec)
297 // Okay, we know this is a binop.
299 getNextToken(); // eat binop
301 // Parse the primary expression after the binary operator.
302 auto RHS = ParsePrimary();
306 // If BinOp binds less tightly with RHS than the operator after RHS, let
307 // the pending operator take RHS as its LHS.
308 int NextPrec = GetTokPrecedence();
309 if (TokPrec < NextPrec) {
310 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
317 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
322 /// ::= primary binoprhs
324 static std::unique_ptr<ExprAST> ParseExpression() {
325 auto LHS = ParsePrimary();
329 return ParseBinOpRHS(0, std::move(LHS));
333 /// ::= id '(' id* ')'
334 static std::unique_ptr<PrototypeAST> ParsePrototype() {
335 if (CurTok != tok_identifier)
336 return ErrorP("Expected function name in prototype");
338 std::string FnName = IdentifierStr;
342 return ErrorP("Expected '(' in prototype");
344 std::vector<std::string> ArgNames;
345 while (getNextToken() == tok_identifier)
346 ArgNames.push_back(IdentifierStr);
348 return ErrorP("Expected ')' in prototype");
351 getNextToken(); // eat ')'.
353 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
356 /// definition ::= 'def' prototype expression
357 static std::unique_ptr<FunctionAST> ParseDefinition() {
358 getNextToken(); // eat def.
359 auto Proto = ParsePrototype();
363 if (auto E = ParseExpression())
364 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
368 /// toplevelexpr ::= expression
369 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
370 if (auto E = ParseExpression()) {
371 // Make an anonymous proto.
372 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
373 std::vector<std::string>());
374 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
379 /// external ::= 'extern' prototype
380 static std::unique_ptr<PrototypeAST> ParseExtern() {
381 getNextToken(); // eat extern.
382 return ParsePrototype();
385 //===----------------------------------------------------------------------===//
387 //===----------------------------------------------------------------------===//
389 static std::unique_ptr<Module> TheModule;
390 static IRBuilder<> Builder(getGlobalContext());
391 static std::map<std::string, Value *> NamedValues;
392 static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
393 static std::unique_ptr<KaleidoscopeJIT> TheJIT;
394 static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
396 Value *ErrorV(const char *Str) {
401 Function *getFunction(std::string Name) {
402 // First, see if the function has already been added to the current module.
403 if (auto *F = TheModule->getFunction(Name))
406 // If not, check whether we can codegen the declaration from some existing
408 auto FI = FunctionProtos.find(Name);
409 if (FI != FunctionProtos.end())
410 return FI->second->codegen();
412 // If no existing prototype exists, return null.
416 Value *NumberExprAST::codegen() {
417 return ConstantFP::get(getGlobalContext(), APFloat(Val));
420 Value *VariableExprAST::codegen() {
421 // Look this variable up in the function.
422 Value *V = NamedValues[Name];
424 return ErrorV("Unknown variable name");
428 Value *BinaryExprAST::codegen() {
429 Value *L = LHS->codegen();
430 Value *R = RHS->codegen();
436 return Builder.CreateFAdd(L, R, "addtmp");
438 return Builder.CreateFSub(L, R, "subtmp");
440 return Builder.CreateFMul(L, R, "multmp");
442 L = Builder.CreateFCmpULT(L, R, "cmptmp");
443 // Convert bool 0/1 to double 0.0 or 1.0
444 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
447 return ErrorV("invalid binary operator");
451 Value *CallExprAST::codegen() {
452 // Look up the name in the global module table.
453 Function *CalleeF = getFunction(Callee);
455 return ErrorV("Unknown function referenced");
457 // If argument mismatch error.
458 if (CalleeF->arg_size() != Args.size())
459 return ErrorV("Incorrect # arguments passed");
461 std::vector<Value *> ArgsV;
462 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
463 ArgsV.push_back(Args[i]->codegen());
468 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
471 Function *PrototypeAST::codegen() {
472 // Make the function type: double(double,double) etc.
473 std::vector<Type *> Doubles(Args.size(),
474 Type::getDoubleTy(getGlobalContext()));
476 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
479 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
481 // Set names for all arguments.
483 for (auto &Arg : F->args())
484 Arg.setName(Args[Idx++]);
489 Function *FunctionAST::codegen() {
490 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
491 // reference to it for use below.
493 FunctionProtos[Proto->getName()] = std::move(Proto);
494 Function *TheFunction = getFunction(P.getName());
498 // Create a new basic block to start insertion into.
499 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
500 Builder.SetInsertPoint(BB);
502 // Record the function arguments in the NamedValues map.
504 for (auto &Arg : TheFunction->args())
505 NamedValues[Arg.getName()] = &Arg;
507 if (Value *RetVal = Body->codegen()) {
508 // Finish off the function.
509 Builder.CreateRet(RetVal);
511 // Validate the generated code, checking for consistency.
512 verifyFunction(*TheFunction);
514 // Run the optimizer on the function.
515 TheFPM->run(*TheFunction);
520 // Error reading body, remove function.
521 TheFunction->eraseFromParent();
525 //===----------------------------------------------------------------------===//
526 // Top-Level parsing and JIT Driver
527 //===----------------------------------------------------------------------===//
529 static void InitializeModuleAndPassManager() {
530 // Open a new module.
531 TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
532 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
534 // Create a new pass manager attached to it.
535 TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
537 // Provide basic AliasAnalysis support for GVN.
538 TheFPM->add(createBasicAliasAnalysisPass());
539 // Do simple "peephole" optimizations and bit-twiddling optzns.
540 TheFPM->add(createInstructionCombiningPass());
541 // Reassociate expressions.
542 TheFPM->add(createReassociatePass());
543 // Eliminate Common SubExpressions.
544 TheFPM->add(createGVNPass());
545 // Simplify the control flow graph (deleting unreachable blocks, etc).
546 TheFPM->add(createCFGSimplificationPass());
548 TheFPM->doInitialization();
551 static void HandleDefinition() {
552 if (auto FnAST = ParseDefinition()) {
553 if (auto *FnIR = FnAST->codegen()) {
554 fprintf(stderr, "Read function definition:");
556 TheJIT->addModule(std::move(TheModule));
557 InitializeModuleAndPassManager();
560 // Skip token for error recovery.
565 static void HandleExtern() {
566 if (auto ProtoAST = ParseExtern()) {
567 if (auto *FnIR = ProtoAST->codegen()) {
568 fprintf(stderr, "Read extern: ");
570 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
573 // Skip token for error recovery.
578 static void HandleTopLevelExpression() {
579 // Evaluate a top-level expression into an anonymous function.
580 if (auto FnAST = ParseTopLevelExpr()) {
581 if (FnAST->codegen()) {
583 // JIT the module containing the anonymous expression, keeping a handle so
584 // we can free it later.
585 auto H = TheJIT->addModule(std::move(TheModule));
586 InitializeModuleAndPassManager();
588 // Search the JIT for the __anon_expr symbol.
589 auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
590 assert(ExprSymbol && "Function not found");
592 // Get the symbol's address and cast it to the right type (takes no
593 // arguments, returns a double) so we can call it as a native function.
594 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
595 fprintf(stderr, "Evaluated to %f\n", FP());
597 // Delete the anonymous expression module from the JIT.
598 TheJIT->removeModule(H);
601 // Skip token for error recovery.
606 /// top ::= definition | external | expression | ';'
607 static void MainLoop() {
609 fprintf(stderr, "ready> ");
613 case ';': // ignore top-level semicolons.
623 HandleTopLevelExpression();
629 //===----------------------------------------------------------------------===//
630 // "Library" functions that can be "extern'd" from user code.
631 //===----------------------------------------------------------------------===//
633 /// putchard - putchar that takes a double and returns 0.
634 __attribute__((used)) extern "C" double putchard(double X) {
635 fputc((char)X, stderr);
639 /// printd - printf that takes a double prints it as "%f\n", returning 0.
640 __attribute__((used)) extern "C" double printd(double X) {
641 fprintf(stderr, "%f\n", X);
645 //===----------------------------------------------------------------------===//
647 //===----------------------------------------------------------------------===//
650 InitializeNativeTarget();
651 InitializeNativeTargetAsmPrinter();
652 InitializeNativeTargetAsmParser();
654 // Install standard binary operators.
655 // 1 is lowest precedence.
656 BinopPrecedence['<'] = 10;
657 BinopPrecedence['+'] = 20;
658 BinopPrecedence['-'] = 20;
659 BinopPrecedence['*'] = 40; // highest.
661 // Prime the first token.
662 fprintf(stderr, "ready> ");
665 TheJIT = llvm::make_unique<KaleidoscopeJIT>();
667 InitializeModuleAndPassManager();
669 // Run the main "interpreter loop" now.