1 #include "llvm/Analysis/Verifier.h"
2 #include "llvm/IR/DerivedTypes.h"
3 #include "llvm/IR/IRBuilder.h"
4 #include "llvm/IR/LLVMContext.h"
5 #include "llvm/IR/Module.h"
13 //===----------------------------------------------------------------------===//
15 //===----------------------------------------------------------------------===//
17 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
18 // of these for known things.
23 tok_def = -2, tok_extern = -3,
26 tok_identifier = -4, tok_number = -5
29 static std::string IdentifierStr; // Filled in if tok_identifier
30 static double NumVal; // Filled in if tok_number
32 /// gettok - Return the next token from standard input.
34 static int LastChar = ' ';
36 // Skip any whitespace.
37 while (isspace(LastChar))
40 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
41 IdentifierStr = LastChar;
42 while (isalnum((LastChar = getchar())))
43 IdentifierStr += LastChar;
45 if (IdentifierStr == "def") return tok_def;
46 if (IdentifierStr == "extern") return tok_extern;
47 return tok_identifier;
50 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
55 } while (isdigit(LastChar) || LastChar == '.');
57 NumVal = strtod(NumStr.c_str(), 0);
61 if (LastChar == '#') {
62 // Comment until end of line.
63 do LastChar = getchar();
64 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
70 // Check for end of file. Don't eat the EOF.
74 // Otherwise, just return the character as its ascii value.
75 int ThisChar = LastChar;
80 //===----------------------------------------------------------------------===//
81 // Abstract Syntax Tree (aka Parse Tree)
82 //===----------------------------------------------------------------------===//
84 /// ExprAST - Base class for all expression nodes.
88 virtual Value *Codegen() = 0;
91 // Provide out-of-line definition to prevent weak vtable.
92 ExprAST::~ExprAST() {}
94 /// NumberExprAST - Expression class for numeric literals like "1.0".
95 class NumberExprAST : public ExprAST {
98 NumberExprAST(double val) : Val(val) {}
99 virtual Value *Codegen();
102 /// VariableExprAST - Expression class for referencing a variable, like "a".
103 class VariableExprAST : public ExprAST {
106 VariableExprAST(const std::string &name) : Name(name) {}
107 virtual Value *Codegen();
110 /// BinaryExprAST - Expression class for a binary operator.
111 class BinaryExprAST : public ExprAST {
115 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
116 : Op(op), LHS(lhs), RHS(rhs) {}
117 virtual Value *Codegen();
120 /// CallExprAST - Expression class for function calls.
121 class CallExprAST : public ExprAST {
123 std::vector<ExprAST*> Args;
125 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
126 : Callee(callee), Args(args) {}
127 virtual Value *Codegen();
130 /// PrototypeAST - This class represents the "prototype" for a function,
131 /// which captures its name, and its argument names (thus implicitly the number
132 /// of arguments the function takes).
135 std::vector<std::string> Args;
137 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
138 : Name(name), Args(args) {}
143 /// FunctionAST - This class represents a function definition itself.
148 FunctionAST(PrototypeAST *proto, ExprAST *body)
149 : Proto(proto), Body(body) {}
154 //===----------------------------------------------------------------------===//
156 //===----------------------------------------------------------------------===//
158 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
159 /// token the parser is looking at. getNextToken reads another token from the
160 /// lexer and updates CurTok with its results.
162 static int getNextToken() {
163 return CurTok = gettok();
166 /// BinopPrecedence - This holds the precedence for each binary operator that is
168 static std::map<char, int> BinopPrecedence;
170 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
171 static int GetTokPrecedence() {
172 if (!isascii(CurTok))
175 // Make sure it's a declared binop.
176 int TokPrec = BinopPrecedence[CurTok];
177 if (TokPrec <= 0) return -1;
181 /// Error* - These are little helper functions for error handling.
182 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
183 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
184 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
186 static ExprAST *ParseExpression();
190 /// ::= identifier '(' expression* ')'
191 static ExprAST *ParseIdentifierExpr() {
192 std::string IdName = IdentifierStr;
194 getNextToken(); // eat identifier.
196 if (CurTok != '(') // Simple variable ref.
197 return new VariableExprAST(IdName);
200 getNextToken(); // eat (
201 std::vector<ExprAST*> Args;
204 ExprAST *Arg = ParseExpression();
208 if (CurTok == ')') break;
211 return Error("Expected ')' or ',' in argument list");
219 return new CallExprAST(IdName, Args);
222 /// numberexpr ::= number
223 static ExprAST *ParseNumberExpr() {
224 ExprAST *Result = new NumberExprAST(NumVal);
225 getNextToken(); // consume the number
229 /// parenexpr ::= '(' expression ')'
230 static ExprAST *ParseParenExpr() {
231 getNextToken(); // eat (.
232 ExprAST *V = ParseExpression();
236 return Error("expected ')'");
237 getNextToken(); // eat ).
242 /// ::= identifierexpr
245 static ExprAST *ParsePrimary() {
247 default: return Error("unknown token when expecting an expression");
248 case tok_identifier: return ParseIdentifierExpr();
249 case tok_number: return ParseNumberExpr();
250 case '(': return ParseParenExpr();
255 /// ::= ('+' primary)*
256 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
257 // If this is a binop, find its precedence.
259 int TokPrec = GetTokPrecedence();
261 // If this is a binop that binds at least as tightly as the current binop,
262 // consume it, otherwise we are done.
263 if (TokPrec < ExprPrec)
266 // Okay, we know this is a binop.
268 getNextToken(); // eat binop
270 // Parse the primary expression after the binary operator.
271 ExprAST *RHS = ParsePrimary();
274 // If BinOp binds less tightly with RHS than the operator after RHS, let
275 // the pending operator take RHS as its LHS.
276 int NextPrec = GetTokPrecedence();
277 if (TokPrec < NextPrec) {
278 RHS = ParseBinOpRHS(TokPrec+1, RHS);
279 if (RHS == 0) return 0;
283 LHS = new BinaryExprAST(BinOp, LHS, RHS);
288 /// ::= primary binoprhs
290 static ExprAST *ParseExpression() {
291 ExprAST *LHS = ParsePrimary();
294 return ParseBinOpRHS(0, LHS);
298 /// ::= id '(' id* ')'
299 static PrototypeAST *ParsePrototype() {
300 if (CurTok != tok_identifier)
301 return ErrorP("Expected function name in prototype");
303 std::string FnName = IdentifierStr;
307 return ErrorP("Expected '(' in prototype");
309 std::vector<std::string> ArgNames;
310 while (getNextToken() == tok_identifier)
311 ArgNames.push_back(IdentifierStr);
313 return ErrorP("Expected ')' in prototype");
316 getNextToken(); // eat ')'.
318 return new PrototypeAST(FnName, ArgNames);
321 /// definition ::= 'def' prototype expression
322 static FunctionAST *ParseDefinition() {
323 getNextToken(); // eat def.
324 PrototypeAST *Proto = ParsePrototype();
325 if (Proto == 0) return 0;
327 if (ExprAST *E = ParseExpression())
328 return new FunctionAST(Proto, E);
332 /// toplevelexpr ::= expression
333 static FunctionAST *ParseTopLevelExpr() {
334 if (ExprAST *E = ParseExpression()) {
335 // Make an anonymous proto.
336 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
337 return new FunctionAST(Proto, E);
342 /// external ::= 'extern' prototype
343 static PrototypeAST *ParseExtern() {
344 getNextToken(); // eat extern.
345 return ParsePrototype();
348 //===----------------------------------------------------------------------===//
350 //===----------------------------------------------------------------------===//
352 static Module *TheModule;
353 static IRBuilder<> Builder(getGlobalContext());
354 static std::map<std::string, Value*> NamedValues;
356 Value *ErrorV(const char *Str) { Error(Str); return 0; }
358 Value *NumberExprAST::Codegen() {
359 return ConstantFP::get(getGlobalContext(), APFloat(Val));
362 Value *VariableExprAST::Codegen() {
363 // Look this variable up in the function.
364 Value *V = NamedValues[Name];
365 return V ? V : ErrorV("Unknown variable name");
368 Value *BinaryExprAST::Codegen() {
369 Value *L = LHS->Codegen();
370 Value *R = RHS->Codegen();
371 if (L == 0 || R == 0) return 0;
374 case '+': return Builder.CreateFAdd(L, R, "addtmp");
375 case '-': return Builder.CreateFSub(L, R, "subtmp");
376 case '*': return Builder.CreateFMul(L, R, "multmp");
378 L = Builder.CreateFCmpULT(L, R, "cmptmp");
379 // Convert bool 0/1 to double 0.0 or 1.0
380 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
382 default: return ErrorV("invalid binary operator");
386 Value *CallExprAST::Codegen() {
387 // Look up the name in the global module table.
388 Function *CalleeF = TheModule->getFunction(Callee);
390 return ErrorV("Unknown function referenced");
392 // If argument mismatch error.
393 if (CalleeF->arg_size() != Args.size())
394 return ErrorV("Incorrect # arguments passed");
396 std::vector<Value*> ArgsV;
397 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
398 ArgsV.push_back(Args[i]->Codegen());
399 if (ArgsV.back() == 0) return 0;
402 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
405 Function *PrototypeAST::Codegen() {
406 // Make the function type: double(double,double) etc.
407 std::vector<Type*> Doubles(Args.size(),
408 Type::getDoubleTy(getGlobalContext()));
409 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
412 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
414 // If F conflicted, there was already something named 'Name'. If it has a
415 // body, don't allow redefinition or reextern.
416 if (F->getName() != Name) {
417 // Delete the one we just made and get the existing one.
418 F->eraseFromParent();
419 F = TheModule->getFunction(Name);
421 // If F already has a body, reject this.
423 ErrorF("redefinition of function");
427 // If F took a different number of args, reject.
428 if (F->arg_size() != Args.size()) {
429 ErrorF("redefinition of function with different # args");
434 // Set names for all arguments.
436 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
438 AI->setName(Args[Idx]);
440 // Add arguments to variable symbol table.
441 NamedValues[Args[Idx]] = AI;
447 Function *FunctionAST::Codegen() {
450 Function *TheFunction = Proto->Codegen();
451 if (TheFunction == 0)
454 // Create a new basic block to start insertion into.
455 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
456 Builder.SetInsertPoint(BB);
458 if (Value *RetVal = Body->Codegen()) {
459 // Finish off the function.
460 Builder.CreateRet(RetVal);
462 // Validate the generated code, checking for consistency.
463 verifyFunction(*TheFunction);
468 // Error reading body, remove function.
469 TheFunction->eraseFromParent();
473 //===----------------------------------------------------------------------===//
474 // Top-Level parsing and JIT Driver
475 //===----------------------------------------------------------------------===//
477 static void HandleDefinition() {
478 if (FunctionAST *F = ParseDefinition()) {
479 if (Function *LF = F->Codegen()) {
480 fprintf(stderr, "Read function definition:");
484 // Skip token for error recovery.
489 static void HandleExtern() {
490 if (PrototypeAST *P = ParseExtern()) {
491 if (Function *F = P->Codegen()) {
492 fprintf(stderr, "Read extern: ");
496 // Skip token for error recovery.
501 static void HandleTopLevelExpression() {
502 // Evaluate a top-level expression into an anonymous function.
503 if (FunctionAST *F = ParseTopLevelExpr()) {
504 if (Function *LF = F->Codegen()) {
505 fprintf(stderr, "Read top-level expression:");
509 // Skip token for error recovery.
514 /// top ::= definition | external | expression | ';'
515 static void MainLoop() {
517 fprintf(stderr, "ready> ");
519 case tok_eof: return;
520 case ';': getNextToken(); break; // ignore top-level semicolons.
521 case tok_def: HandleDefinition(); break;
522 case tok_extern: HandleExtern(); break;
523 default: HandleTopLevelExpression(); break;
528 //===----------------------------------------------------------------------===//
529 // "Library" functions that can be "extern'd" from user code.
530 //===----------------------------------------------------------------------===//
532 /// putchard - putchar that takes a double and returns 0.
534 double putchard(double X) {
539 //===----------------------------------------------------------------------===//
541 //===----------------------------------------------------------------------===//
544 LLVMContext &Context = getGlobalContext();
546 // Install standard binary operators.
547 // 1 is lowest precedence.
548 BinopPrecedence['<'] = 10;
549 BinopPrecedence['+'] = 20;
550 BinopPrecedence['-'] = 20;
551 BinopPrecedence['*'] = 40; // highest.
553 // Prime the first token.
554 fprintf(stderr, "ready> ");
557 // Make the module, which holds all the code.
558 TheModule = new Module("my cool jit", Context);
560 // Run the main "interpreter loop" now.
563 // Print out all of the generated code.