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.
31 tok_def = -2, tok_extern = -3,
34 tok_identifier = -4, tok_number = -5
37 static std::string IdentifierStr; // Filled in if tok_identifier
38 static double NumVal; // Filled in if tok_number
40 /// gettok - Return the next token from standard input.
42 static int LastChar = ' ';
44 // Skip any whitespace.
45 while (isspace(LastChar))
48 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
49 IdentifierStr = LastChar;
50 while (isalnum((LastChar = getchar())))
51 IdentifierStr += LastChar;
53 if (IdentifierStr == "def") return tok_def;
54 if (IdentifierStr == "extern") return tok_extern;
55 return tok_identifier;
58 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
63 } while (isdigit(LastChar) || LastChar == '.');
65 NumVal = strtod(NumStr.c_str(), 0);
69 if (LastChar == '#') {
70 // Comment until end of line.
71 do LastChar = getchar();
72 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
78 // Check for end of file. Don't eat the EOF.
82 // Otherwise, just return the character as its ascii value.
83 int ThisChar = LastChar;
88 //===----------------------------------------------------------------------===//
89 // Abstract Syntax Tree (aka Parse Tree)
90 //===----------------------------------------------------------------------===//
92 /// ExprAST - Base class for all expression nodes.
96 virtual Value *Codegen() = 0;
99 /// NumberExprAST - Expression class for numeric literals like "1.0".
100 class NumberExprAST : public ExprAST {
103 NumberExprAST(double val) : Val(val) {}
104 virtual Value *Codegen();
107 /// VariableExprAST - Expression class for referencing a variable, like "a".
108 class VariableExprAST : public ExprAST {
111 VariableExprAST(const std::string &name) : Name(name) {}
112 virtual Value *Codegen();
115 /// BinaryExprAST - Expression class for a binary operator.
116 class BinaryExprAST : public ExprAST {
120 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
121 : Op(op), LHS(lhs), RHS(rhs) {}
122 virtual Value *Codegen();
125 /// CallExprAST - Expression class for function calls.
126 class CallExprAST : public ExprAST {
128 std::vector<ExprAST*> Args;
130 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
131 : Callee(callee), Args(args) {}
132 virtual Value *Codegen();
135 /// PrototypeAST - This class represents the "prototype" for a function,
136 /// which captures its name, and its argument names (thus implicitly the number
137 /// of arguments the function takes).
140 std::vector<std::string> Args;
142 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
143 : Name(name), Args(args) {}
148 /// FunctionAST - This class represents a function definition itself.
153 FunctionAST(PrototypeAST *proto, ExprAST *body)
154 : Proto(proto), Body(body) {}
158 } // end anonymous namespace
160 //===----------------------------------------------------------------------===//
162 //===----------------------------------------------------------------------===//
164 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
165 /// token the parser is looking at. getNextToken reads another token from the
166 /// lexer and updates CurTok with its results.
168 static int getNextToken() {
169 return CurTok = gettok();
172 /// BinopPrecedence - This holds the precedence for each binary operator that is
174 static std::map<char, int> BinopPrecedence;
176 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
177 static int GetTokPrecedence() {
178 if (!isascii(CurTok))
181 // Make sure it's a declared binop.
182 int TokPrec = BinopPrecedence[CurTok];
183 if (TokPrec <= 0) return -1;
187 /// Error* - These are little helper functions for error handling.
188 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
189 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
190 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
192 static ExprAST *ParseExpression();
196 /// ::= identifier '(' expression* ')'
197 static ExprAST *ParseIdentifierExpr() {
198 std::string IdName = IdentifierStr;
200 getNextToken(); // eat identifier.
202 if (CurTok != '(') // Simple variable ref.
203 return new VariableExprAST(IdName);
206 getNextToken(); // eat (
207 std::vector<ExprAST*> Args;
210 ExprAST *Arg = ParseExpression();
214 if (CurTok == ')') break;
217 return Error("Expected ')' or ',' in argument list");
225 return new CallExprAST(IdName, Args);
228 /// numberexpr ::= number
229 static ExprAST *ParseNumberExpr() {
230 ExprAST *Result = new NumberExprAST(NumVal);
231 getNextToken(); // consume the number
235 /// parenexpr ::= '(' expression ')'
236 static ExprAST *ParseParenExpr() {
237 getNextToken(); // eat (.
238 ExprAST *V = ParseExpression();
242 return Error("expected ')'");
243 getNextToken(); // eat ).
248 /// ::= identifierexpr
251 static ExprAST *ParsePrimary() {
253 default: return Error("unknown token when expecting an expression");
254 case tok_identifier: return ParseIdentifierExpr();
255 case tok_number: return ParseNumberExpr();
256 case '(': return ParseParenExpr();
261 /// ::= ('+' primary)*
262 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
263 // If this is a binop, find its precedence.
265 int TokPrec = GetTokPrecedence();
267 // If this is a binop that binds at least as tightly as the current binop,
268 // consume it, otherwise we are done.
269 if (TokPrec < ExprPrec)
272 // Okay, we know this is a binop.
274 getNextToken(); // eat binop
276 // Parse the primary expression after the binary operator.
277 ExprAST *RHS = ParsePrimary();
280 // If BinOp binds less tightly with RHS than the operator after RHS, let
281 // the pending operator take RHS as its LHS.
282 int NextPrec = GetTokPrecedence();
283 if (TokPrec < NextPrec) {
284 RHS = ParseBinOpRHS(TokPrec+1, RHS);
285 if (RHS == 0) return 0;
289 LHS = new BinaryExprAST(BinOp, LHS, RHS);
294 /// ::= primary binoprhs
296 static ExprAST *ParseExpression() {
297 ExprAST *LHS = ParsePrimary();
300 return ParseBinOpRHS(0, LHS);
304 /// ::= id '(' id* ')'
305 static PrototypeAST *ParsePrototype() {
306 if (CurTok != tok_identifier)
307 return ErrorP("Expected function name in prototype");
309 std::string FnName = IdentifierStr;
313 return ErrorP("Expected '(' in prototype");
315 std::vector<std::string> ArgNames;
316 while (getNextToken() == tok_identifier)
317 ArgNames.push_back(IdentifierStr);
319 return ErrorP("Expected ')' in prototype");
322 getNextToken(); // eat ')'.
324 return new PrototypeAST(FnName, ArgNames);
327 /// definition ::= 'def' prototype expression
328 static FunctionAST *ParseDefinition() {
329 getNextToken(); // eat def.
330 PrototypeAST *Proto = ParsePrototype();
331 if (Proto == 0) return 0;
333 if (ExprAST *E = ParseExpression())
334 return new FunctionAST(Proto, E);
338 /// toplevelexpr ::= expression
339 static FunctionAST *ParseTopLevelExpr() {
340 if (ExprAST *E = ParseExpression()) {
341 // Make an anonymous proto.
342 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
343 return new FunctionAST(Proto, E);
348 /// external ::= 'extern' prototype
349 static PrototypeAST *ParseExtern() {
350 getNextToken(); // eat extern.
351 return ParsePrototype();
354 //===----------------------------------------------------------------------===//
356 //===----------------------------------------------------------------------===//
358 static Module *TheModule;
359 static IRBuilder<> Builder(getGlobalContext());
360 static std::map<std::string, Value*> NamedValues;
361 static FunctionPassManager *TheFPM;
363 Value *ErrorV(const char *Str) { Error(Str); return 0; }
365 Value *NumberExprAST::Codegen() {
366 return ConstantFP::get(getGlobalContext(), APFloat(Val));
369 Value *VariableExprAST::Codegen() {
370 // Look this variable up in the function.
371 Value *V = NamedValues[Name];
372 return V ? V : ErrorV("Unknown variable name");
375 Value *BinaryExprAST::Codegen() {
376 Value *L = LHS->Codegen();
377 Value *R = RHS->Codegen();
378 if (L == 0 || R == 0) return 0;
381 case '+': return Builder.CreateFAdd(L, R, "addtmp");
382 case '-': return Builder.CreateFSub(L, R, "subtmp");
383 case '*': return Builder.CreateFMul(L, R, "multmp");
385 L = Builder.CreateFCmpULT(L, R, "cmptmp");
386 // Convert bool 0/1 to double 0.0 or 1.0
387 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
389 default: return ErrorV("invalid binary operator");
393 Value *CallExprAST::Codegen() {
394 // Look up the name in the global module table.
395 Function *CalleeF = TheModule->getFunction(Callee);
397 return ErrorV("Unknown function referenced");
399 // If argument mismatch error.
400 if (CalleeF->arg_size() != Args.size())
401 return ErrorV("Incorrect # arguments passed");
403 std::vector<Value*> ArgsV;
404 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
405 ArgsV.push_back(Args[i]->Codegen());
406 if (ArgsV.back() == 0) return 0;
409 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
412 Function *PrototypeAST::Codegen() {
413 // Make the function type: double(double,double) etc.
414 std::vector<Type*> Doubles(Args.size(),
415 Type::getDoubleTy(getGlobalContext()));
416 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
419 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
421 // If F conflicted, there was already something named 'Name'. If it has a
422 // body, don't allow redefinition or reextern.
423 if (F->getName() != Name) {
424 // Delete the one we just made and get the existing one.
425 F->eraseFromParent();
426 F = TheModule->getFunction(Name);
428 // If F already has a body, reject this.
430 ErrorF("redefinition of function");
434 // If F took a different number of args, reject.
435 if (F->arg_size() != Args.size()) {
436 ErrorF("redefinition of function with different # args");
441 // Set names for all arguments.
443 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
445 AI->setName(Args[Idx]);
447 // Add arguments to variable symbol table.
448 NamedValues[Args[Idx]] = AI;
454 Function *FunctionAST::Codegen() {
457 Function *TheFunction = Proto->Codegen();
458 if (TheFunction == 0)
461 // Create a new basic block to start insertion into.
462 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
463 Builder.SetInsertPoint(BB);
465 if (Value *RetVal = Body->Codegen()) {
466 // Finish off the function.
467 Builder.CreateRet(RetVal);
469 // Validate the generated code, checking for consistency.
470 verifyFunction(*TheFunction);
472 // Optimize the function.
473 TheFPM->run(*TheFunction);
478 // Error reading body, remove function.
479 TheFunction->eraseFromParent();
483 //===----------------------------------------------------------------------===//
484 // Top-Level parsing and JIT Driver
485 //===----------------------------------------------------------------------===//
487 static ExecutionEngine *TheExecutionEngine;
489 static void HandleDefinition() {
490 if (FunctionAST *F = ParseDefinition()) {
491 if (Function *LF = F->Codegen()) {
492 fprintf(stderr, "Read function definition:");
496 // Skip token for error recovery.
501 static void HandleExtern() {
502 if (PrototypeAST *P = ParseExtern()) {
503 if (Function *F = P->Codegen()) {
504 fprintf(stderr, "Read extern: ");
508 // Skip token for error recovery.
513 static void HandleTopLevelExpression() {
514 // Evaluate a top-level expression into an anonymous function.
515 if (FunctionAST *F = ParseTopLevelExpr()) {
516 if (Function *LF = F->Codegen()) {
517 TheExecutionEngine->finalizeObject();
518 // JIT the function, returning a function pointer.
519 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
521 // Cast it to the right type (takes no arguments, returns a double) so we
522 // can call it as a native function.
523 double (*FP)() = (double (*)())(intptr_t)FPtr;
524 fprintf(stderr, "Evaluated to %f\n", FP());
527 // Skip token for error recovery.
532 /// top ::= definition | external | expression | ';'
533 static void MainLoop() {
535 fprintf(stderr, "ready> ");
537 case tok_eof: return;
538 case ';': getNextToken(); break; // ignore top-level semicolons.
539 case tok_def: HandleDefinition(); break;
540 case tok_extern: HandleExtern(); break;
541 default: HandleTopLevelExpression(); break;
546 //===----------------------------------------------------------------------===//
547 // "Library" functions that can be "extern'd" from user code.
548 //===----------------------------------------------------------------------===//
550 /// putchard - putchar that takes a double and returns 0.
552 double putchard(double X) {
557 //===----------------------------------------------------------------------===//
559 //===----------------------------------------------------------------------===//
562 InitializeNativeTarget();
563 InitializeNativeTargetAsmPrinter();
564 InitializeNativeTargetAsmParser();
565 LLVMContext &Context = getGlobalContext();
567 // Install standard binary operators.
568 // 1 is lowest precedence.
569 BinopPrecedence['<'] = 10;
570 BinopPrecedence['+'] = 20;
571 BinopPrecedence['-'] = 20;
572 BinopPrecedence['*'] = 40; // highest.
574 // Prime the first token.
575 fprintf(stderr, "ready> ");
578 // Make the module, which holds all the code.
579 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
580 TheModule = Owner.get();
582 // Create the JIT. This takes ownership of the module.
584 TheExecutionEngine = EngineBuilder(std::move(Owner))
585 .setErrorStr(&ErrStr)
586 .setMCJITMemoryManager(new SectionMemoryManager())
588 if (!TheExecutionEngine) {
589 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
593 FunctionPassManager OurFPM(TheModule);
595 // Set up the optimizer pipeline. Start with registering info about how the
596 // target lays out data structures.
597 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
598 OurFPM.add(new DataLayoutPass());
599 // Provide basic AliasAnalysis support for GVN.
600 OurFPM.add(createBasicAliasAnalysisPass());
601 // Do simple "peephole" optimizations and bit-twiddling optzns.
602 OurFPM.add(createInstructionCombiningPass());
603 // Reassociate expressions.
604 OurFPM.add(createReassociatePass());
605 // Eliminate Common SubExpressions.
606 OurFPM.add(createGVNPass());
607 // Simplify the control flow graph (deleting unreachable blocks, etc).
608 OurFPM.add(createCFGSimplificationPass());
610 OurFPM.doInitialization();
612 // Set the global so the code gen can use this.
615 // Run the main "interpreter loop" now.
620 // Print out all of the generated code.