1 #include "llvm/Analysis/Passes.h"
2 #include "llvm/ExecutionEngine/ExecutionEngine.h"
3 #include "llvm/ExecutionEngine/MCJIT.h"
4 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
5 #include "llvm/IR/DataLayout.h"
6 #include "llvm/IR/DerivedTypes.h"
7 #include "llvm/IR/IRBuilder.h"
8 #include "llvm/IR/LLVMContext.h"
9 #include "llvm/IR/Module.h"
10 #include "llvm/IR/Verifier.h"
11 #include "llvm/PassManager.h"
12 #include "llvm/Support/TargetSelect.h"
13 #include "llvm/Transforms/Scalar.h"
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 virtual Value *Codegen();
113 /// VariableExprAST - Expression class for referencing a variable, like "a".
114 class VariableExprAST : public ExprAST {
118 VariableExprAST(const std::string &name) : Name(name) {}
119 virtual Value *Codegen();
122 /// BinaryExprAST - Expression class for a binary operator.
123 class BinaryExprAST : public ExprAST {
128 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
129 : Op(op), LHS(lhs), RHS(rhs) {}
130 virtual Value *Codegen();
133 /// CallExprAST - Expression class for function calls.
134 class CallExprAST : public ExprAST {
136 std::vector<ExprAST *> Args;
139 CallExprAST(const std::string &callee, std::vector<ExprAST *> &args)
140 : Callee(callee), Args(args) {}
141 virtual Value *Codegen();
144 /// PrototypeAST - This class represents the "prototype" for a function,
145 /// which captures its name, and its argument names (thus implicitly the number
146 /// of arguments the function takes).
149 std::vector<std::string> Args;
152 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
153 : Name(name), Args(args) {}
158 /// FunctionAST - This class represents a function definition itself.
164 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
168 } // end anonymous namespace
170 //===----------------------------------------------------------------------===//
172 //===----------------------------------------------------------------------===//
174 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
175 /// token the parser is looking at. getNextToken reads another token from the
176 /// lexer and updates CurTok with its results.
178 static int getNextToken() { return CurTok = gettok(); }
180 /// BinopPrecedence - This holds the precedence for each binary operator that is
182 static std::map<char, int> BinopPrecedence;
184 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
185 static int GetTokPrecedence() {
186 if (!isascii(CurTok))
189 // Make sure it's a declared binop.
190 int TokPrec = BinopPrecedence[CurTok];
196 /// Error* - These are little helper functions for error handling.
197 ExprAST *Error(const char *Str) {
198 fprintf(stderr, "Error: %s\n", Str);
201 PrototypeAST *ErrorP(const char *Str) {
205 FunctionAST *ErrorF(const char *Str) {
210 static ExprAST *ParseExpression();
214 /// ::= identifier '(' expression* ')'
215 static ExprAST *ParseIdentifierExpr() {
216 std::string IdName = IdentifierStr;
218 getNextToken(); // eat identifier.
220 if (CurTok != '(') // Simple variable ref.
221 return new VariableExprAST(IdName);
224 getNextToken(); // eat (
225 std::vector<ExprAST *> Args;
228 ExprAST *Arg = ParseExpression();
237 return Error("Expected ')' or ',' in argument list");
245 return new CallExprAST(IdName, Args);
248 /// numberexpr ::= number
249 static ExprAST *ParseNumberExpr() {
250 ExprAST *Result = new NumberExprAST(NumVal);
251 getNextToken(); // consume the number
255 /// parenexpr ::= '(' expression ')'
256 static ExprAST *ParseParenExpr() {
257 getNextToken(); // eat (.
258 ExprAST *V = ParseExpression();
263 return Error("expected ')'");
264 getNextToken(); // eat ).
269 /// ::= identifierexpr
272 static ExprAST *ParsePrimary() {
275 return Error("unknown token when expecting an expression");
277 return ParseIdentifierExpr();
279 return ParseNumberExpr();
281 return ParseParenExpr();
286 /// ::= ('+' primary)*
287 static ExprAST *ParseBinOpRHS(int ExprPrec, 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 ExprAST *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, RHS);
316 LHS = new BinaryExprAST(BinOp, LHS, RHS);
321 /// ::= primary binoprhs
323 static ExprAST *ParseExpression() {
324 ExprAST *LHS = ParsePrimary();
328 return ParseBinOpRHS(0, LHS);
332 /// ::= id '(' id* ')'
333 static PrototypeAST *ParsePrototype() {
334 if (CurTok != tok_identifier)
335 return ErrorP("Expected function name in prototype");
337 std::string FnName = IdentifierStr;
341 return ErrorP("Expected '(' in prototype");
343 std::vector<std::string> ArgNames;
344 while (getNextToken() == tok_identifier)
345 ArgNames.push_back(IdentifierStr);
347 return ErrorP("Expected ')' in prototype");
350 getNextToken(); // eat ')'.
352 return new PrototypeAST(FnName, ArgNames);
355 /// definition ::= 'def' prototype expression
356 static FunctionAST *ParseDefinition() {
357 getNextToken(); // eat def.
358 PrototypeAST *Proto = ParsePrototype();
362 if (ExprAST *E = ParseExpression())
363 return new FunctionAST(Proto, E);
367 /// toplevelexpr ::= expression
368 static FunctionAST *ParseTopLevelExpr() {
369 if (ExprAST *E = ParseExpression()) {
370 // Make an anonymous proto.
371 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
372 return new FunctionAST(Proto, E);
377 /// external ::= 'extern' prototype
378 static PrototypeAST *ParseExtern() {
379 getNextToken(); // eat extern.
380 return ParsePrototype();
383 //===----------------------------------------------------------------------===//
385 //===----------------------------------------------------------------------===//
387 static Module *TheModule;
388 static IRBuilder<> Builder(getGlobalContext());
389 static std::map<std::string, Value *> NamedValues;
390 static FunctionPassManager *TheFPM;
392 Value *ErrorV(const char *Str) {
397 Value *NumberExprAST::Codegen() {
398 return ConstantFP::get(getGlobalContext(), APFloat(Val));
401 Value *VariableExprAST::Codegen() {
402 // Look this variable up in the function.
403 Value *V = NamedValues[Name];
404 return V ? V : ErrorV("Unknown variable name");
407 Value *BinaryExprAST::Codegen() {
408 Value *L = LHS->Codegen();
409 Value *R = RHS->Codegen();
410 if (L == 0 || R == 0)
415 return Builder.CreateFAdd(L, R, "addtmp");
417 return Builder.CreateFSub(L, R, "subtmp");
419 return Builder.CreateFMul(L, R, "multmp");
421 L = Builder.CreateFCmpULT(L, R, "cmptmp");
422 // Convert bool 0/1 to double 0.0 or 1.0
423 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
426 return ErrorV("invalid binary operator");
430 Value *CallExprAST::Codegen() {
431 // Look up the name in the global module table.
432 Function *CalleeF = TheModule->getFunction(Callee);
434 return ErrorV("Unknown function referenced");
436 // If argument mismatch error.
437 if (CalleeF->arg_size() != Args.size())
438 return ErrorV("Incorrect # arguments passed");
440 std::vector<Value *> ArgsV;
441 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
442 ArgsV.push_back(Args[i]->Codegen());
443 if (ArgsV.back() == 0)
447 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
450 Function *PrototypeAST::Codegen() {
451 // Make the function type: double(double,double) etc.
452 std::vector<Type *> Doubles(Args.size(),
453 Type::getDoubleTy(getGlobalContext()));
455 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
458 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
460 // If F conflicted, there was already something named 'Name'. If it has a
461 // body, don't allow redefinition or reextern.
462 if (F->getName() != Name) {
463 // Delete the one we just made and get the existing one.
464 F->eraseFromParent();
465 F = TheModule->getFunction(Name);
467 // If F already has a body, reject this.
469 ErrorF("redefinition of function");
473 // If F took a different number of args, reject.
474 if (F->arg_size() != Args.size()) {
475 ErrorF("redefinition of function with different # args");
480 // Set names for all arguments.
482 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
484 AI->setName(Args[Idx]);
486 // Add arguments to variable symbol table.
487 NamedValues[Args[Idx]] = AI;
493 Function *FunctionAST::Codegen() {
496 Function *TheFunction = Proto->Codegen();
497 if (TheFunction == 0)
500 // Create a new basic block to start insertion into.
501 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
502 Builder.SetInsertPoint(BB);
504 if (Value *RetVal = Body->Codegen()) {
505 // Finish off the function.
506 Builder.CreateRet(RetVal);
508 // Validate the generated code, checking for consistency.
509 verifyFunction(*TheFunction);
511 // Optimize the function.
512 TheFPM->run(*TheFunction);
517 // Error reading body, remove function.
518 TheFunction->eraseFromParent();
522 //===----------------------------------------------------------------------===//
523 // Top-Level parsing and JIT Driver
524 //===----------------------------------------------------------------------===//
526 static ExecutionEngine *TheExecutionEngine;
528 static void HandleDefinition() {
529 if (FunctionAST *F = ParseDefinition()) {
530 if (Function *LF = F->Codegen()) {
531 fprintf(stderr, "Read function definition:");
535 // Skip token for error recovery.
540 static void HandleExtern() {
541 if (PrototypeAST *P = ParseExtern()) {
542 if (Function *F = P->Codegen()) {
543 fprintf(stderr, "Read extern: ");
547 // Skip token for error recovery.
552 static void HandleTopLevelExpression() {
553 // Evaluate a top-level expression into an anonymous function.
554 if (FunctionAST *F = ParseTopLevelExpr()) {
555 if (Function *LF = F->Codegen()) {
556 TheExecutionEngine->finalizeObject();
557 // JIT the function, returning a function pointer.
558 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
560 // Cast it to the right type (takes no arguments, returns a double) so we
561 // can call it as a native function.
562 double (*FP)() = (double (*)())(intptr_t)FPtr;
563 fprintf(stderr, "Evaluated to %f\n", FP());
566 // Skip token for error recovery.
571 /// top ::= definition | external | expression | ';'
572 static void MainLoop() {
574 fprintf(stderr, "ready> ");
580 break; // ignore top-level semicolons.
588 HandleTopLevelExpression();
594 //===----------------------------------------------------------------------===//
595 // "Library" functions that can be "extern'd" from user code.
596 //===----------------------------------------------------------------------===//
598 /// putchard - putchar that takes a double and returns 0.
599 extern "C" double putchard(double X) {
604 //===----------------------------------------------------------------------===//
606 //===----------------------------------------------------------------------===//
609 InitializeNativeTarget();
610 InitializeNativeTargetAsmPrinter();
611 InitializeNativeTargetAsmParser();
612 LLVMContext &Context = getGlobalContext();
614 // Install standard binary operators.
615 // 1 is lowest precedence.
616 BinopPrecedence['<'] = 10;
617 BinopPrecedence['+'] = 20;
618 BinopPrecedence['-'] = 20;
619 BinopPrecedence['*'] = 40; // highest.
621 // Prime the first token.
622 fprintf(stderr, "ready> ");
625 // Make the module, which holds all the code.
626 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
627 TheModule = Owner.get();
629 // Create the JIT. This takes ownership of the module.
632 EngineBuilder(std::move(Owner))
633 .setErrorStr(&ErrStr)
634 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
636 if (!TheExecutionEngine) {
637 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
641 FunctionPassManager OurFPM(TheModule);
643 // Set up the optimizer pipeline. Start with registering info about how the
644 // target lays out data structures.
645 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
646 OurFPM.add(new DataLayoutPass());
647 // Provide basic AliasAnalysis support for GVN.
648 OurFPM.add(createBasicAliasAnalysisPass());
649 // Do simple "peephole" optimizations and bit-twiddling optzns.
650 OurFPM.add(createInstructionCombiningPass());
651 // Reassociate expressions.
652 OurFPM.add(createReassociatePass());
653 // Eliminate Common SubExpressions.
654 OurFPM.add(createGVNPass());
655 // Simplify the control flow graph (deleting unreachable blocks, etc).
656 OurFPM.add(createCFGSimplificationPass());
658 OurFPM.doInitialization();
660 // Set the global so the code gen can use this.
663 // Run the main "interpreter loop" now.
668 // Print out all of the generated code.