1 #include "llvm/DerivedTypes.h"
2 #include "llvm/LLVMContext.h"
3 #include "llvm/Module.h"
4 #include "llvm/Analysis/Verifier.h"
5 #include "llvm/Support/IRBuilder.h"
12 //===----------------------------------------------------------------------===//
14 //===----------------------------------------------------------------------===//
16 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
17 // of these for known things.
22 tok_def = -2, tok_extern = -3,
25 tok_identifier = -4, tok_number = -5
28 static std::string IdentifierStr; // Filled in if tok_identifier
29 static double NumVal; // Filled in if tok_number
31 /// gettok - Return the next token from standard input.
33 static int LastChar = ' ';
35 // Skip any whitespace.
36 while (isspace(LastChar))
39 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
40 IdentifierStr = LastChar;
41 while (isalnum((LastChar = getchar())))
42 IdentifierStr += LastChar;
44 if (IdentifierStr == "def") return tok_def;
45 if (IdentifierStr == "extern") return tok_extern;
46 return tok_identifier;
49 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
54 } while (isdigit(LastChar) || LastChar == '.');
56 NumVal = strtod(NumStr.c_str(), 0);
60 if (LastChar == '#') {
61 // Comment until end of line.
62 do LastChar = getchar();
63 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
69 // Check for end of file. Don't eat the EOF.
73 // Otherwise, just return the character as its ascii value.
74 int ThisChar = LastChar;
79 //===----------------------------------------------------------------------===//
80 // Abstract Syntax Tree (aka Parse Tree)
81 //===----------------------------------------------------------------------===//
83 /// ExprAST - Base class for all expression nodes.
87 virtual Value *Codegen() = 0;
90 /// NumberExprAST - Expression class for numeric literals like "1.0".
91 class NumberExprAST : public ExprAST {
94 NumberExprAST(double val) : Val(val) {}
95 virtual Value *Codegen();
98 /// VariableExprAST - Expression class for referencing a variable, like "a".
99 class VariableExprAST : public ExprAST {
102 VariableExprAST(const std::string &name) : Name(name) {}
103 virtual Value *Codegen();
106 /// BinaryExprAST - Expression class for a binary operator.
107 class BinaryExprAST : public ExprAST {
111 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
112 : Op(op), LHS(lhs), RHS(rhs) {}
113 virtual Value *Codegen();
116 /// CallExprAST - Expression class for function calls.
117 class CallExprAST : public ExprAST {
119 std::vector<ExprAST*> Args;
121 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
122 : Callee(callee), Args(args) {}
123 virtual Value *Codegen();
126 /// PrototypeAST - This class represents the "prototype" for a function,
127 /// which captures its name, and its argument names (thus implicitly the number
128 /// of arguments the function takes).
131 std::vector<std::string> Args;
133 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
134 : Name(name), Args(args) {}
139 /// FunctionAST - This class represents a function definition itself.
144 FunctionAST(PrototypeAST *proto, ExprAST *body)
145 : Proto(proto), Body(body) {}
150 //===----------------------------------------------------------------------===//
152 //===----------------------------------------------------------------------===//
154 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
155 /// token the parser is looking at. getNextToken reads another token from the
156 /// lexer and updates CurTok with its results.
158 static int getNextToken() {
159 return CurTok = gettok();
162 /// BinopPrecedence - This holds the precedence for each binary operator that is
164 static std::map<char, int> BinopPrecedence;
166 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
167 static int GetTokPrecedence() {
168 if (!isascii(CurTok))
171 // Make sure it's a declared binop.
172 int TokPrec = BinopPrecedence[CurTok];
173 if (TokPrec <= 0) return -1;
177 /// Error* - These are little helper functions for error handling.
178 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
179 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
180 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
182 static ExprAST *ParseExpression();
186 /// ::= identifier '(' expression* ')'
187 static ExprAST *ParseIdentifierExpr() {
188 std::string IdName = IdentifierStr;
190 getNextToken(); // eat identifier.
192 if (CurTok != '(') // Simple variable ref.
193 return new VariableExprAST(IdName);
196 getNextToken(); // eat (
197 std::vector<ExprAST*> Args;
200 ExprAST *Arg = ParseExpression();
204 if (CurTok == ')') break;
207 return Error("Expected ')' or ',' in argument list");
215 return new CallExprAST(IdName, Args);
218 /// numberexpr ::= number
219 static ExprAST *ParseNumberExpr() {
220 ExprAST *Result = new NumberExprAST(NumVal);
221 getNextToken(); // consume the number
225 /// parenexpr ::= '(' expression ')'
226 static ExprAST *ParseParenExpr() {
227 getNextToken(); // eat (.
228 ExprAST *V = ParseExpression();
232 return Error("expected ')'");
233 getNextToken(); // eat ).
238 /// ::= identifierexpr
241 static ExprAST *ParsePrimary() {
243 default: return Error("unknown token when expecting an expression");
244 case tok_identifier: return ParseIdentifierExpr();
245 case tok_number: return ParseNumberExpr();
246 case '(': return ParseParenExpr();
251 /// ::= ('+' primary)*
252 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
253 // If this is a binop, find its precedence.
255 int TokPrec = GetTokPrecedence();
257 // If this is a binop that binds at least as tightly as the current binop,
258 // consume it, otherwise we are done.
259 if (TokPrec < ExprPrec)
262 // Okay, we know this is a binop.
264 getNextToken(); // eat binop
266 // Parse the primary expression after the binary operator.
267 ExprAST *RHS = ParsePrimary();
270 // If BinOp binds less tightly with RHS than the operator after RHS, let
271 // the pending operator take RHS as its LHS.
272 int NextPrec = GetTokPrecedence();
273 if (TokPrec < NextPrec) {
274 RHS = ParseBinOpRHS(TokPrec+1, RHS);
275 if (RHS == 0) return 0;
279 LHS = new BinaryExprAST(BinOp, LHS, RHS);
284 /// ::= primary binoprhs
286 static ExprAST *ParseExpression() {
287 ExprAST *LHS = ParsePrimary();
290 return ParseBinOpRHS(0, LHS);
294 /// ::= id '(' id* ')'
295 static PrototypeAST *ParsePrototype() {
296 if (CurTok != tok_identifier)
297 return ErrorP("Expected function name in prototype");
299 std::string FnName = IdentifierStr;
303 return ErrorP("Expected '(' in prototype");
305 std::vector<std::string> ArgNames;
306 while (getNextToken() == tok_identifier)
307 ArgNames.push_back(IdentifierStr);
309 return ErrorP("Expected ')' in prototype");
312 getNextToken(); // eat ')'.
314 return new PrototypeAST(FnName, ArgNames);
317 /// definition ::= 'def' prototype expression
318 static FunctionAST *ParseDefinition() {
319 getNextToken(); // eat def.
320 PrototypeAST *Proto = ParsePrototype();
321 if (Proto == 0) return 0;
323 if (ExprAST *E = ParseExpression())
324 return new FunctionAST(Proto, E);
328 /// toplevelexpr ::= expression
329 static FunctionAST *ParseTopLevelExpr() {
330 if (ExprAST *E = ParseExpression()) {
331 // Make an anonymous proto.
332 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
333 return new FunctionAST(Proto, E);
338 /// external ::= 'extern' prototype
339 static PrototypeAST *ParseExtern() {
340 getNextToken(); // eat extern.
341 return ParsePrototype();
344 //===----------------------------------------------------------------------===//
346 //===----------------------------------------------------------------------===//
348 static Module *TheModule;
349 static IRBuilder<> Builder(getGlobalContext());
350 static std::map<std::string, Value*> NamedValues;
352 Value *ErrorV(const char *Str) { Error(Str); return 0; }
354 Value *NumberExprAST::Codegen() {
355 return ConstantFP::get(getGlobalContext(), APFloat(Val));
358 Value *VariableExprAST::Codegen() {
359 // Look this variable up in the function.
360 Value *V = NamedValues[Name];
361 return V ? V : ErrorV("Unknown variable name");
364 Value *BinaryExprAST::Codegen() {
365 Value *L = LHS->Codegen();
366 Value *R = RHS->Codegen();
367 if (L == 0 || R == 0) return 0;
370 case '+': return Builder.CreateFAdd(L, R, "addtmp");
371 case '-': return Builder.CreateFSub(L, R, "subtmp");
372 case '*': return Builder.CreateFMul(L, R, "multmp");
374 L = Builder.CreateFCmpULT(L, R, "cmptmp");
375 // Convert bool 0/1 to double 0.0 or 1.0
376 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
378 default: return ErrorV("invalid binary operator");
382 Value *CallExprAST::Codegen() {
383 // Look up the name in the global module table.
384 Function *CalleeF = TheModule->getFunction(Callee);
386 return ErrorV("Unknown function referenced");
388 // If argument mismatch error.
389 if (CalleeF->arg_size() != Args.size())
390 return ErrorV("Incorrect # arguments passed");
392 std::vector<Value*> ArgsV;
393 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
394 ArgsV.push_back(Args[i]->Codegen());
395 if (ArgsV.back() == 0) return 0;
398 return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
401 Function *PrototypeAST::Codegen() {
402 // Make the function type: double(double,double) etc.
403 std::vector<const Type*> Doubles(Args.size(),
404 Type::getDoubleTy(getGlobalContext()));
405 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
408 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
410 // If F conflicted, there was already something named 'Name'. If it has a
411 // body, don't allow redefinition or reextern.
412 if (F->getName() != Name) {
413 // Delete the one we just made and get the existing one.
414 F->eraseFromParent();
415 F = TheModule->getFunction(Name);
417 // If F already has a body, reject this.
419 ErrorF("redefinition of function");
423 // If F took a different number of args, reject.
424 if (F->arg_size() != Args.size()) {
425 ErrorF("redefinition of function with different # args");
430 // Set names for all arguments.
432 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
434 AI->setName(Args[Idx]);
436 // Add arguments to variable symbol table.
437 NamedValues[Args[Idx]] = AI;
443 Function *FunctionAST::Codegen() {
446 Function *TheFunction = Proto->Codegen();
447 if (TheFunction == 0)
450 // Create a new basic block to start insertion into.
451 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
452 Builder.SetInsertPoint(BB);
454 if (Value *RetVal = Body->Codegen()) {
455 // Finish off the function.
456 Builder.CreateRet(RetVal);
458 // Validate the generated code, checking for consistency.
459 verifyFunction(*TheFunction);
464 // Error reading body, remove function.
465 TheFunction->eraseFromParent();
469 //===----------------------------------------------------------------------===//
470 // Top-Level parsing and JIT Driver
471 //===----------------------------------------------------------------------===//
473 static void HandleDefinition() {
474 if (FunctionAST *F = ParseDefinition()) {
475 if (Function *LF = F->Codegen()) {
476 fprintf(stderr, "Read function definition:");
480 // Skip token for error recovery.
485 static void HandleExtern() {
486 if (PrototypeAST *P = ParseExtern()) {
487 if (Function *F = P->Codegen()) {
488 fprintf(stderr, "Read extern: ");
492 // Skip token for error recovery.
497 static void HandleTopLevelExpression() {
498 // Evaluate a top-level expression into an anonymous function.
499 if (FunctionAST *F = ParseTopLevelExpr()) {
500 if (Function *LF = F->Codegen()) {
501 fprintf(stderr, "Read top-level expression:");
505 // Skip token for error recovery.
510 /// top ::= definition | external | expression | ';'
511 static void MainLoop() {
513 fprintf(stderr, "ready> ");
515 case tok_eof: return;
516 case ';': getNextToken(); break; // ignore top-level semicolons.
517 case tok_def: HandleDefinition(); break;
518 case tok_extern: HandleExtern(); break;
519 default: HandleTopLevelExpression(); break;
524 //===----------------------------------------------------------------------===//
525 // "Library" functions that can be "extern'd" from user code.
526 //===----------------------------------------------------------------------===//
528 /// putchard - putchar that takes a double and returns 0.
530 double putchard(double X) {
535 //===----------------------------------------------------------------------===//
537 //===----------------------------------------------------------------------===//
540 LLVMContext &Context = getGlobalContext();
542 // Install standard binary operators.
543 // 1 is lowest precedence.
544 BinopPrecedence['<'] = 10;
545 BinopPrecedence['+'] = 20;
546 BinopPrecedence['-'] = 20;
547 BinopPrecedence['*'] = 40; // highest.
549 // Prime the first token.
550 fprintf(stderr, "ready> ");
553 // Make the module, which holds all the code.
554 TheModule = new Module("my cool jit", Context);
556 // Run the main "interpreter loop" now.
559 // Print out all of the generated code.