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 /// NumberExprAST - Expression class for numeric literals like "1.0".
92 class NumberExprAST : public ExprAST {
95 NumberExprAST(double val) : Val(val) {}
96 virtual Value *Codegen();
99 /// VariableExprAST - Expression class for referencing a variable, like "a".
100 class VariableExprAST : public ExprAST {
103 VariableExprAST(const std::string &name) : Name(name) {}
104 virtual Value *Codegen();
107 /// BinaryExprAST - Expression class for a binary operator.
108 class BinaryExprAST : public ExprAST {
112 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
113 : Op(op), LHS(lhs), RHS(rhs) {}
114 virtual Value *Codegen();
117 /// CallExprAST - Expression class for function calls.
118 class CallExprAST : public ExprAST {
120 std::vector<ExprAST*> Args;
122 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
123 : Callee(callee), Args(args) {}
124 virtual Value *Codegen();
127 /// PrototypeAST - This class represents the "prototype" for a function,
128 /// which captures its name, and its argument names (thus implicitly the number
129 /// of arguments the function takes).
132 std::vector<std::string> Args;
134 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
135 : Name(name), Args(args) {}
140 /// FunctionAST - This class represents a function definition itself.
145 FunctionAST(PrototypeAST *proto, ExprAST *body)
146 : Proto(proto), Body(body) {}
151 //===----------------------------------------------------------------------===//
153 //===----------------------------------------------------------------------===//
155 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
156 /// token the parser is looking at. getNextToken reads another token from the
157 /// lexer and updates CurTok with its results.
159 static int getNextToken() {
160 return CurTok = gettok();
163 /// BinopPrecedence - This holds the precedence for each binary operator that is
165 static std::map<char, int> BinopPrecedence;
167 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
168 static int GetTokPrecedence() {
169 if (!isascii(CurTok))
172 // Make sure it's a declared binop.
173 int TokPrec = BinopPrecedence[CurTok];
174 if (TokPrec <= 0) return -1;
178 /// Error* - These are little helper functions for error handling.
179 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
180 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
181 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
183 static ExprAST *ParseExpression();
187 /// ::= identifier '(' expression* ')'
188 static ExprAST *ParseIdentifierExpr() {
189 std::string IdName = IdentifierStr;
191 getNextToken(); // eat identifier.
193 if (CurTok != '(') // Simple variable ref.
194 return new VariableExprAST(IdName);
197 getNextToken(); // eat (
198 std::vector<ExprAST*> Args;
201 ExprAST *Arg = ParseExpression();
205 if (CurTok == ')') break;
208 return Error("Expected ')' or ',' in argument list");
216 return new CallExprAST(IdName, Args);
219 /// numberexpr ::= number
220 static ExprAST *ParseNumberExpr() {
221 ExprAST *Result = new NumberExprAST(NumVal);
222 getNextToken(); // consume the number
226 /// parenexpr ::= '(' expression ')'
227 static ExprAST *ParseParenExpr() {
228 getNextToken(); // eat (.
229 ExprAST *V = ParseExpression();
233 return Error("expected ')'");
234 getNextToken(); // eat ).
239 /// ::= identifierexpr
242 static ExprAST *ParsePrimary() {
244 default: return Error("unknown token when expecting an expression");
245 case tok_identifier: return ParseIdentifierExpr();
246 case tok_number: return ParseNumberExpr();
247 case '(': return ParseParenExpr();
252 /// ::= ('+' primary)*
253 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
254 // If this is a binop, find its precedence.
256 int TokPrec = GetTokPrecedence();
258 // If this is a binop that binds at least as tightly as the current binop,
259 // consume it, otherwise we are done.
260 if (TokPrec < ExprPrec)
263 // Okay, we know this is a binop.
265 getNextToken(); // eat binop
267 // Parse the primary expression after the binary operator.
268 ExprAST *RHS = ParsePrimary();
271 // If BinOp binds less tightly with RHS than the operator after RHS, let
272 // the pending operator take RHS as its LHS.
273 int NextPrec = GetTokPrecedence();
274 if (TokPrec < NextPrec) {
275 RHS = ParseBinOpRHS(TokPrec+1, RHS);
276 if (RHS == 0) return 0;
280 LHS = new BinaryExprAST(BinOp, LHS, RHS);
285 /// ::= primary binoprhs
287 static ExprAST *ParseExpression() {
288 ExprAST *LHS = ParsePrimary();
291 return ParseBinOpRHS(0, LHS);
295 /// ::= id '(' id* ')'
296 static PrototypeAST *ParsePrototype() {
297 if (CurTok != tok_identifier)
298 return ErrorP("Expected function name in prototype");
300 std::string FnName = IdentifierStr;
304 return ErrorP("Expected '(' in prototype");
306 std::vector<std::string> ArgNames;
307 while (getNextToken() == tok_identifier)
308 ArgNames.push_back(IdentifierStr);
310 return ErrorP("Expected ')' in prototype");
313 getNextToken(); // eat ')'.
315 return new PrototypeAST(FnName, ArgNames);
318 /// definition ::= 'def' prototype expression
319 static FunctionAST *ParseDefinition() {
320 getNextToken(); // eat def.
321 PrototypeAST *Proto = ParsePrototype();
322 if (Proto == 0) return 0;
324 if (ExprAST *E = ParseExpression())
325 return new FunctionAST(Proto, E);
329 /// toplevelexpr ::= expression
330 static FunctionAST *ParseTopLevelExpr() {
331 if (ExprAST *E = ParseExpression()) {
332 // Make an anonymous proto.
333 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
334 return new FunctionAST(Proto, E);
339 /// external ::= 'extern' prototype
340 static PrototypeAST *ParseExtern() {
341 getNextToken(); // eat extern.
342 return ParsePrototype();
345 //===----------------------------------------------------------------------===//
347 //===----------------------------------------------------------------------===//
349 static Module *TheModule;
350 static IRBuilder<> Builder(getGlobalContext());
351 static std::map<std::string, Value*> NamedValues;
353 Value *ErrorV(const char *Str) { Error(Str); return 0; }
355 Value *NumberExprAST::Codegen() {
356 return ConstantFP::get(getGlobalContext(), APFloat(Val));
359 Value *VariableExprAST::Codegen() {
360 // Look this variable up in the function.
361 Value *V = NamedValues[Name];
362 return V ? V : ErrorV("Unknown variable name");
365 Value *BinaryExprAST::Codegen() {
366 Value *L = LHS->Codegen();
367 Value *R = RHS->Codegen();
368 if (L == 0 || R == 0) return 0;
371 case '+': return Builder.CreateFAdd(L, R, "addtmp");
372 case '-': return Builder.CreateFSub(L, R, "subtmp");
373 case '*': return Builder.CreateFMul(L, R, "multmp");
375 L = Builder.CreateFCmpULT(L, R, "cmptmp");
376 // Convert bool 0/1 to double 0.0 or 1.0
377 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
379 default: return ErrorV("invalid binary operator");
383 Value *CallExprAST::Codegen() {
384 // Look up the name in the global module table.
385 Function *CalleeF = TheModule->getFunction(Callee);
387 return ErrorV("Unknown function referenced");
389 // If argument mismatch error.
390 if (CalleeF->arg_size() != Args.size())
391 return ErrorV("Incorrect # arguments passed");
393 std::vector<Value*> ArgsV;
394 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
395 ArgsV.push_back(Args[i]->Codegen());
396 if (ArgsV.back() == 0) return 0;
399 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
402 Function *PrototypeAST::Codegen() {
403 // Make the function type: double(double,double) etc.
404 std::vector<Type*> Doubles(Args.size(),
405 Type::getDoubleTy(getGlobalContext()));
406 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
409 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
411 // If F conflicted, there was already something named 'Name'. If it has a
412 // body, don't allow redefinition or reextern.
413 if (F->getName() != Name) {
414 // Delete the one we just made and get the existing one.
415 F->eraseFromParent();
416 F = TheModule->getFunction(Name);
418 // If F already has a body, reject this.
420 ErrorF("redefinition of function");
424 // If F took a different number of args, reject.
425 if (F->arg_size() != Args.size()) {
426 ErrorF("redefinition of function with different # args");
431 // Set names for all arguments.
433 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
435 AI->setName(Args[Idx]);
437 // Add arguments to variable symbol table.
438 NamedValues[Args[Idx]] = AI;
444 Function *FunctionAST::Codegen() {
447 Function *TheFunction = Proto->Codegen();
448 if (TheFunction == 0)
451 // Create a new basic block to start insertion into.
452 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
453 Builder.SetInsertPoint(BB);
455 if (Value *RetVal = Body->Codegen()) {
456 // Finish off the function.
457 Builder.CreateRet(RetVal);
459 // Validate the generated code, checking for consistency.
460 verifyFunction(*TheFunction);
465 // Error reading body, remove function.
466 TheFunction->eraseFromParent();
470 //===----------------------------------------------------------------------===//
471 // Top-Level parsing and JIT Driver
472 //===----------------------------------------------------------------------===//
474 static void HandleDefinition() {
475 if (FunctionAST *F = ParseDefinition()) {
476 if (Function *LF = F->Codegen()) {
477 fprintf(stderr, "Read function definition:");
481 // Skip token for error recovery.
486 static void HandleExtern() {
487 if (PrototypeAST *P = ParseExtern()) {
488 if (Function *F = P->Codegen()) {
489 fprintf(stderr, "Read extern: ");
493 // Skip token for error recovery.
498 static void HandleTopLevelExpression() {
499 // Evaluate a top-level expression into an anonymous function.
500 if (FunctionAST *F = ParseTopLevelExpr()) {
501 if (Function *LF = F->Codegen()) {
502 fprintf(stderr, "Read top-level expression:");
506 // Skip token for error recovery.
511 /// top ::= definition | external | expression | ';'
512 static void MainLoop() {
514 fprintf(stderr, "ready> ");
516 case tok_eof: return;
517 case ';': getNextToken(); break; // ignore top-level semicolons.
518 case tok_def: HandleDefinition(); break;
519 case tok_extern: HandleExtern(); break;
520 default: HandleTopLevelExpression(); break;
525 //===----------------------------------------------------------------------===//
526 // "Library" functions that can be "extern'd" from user code.
527 //===----------------------------------------------------------------------===//
529 /// putchard - putchar that takes a double and returns 0.
531 double putchard(double X) {
536 //===----------------------------------------------------------------------===//
538 //===----------------------------------------------------------------------===//
541 LLVMContext &Context = getGlobalContext();
543 // Install standard binary operators.
544 // 1 is lowest precedence.
545 BinopPrecedence['<'] = 10;
546 BinopPrecedence['+'] = 20;
547 BinopPrecedence['-'] = 20;
548 BinopPrecedence['*'] = 40; // highest.
550 // Prime the first token.
551 fprintf(stderr, "ready> ");
554 // Make the module, which holds all the code.
555 TheModule = new Module("my cool jit", Context);
557 // Run the main "interpreter loop" now.
560 // Print out all of the generated code.