1#include "llvm/Analysis/Passes.h" 2#include "llvm/ExecutionEngine/ExecutionEngine.h" 3#include "llvm/ExecutionEngine/JIT.h" 4#include "llvm/IR/DataLayout.h" 5#include "llvm/IR/DerivedTypes.h" 6#include "llvm/IR/IRBuilder.h" 7#include "llvm/IR/LLVMContext.h" 8#include "llvm/IR/Module.h" 9#include "llvm/IR/Verifier.h" 10#include "llvm/PassManager.h" 11#include "llvm/Support/TargetSelect.h" 12#include "llvm/Transforms/Scalar.h" 13#include <cctype> 14#include <cstdio> 15#include <map> 16#include <string> 17#include <vector> 18using namespace llvm; 19 20//===----------------------------------------------------------------------===// 21// Lexer 22//===----------------------------------------------------------------------===// 23 24// The lexer returns tokens [0-255] if it is an unknown character, otherwise one 25// of these for known things. 26enum Token { 27 tok_eof = -1, 28 29 // commands 30 tok_def = -2, tok_extern = -3, 31 32 // primary 33 tok_identifier = -4, tok_number = -5, 34 35 // control 36 tok_if = -6, tok_then = -7, tok_else = -8, 37 tok_for = -9, tok_in = -10, 38 39 // operators 40 tok_binary = -11, tok_unary = -12, 41 42 // var definition 43 tok_var = -13 44}; 45 46static std::string IdentifierStr; // Filled in if tok_identifier 47static double NumVal; // Filled in if tok_number 48 49/// gettok - Return the next token from standard input. 50static int gettok() { 51 static int LastChar = ' '; 52 53 // Skip any whitespace. 54 while (isspace(LastChar)) 55 LastChar = getchar(); 56 57 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]* 58 IdentifierStr = LastChar; 59 while (isalnum((LastChar = getchar()))) 60 IdentifierStr += LastChar; 61 62 if (IdentifierStr == "def") return tok_def; 63 if (IdentifierStr == "extern") return tok_extern; 64 if (IdentifierStr == "if") return tok_if; 65 if (IdentifierStr == "then") return tok_then; 66 if (IdentifierStr == "else") return tok_else; 67 if (IdentifierStr == "for") return tok_for; 68 if (IdentifierStr == "in") return tok_in; 69 if (IdentifierStr == "binary") return tok_binary; 70 if (IdentifierStr == "unary") return tok_unary; 71 if (IdentifierStr == "var") return tok_var; 72 return tok_identifier; 73 } 74 75 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+ 76 std::string NumStr; 77 do { 78 NumStr += LastChar; 79 LastChar = getchar(); 80 } while (isdigit(LastChar) || LastChar == '.'); 81 82 NumVal = strtod(NumStr.c_str(), 0); 83 return tok_number; 84 } 85 86 if (LastChar == '#') { 87 // Comment until end of line. 88 do LastChar = getchar(); 89 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r'); 90 91 if (LastChar != EOF) 92 return gettok(); 93 } 94 95 // Check for end of file. Don't eat the EOF. 96 if (LastChar == EOF) 97 return tok_eof; 98 99 // Otherwise, just return the character as its ascii value. 100 int ThisChar = LastChar; 101 LastChar = getchar(); 102 return ThisChar; 103} 104 105//===----------------------------------------------------------------------===// 106// Abstract Syntax Tree (aka Parse Tree) 107//===----------------------------------------------------------------------===// 108namespace { 109/// ExprAST - Base class for all expression nodes. 110class ExprAST { 111public: 112 virtual ~ExprAST() {} 113 virtual Value *Codegen() = 0; 114}; 115 116/// NumberExprAST - Expression class for numeric literals like "1.0". 117class NumberExprAST : public ExprAST { 118 double Val; 119public: 120 NumberExprAST(double val) : Val(val) {} 121 virtual Value *Codegen(); 122}; 123 124/// VariableExprAST - Expression class for referencing a variable, like "a". 125class VariableExprAST : public ExprAST { 126 std::string Name; 127public: 128 VariableExprAST(const std::string &name) : Name(name) {} 129 const std::string &getName() const { return Name; } 130 virtual Value *Codegen(); 131}; 132 133/// UnaryExprAST - Expression class for a unary operator. 134class UnaryExprAST : public ExprAST { 135 char Opcode; 136 ExprAST *Operand; 137public: 138 UnaryExprAST(char opcode, ExprAST *operand) 139 : Opcode(opcode), Operand(operand) {} 140 virtual Value *Codegen(); 141}; 142 143/// BinaryExprAST - Expression class for a binary operator. 144class BinaryExprAST : public ExprAST { 145 char Op; 146 ExprAST *LHS, *RHS; 147public: 148 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs) 149 : Op(op), LHS(lhs), RHS(rhs) {} 150 virtual Value *Codegen(); 151}; 152 153/// CallExprAST - Expression class for function calls. 154class CallExprAST : public ExprAST { 155 std::string Callee; 156 std::vector<ExprAST*> Args; 157public: 158 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args) 159 : Callee(callee), Args(args) {} 160 virtual Value *Codegen(); 161}; 162 163/// IfExprAST - Expression class for if/then/else. 164class IfExprAST : public ExprAST { 165 ExprAST *Cond, *Then, *Else; 166public: 167 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else) 168 : Cond(cond), Then(then), Else(_else) {} 169 virtual Value *Codegen(); 170}; 171 172/// ForExprAST - Expression class for for/in. 173class ForExprAST : public ExprAST { 174 std::string VarName; 175 ExprAST *Start, *End, *Step, *Body; 176public: 177 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end, 178 ExprAST *step, ExprAST *body) 179 : VarName(varname), Start(start), End(end), Step(step), Body(body) {} 180 virtual Value *Codegen(); 181}; 182 183/// VarExprAST - Expression class for var/in 184class VarExprAST : public ExprAST { 185 std::vector<std::pair<std::string, ExprAST*> > VarNames; 186 ExprAST *Body; 187public: 188 VarExprAST(const std::vector<std::pair<std::string, ExprAST*> > &varnames, 189 ExprAST *body) 190 : VarNames(varnames), Body(body) {} 191 192 virtual Value *Codegen(); 193}; 194 195/// PrototypeAST - This class represents the "prototype" for a function, 196/// which captures its argument names as well as if it is an operator. 197class PrototypeAST { 198 std::string Name; 199 std::vector<std::string> Args; 200 bool isOperator; 201 unsigned Precedence; // Precedence if a binary op. 202public: 203 PrototypeAST(const std::string &name, const std::vector<std::string> &args, 204 bool isoperator = false, unsigned prec = 0) 205 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {} 206 207 bool isUnaryOp() const { return isOperator && Args.size() == 1; } 208 bool isBinaryOp() const { return isOperator && Args.size() == 2; } 209 210 char getOperatorName() const { 211 assert(isUnaryOp() || isBinaryOp()); 212 return Name[Name.size()-1]; 213 } 214 215 unsigned getBinaryPrecedence() const { return Precedence; } 216 217 Function *Codegen(); 218 219 void CreateArgumentAllocas(Function *F); 220}; 221 222/// FunctionAST - This class represents a function definition itself. 223class FunctionAST { 224 PrototypeAST *Proto; 225 ExprAST *Body; 226public: 227 FunctionAST(PrototypeAST *proto, ExprAST *body) 228 : Proto(proto), Body(body) {} 229 230 Function *Codegen(); 231}; 232} // end anonymous namespace 233 234//===----------------------------------------------------------------------===// 235// Parser 236//===----------------------------------------------------------------------===// 237 238/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current 239/// token the parser is looking at. getNextToken reads another token from the 240/// lexer and updates CurTok with its results. 241static int CurTok; 242static int getNextToken() { 243 return CurTok = gettok(); 244} 245 246/// BinopPrecedence - This holds the precedence for each binary operator that is 247/// defined. 248static std::map<char, int> BinopPrecedence; 249 250/// GetTokPrecedence - Get the precedence of the pending binary operator token. 251static int GetTokPrecedence() { 252 if (!isascii(CurTok)) 253 return -1; 254 255 // Make sure it's a declared binop. 256 int TokPrec = BinopPrecedence[CurTok]; 257 if (TokPrec <= 0) return -1; 258 return TokPrec; 259} 260 261/// Error* - These are little helper functions for error handling. 262ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;} 263PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; } 264FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; } 265 266static ExprAST *ParseExpression(); 267 268/// identifierexpr 269/// ::= identifier 270/// ::= identifier '(' expression* ')' 271static ExprAST *ParseIdentifierExpr() { 272 std::string IdName = IdentifierStr; 273 274 getNextToken(); // eat identifier. 275 276 if (CurTok != '(') // Simple variable ref. 277 return new VariableExprAST(IdName); 278 279 // Call. 280 getNextToken(); // eat ( 281 std::vector<ExprAST*> Args; 282 if (CurTok != ')') { 283 while (1) { 284 ExprAST *Arg = ParseExpression(); 285 if (!Arg) return 0; 286 Args.push_back(Arg); 287 288 if (CurTok == ')') break; 289 290 if (CurTok != ',') 291 return Error("Expected ')' or ',' in argument list"); 292 getNextToken(); 293 } 294 } 295 296 // Eat the ')'. 297 getNextToken(); 298 299 return new CallExprAST(IdName, Args); 300} 301 302/// numberexpr ::= number 303static ExprAST *ParseNumberExpr() { 304 ExprAST *Result = new NumberExprAST(NumVal); 305 getNextToken(); // consume the number 306 return Result; 307} 308 309/// parenexpr ::= '(' expression ')' 310static ExprAST *ParseParenExpr() { 311 getNextToken(); // eat (. 312 ExprAST *V = ParseExpression(); 313 if (!V) return 0; 314 315 if (CurTok != ')') 316 return Error("expected ')'"); 317 getNextToken(); // eat ). 318 return V; 319} 320 321/// ifexpr ::= 'if' expression 'then' expression 'else' expression 322static ExprAST *ParseIfExpr() { 323 getNextToken(); // eat the if. 324 325 // condition. 326 ExprAST *Cond = ParseExpression(); 327 if (!Cond) return 0; 328 329 if (CurTok != tok_then) 330 return Error("expected then"); 331 getNextToken(); // eat the then 332 333 ExprAST *Then = ParseExpression(); 334 if (Then == 0) return 0; 335 336 if (CurTok != tok_else) 337 return Error("expected else"); 338 339 getNextToken(); 340 341 ExprAST *Else = ParseExpression(); 342 if (!Else) return 0; 343 344 return new IfExprAST(Cond, Then, Else); 345} 346 347/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression 348static ExprAST *ParseForExpr() { 349 getNextToken(); // eat the for. 350 351 if (CurTok != tok_identifier) 352 return Error("expected identifier after for"); 353 354 std::string IdName = IdentifierStr; 355 getNextToken(); // eat identifier. 356 357 if (CurTok != '=') 358 return Error("expected '=' after for"); 359 getNextToken(); // eat '='. 360 361 362 ExprAST *Start = ParseExpression(); 363 if (Start == 0) return 0; 364 if (CurTok != ',') 365 return Error("expected ',' after for start value"); 366 getNextToken(); 367 368 ExprAST *End = ParseExpression(); 369 if (End == 0) return 0; 370 371 // The step value is optional. 372 ExprAST *Step = 0; 373 if (CurTok == ',') { 374 getNextToken(); 375 Step = ParseExpression(); 376 if (Step == 0) return 0; 377 } 378 379 if (CurTok != tok_in) 380 return Error("expected 'in' after for"); 381 getNextToken(); // eat 'in'. 382 383 ExprAST *Body = ParseExpression(); 384 if (Body == 0) return 0; 385 386 return new ForExprAST(IdName, Start, End, Step, Body); 387} 388 389/// varexpr ::= 'var' identifier ('=' expression)? 390// (',' identifier ('=' expression)?)* 'in' expression 391static ExprAST *ParseVarExpr() { 392 getNextToken(); // eat the var. 393 394 std::vector<std::pair<std::string, ExprAST*> > VarNames; 395 396 // At least one variable name is required. 397 if (CurTok != tok_identifier) 398 return Error("expected identifier after var"); 399 400 while (1) { 401 std::string Name = IdentifierStr; 402 getNextToken(); // eat identifier. 403 404 // Read the optional initializer. 405 ExprAST *Init = 0; 406 if (CurTok == '=') { 407 getNextToken(); // eat the '='. 408 409 Init = ParseExpression(); 410 if (Init == 0) return 0; 411 } 412 413 VarNames.push_back(std::make_pair(Name, Init)); 414 415 // End of var list, exit loop. 416 if (CurTok != ',') break; 417 getNextToken(); // eat the ','. 418 419 if (CurTok != tok_identifier) 420 return Error("expected identifier list after var"); 421 } 422 423 // At this point, we have to have 'in'. 424 if (CurTok != tok_in) 425 return Error("expected 'in' keyword after 'var'"); 426 getNextToken(); // eat 'in'. 427 428 ExprAST *Body = ParseExpression(); 429 if (Body == 0) return 0; 430 431 return new VarExprAST(VarNames, Body); 432} 433 434/// primary 435/// ::= identifierexpr 436/// ::= numberexpr 437/// ::= parenexpr 438/// ::= ifexpr 439/// ::= forexpr 440/// ::= varexpr 441static ExprAST *ParsePrimary() { 442 switch (CurTok) { 443 default: return Error("unknown token when expecting an expression"); 444 case tok_identifier: return ParseIdentifierExpr(); 445 case tok_number: return ParseNumberExpr(); 446 case '(': return ParseParenExpr(); 447 case tok_if: return ParseIfExpr(); 448 case tok_for: return ParseForExpr(); 449 case tok_var: return ParseVarExpr(); 450 } 451} 452 453/// unary 454/// ::= primary 455/// ::= '!' unary 456static ExprAST *ParseUnary() { 457 // If the current token is not an operator, it must be a primary expr. 458 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',') 459 return ParsePrimary(); 460 461 // If this is a unary operator, read it. 462 int Opc = CurTok; 463 getNextToken(); 464 if (ExprAST *Operand = ParseUnary()) 465 return new UnaryExprAST(Opc, Operand); 466 return 0; 467} 468 469/// binoprhs 470/// ::= ('+' unary)* 471static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) { 472 // If this is a binop, find its precedence. 473 while (1) { 474 int TokPrec = GetTokPrecedence(); 475 476 // If this is a binop that binds at least as tightly as the current binop, 477 // consume it, otherwise we are done. 478 if (TokPrec < ExprPrec) 479 return LHS; 480 481 // Okay, we know this is a binop. 482 int BinOp = CurTok; 483 getNextToken(); // eat binop 484 485 // Parse the unary expression after the binary operator. 486 ExprAST *RHS = ParseUnary(); 487 if (!RHS) return 0; 488 489 // If BinOp binds less tightly with RHS than the operator after RHS, let 490 // the pending operator take RHS as its LHS. 491 int NextPrec = GetTokPrecedence(); 492 if (TokPrec < NextPrec) { 493 RHS = ParseBinOpRHS(TokPrec+1, RHS); 494 if (RHS == 0) return 0; 495 } 496 497 // Merge LHS/RHS. 498 LHS = new BinaryExprAST(BinOp, LHS, RHS); 499 } 500} 501 502/// expression 503/// ::= unary binoprhs 504/// 505static ExprAST *ParseExpression() { 506 ExprAST *LHS = ParseUnary(); 507 if (!LHS) return 0; 508 509 return ParseBinOpRHS(0, LHS); 510} 511 512/// prototype 513/// ::= id '(' id* ')' 514/// ::= binary LETTER number? (id, id) 515/// ::= unary LETTER (id) 516static PrototypeAST *ParsePrototype() { 517 std::string FnName; 518 519 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary. 520 unsigned BinaryPrecedence = 30; 521 522 switch (CurTok) { 523 default: 524 return ErrorP("Expected function name in prototype"); 525 case tok_identifier: 526 FnName = IdentifierStr; 527 Kind = 0; 528 getNextToken(); 529 break; 530 case tok_unary: 531 getNextToken(); 532 if (!isascii(CurTok)) 533 return ErrorP("Expected unary operator"); 534 FnName = "unary"; 535 FnName += (char)CurTok; 536 Kind = 1; 537 getNextToken(); 538 break; 539 case tok_binary: 540 getNextToken(); 541 if (!isascii(CurTok)) 542 return ErrorP("Expected binary operator"); 543 FnName = "binary"; 544 FnName += (char)CurTok; 545 Kind = 2; 546 getNextToken(); 547 548 // Read the precedence if present. 549 if (CurTok == tok_number) { 550 if (NumVal < 1 || NumVal > 100) 551 return ErrorP("Invalid precedecnce: must be 1..100"); 552 BinaryPrecedence = (unsigned)NumVal; 553 getNextToken(); 554 } 555 break; 556 } 557 558 if (CurTok != '(') 559 return ErrorP("Expected '(' in prototype"); 560 561 std::vector<std::string> ArgNames; 562 while (getNextToken() == tok_identifier) 563 ArgNames.push_back(IdentifierStr); 564 if (CurTok != ')') 565 return ErrorP("Expected ')' in prototype"); 566 567 // success. 568 getNextToken(); // eat ')'. 569 570 // Verify right number of names for operator. 571 if (Kind && ArgNames.size() != Kind) 572 return ErrorP("Invalid number of operands for operator"); 573 574 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence); 575} 576 577/// definition ::= 'def' prototype expression 578static FunctionAST *ParseDefinition() { 579 getNextToken(); // eat def. 580 PrototypeAST *Proto = ParsePrototype(); 581 if (Proto == 0) return 0; 582 583 if (ExprAST *E = ParseExpression()) 584 return new FunctionAST(Proto, E); 585 return 0; 586} 587 588/// toplevelexpr ::= expression 589static FunctionAST *ParseTopLevelExpr() { 590 if (ExprAST *E = ParseExpression()) { 591 // Make an anonymous proto. 592 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>()); 593 return new FunctionAST(Proto, E); 594 } 595 return 0; 596} 597 598/// external ::= 'extern' prototype 599static PrototypeAST *ParseExtern() { 600 getNextToken(); // eat extern. 601 return ParsePrototype(); 602} 603 604//===----------------------------------------------------------------------===// 605// Code Generation 606//===----------------------------------------------------------------------===// 607 608static Module *TheModule; 609static IRBuilder<> Builder(getGlobalContext()); 610static std::map<std::string, AllocaInst*> NamedValues; 611static FunctionPassManager *TheFPM; 612 613Value *ErrorV(const char *Str) { Error(Str); return 0; } 614 615/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of 616/// the function. This is used for mutable variables etc. 617static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction, 618 const std::string &VarName) { 619 IRBuilder<> TmpB(&TheFunction->getEntryBlock(), 620 TheFunction->getEntryBlock().begin()); 621 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0, 622 VarName.c_str()); 623} 624 625Value *NumberExprAST::Codegen() { 626 return ConstantFP::get(getGlobalContext(), APFloat(Val)); 627} 628 629Value *VariableExprAST::Codegen() { 630 // Look this variable up in the function. 631 Value *V = NamedValues[Name]; 632 if (V == 0) return ErrorV("Unknown variable name"); 633 634 // Load the value. 635 return Builder.CreateLoad(V, Name.c_str()); 636} 637 638Value *UnaryExprAST::Codegen() { 639 Value *OperandV = Operand->Codegen(); 640 if (OperandV == 0) return 0; 641 642 Function *F = TheModule->getFunction(std::string("unary")+Opcode); 643 if (F == 0) 644 return ErrorV("Unknown unary operator"); 645 646 return Builder.CreateCall(F, OperandV, "unop"); 647} 648 649Value *BinaryExprAST::Codegen() { 650 // Special case '=' because we don't want to emit the LHS as an expression. 651 if (Op == '=') { 652 // Assignment requires the LHS to be an identifier. 653 VariableExprAST *LHSE = dynamic_cast<VariableExprAST*>(LHS); 654 if (!LHSE) 655 return ErrorV("destination of '=' must be a variable"); 656 // Codegen the RHS. 657 Value *Val = RHS->Codegen(); 658 if (Val == 0) return 0; 659 660 // Look up the name. 661 Value *Variable = NamedValues[LHSE->getName()]; 662 if (Variable == 0) return ErrorV("Unknown variable name"); 663 664 Builder.CreateStore(Val, Variable); 665 return Val; 666 } 667 668 Value *L = LHS->Codegen(); 669 Value *R = RHS->Codegen(); 670 if (L == 0 || R == 0) return 0; 671 672 switch (Op) { 673 case '+': return Builder.CreateFAdd(L, R, "addtmp"); 674 case '-': return Builder.CreateFSub(L, R, "subtmp"); 675 case '*': return Builder.CreateFMul(L, R, "multmp"); 676 case '<': 677 L = Builder.CreateFCmpULT(L, R, "cmptmp"); 678 // Convert bool 0/1 to double 0.0 or 1.0 679 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()), 680 "booltmp"); 681 default: break; 682 } 683 684 // If it wasn't a builtin binary operator, it must be a user defined one. Emit 685 // a call to it. 686 Function *F = TheModule->getFunction(std::string("binary")+Op); 687 assert(F && "binary operator not found!"); 688 689 Value *Ops[] = { L, R }; 690 return Builder.CreateCall(F, Ops, "binop"); 691} 692 693Value *CallExprAST::Codegen() { 694 // Look up the name in the global module table. 695 Function *CalleeF = TheModule->getFunction(Callee); 696 if (CalleeF == 0) 697 return ErrorV("Unknown function referenced"); 698 699 // If argument mismatch error. 700 if (CalleeF->arg_size() != Args.size()) 701 return ErrorV("Incorrect # arguments passed"); 702 703 std::vector<Value*> ArgsV; 704 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 705 ArgsV.push_back(Args[i]->Codegen()); 706 if (ArgsV.back() == 0) return 0; 707 } 708 709 return Builder.CreateCall(CalleeF, ArgsV, "calltmp"); 710} 711 712Value *IfExprAST::Codegen() { 713 Value *CondV = Cond->Codegen(); 714 if (CondV == 0) return 0; 715 716 // Convert condition to a bool by comparing equal to 0.0. 717 CondV = Builder.CreateFCmpONE(CondV, 718 ConstantFP::get(getGlobalContext(), APFloat(0.0)), 719 "ifcond"); 720 721 Function *TheFunction = Builder.GetInsertBlock()->getParent(); 722 723 // Create blocks for the then and else cases. Insert the 'then' block at the 724 // end of the function. 725 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction); 726 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else"); 727 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont"); 728 729 Builder.CreateCondBr(CondV, ThenBB, ElseBB); 730 731 // Emit then value. 732 Builder.SetInsertPoint(ThenBB); 733 734 Value *ThenV = Then->Codegen(); 735 if (ThenV == 0) return 0; 736 737 Builder.CreateBr(MergeBB); 738 // Codegen of 'Then' can change the current block, update ThenBB for the PHI. 739 ThenBB = Builder.GetInsertBlock(); 740 741 // Emit else block. 742 TheFunction->getBasicBlockList().push_back(ElseBB); 743 Builder.SetInsertPoint(ElseBB); 744 745 Value *ElseV = Else->Codegen(); 746 if (ElseV == 0) return 0; 747 748 Builder.CreateBr(MergeBB); 749 // Codegen of 'Else' can change the current block, update ElseBB for the PHI. 750 ElseBB = Builder.GetInsertBlock(); 751 752 // Emit merge block. 753 TheFunction->getBasicBlockList().push_back(MergeBB); 754 Builder.SetInsertPoint(MergeBB); 755 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, 756 "iftmp"); 757 758 PN->addIncoming(ThenV, ThenBB); 759 PN->addIncoming(ElseV, ElseBB); 760 return PN; 761} 762 763Value *ForExprAST::Codegen() { 764 // Output this as: 765 // var = alloca double 766 // ... 767 // start = startexpr 768 // store start -> var 769 // goto loop 770 // loop: 771 // ... 772 // bodyexpr 773 // ... 774 // loopend: 775 // step = stepexpr 776 // endcond = endexpr 777 // 778 // curvar = load var 779 // nextvar = curvar + step 780 // store nextvar -> var 781 // br endcond, loop, endloop 782 // outloop: 783 784 Function *TheFunction = Builder.GetInsertBlock()->getParent(); 785 786 // Create an alloca for the variable in the entry block. 787 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName); 788 789 // Emit the start code first, without 'variable' in scope. 790 Value *StartVal = Start->Codegen(); 791 if (StartVal == 0) return 0; 792 793 // Store the value into the alloca. 794 Builder.CreateStore(StartVal, Alloca); 795 796 // Make the new basic block for the loop header, inserting after current 797 // block. 798 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction); 799 800 // Insert an explicit fall through from the current block to the LoopBB. 801 Builder.CreateBr(LoopBB); 802 803 // Start insertion in LoopBB. 804 Builder.SetInsertPoint(LoopBB); 805 806 // Within the loop, the variable is defined equal to the PHI node. If it 807 // shadows an existing variable, we have to restore it, so save it now. 808 AllocaInst *OldVal = NamedValues[VarName]; 809 NamedValues[VarName] = Alloca; 810 811 // Emit the body of the loop. This, like any other expr, can change the 812 // current BB. Note that we ignore the value computed by the body, but don't 813 // allow an error. 814 if (Body->Codegen() == 0) 815 return 0; 816 817 // Emit the step value. 818 Value *StepVal; 819 if (Step) { 820 StepVal = Step->Codegen(); 821 if (StepVal == 0) return 0; 822 } else { 823 // If not specified, use 1.0. 824 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0)); 825 } 826 827 // Compute the end condition. 828 Value *EndCond = End->Codegen(); 829 if (EndCond == 0) return EndCond; 830 831 // Reload, increment, and restore the alloca. This handles the case where 832 // the body of the loop mutates the variable. 833 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str()); 834 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar"); 835 Builder.CreateStore(NextVar, Alloca); 836 837 // Convert condition to a bool by comparing equal to 0.0. 838 EndCond = Builder.CreateFCmpONE(EndCond, 839 ConstantFP::get(getGlobalContext(), APFloat(0.0)), 840 "loopcond"); 841 842 // Create the "after loop" block and insert it. 843 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction); 844 845 // Insert the conditional branch into the end of LoopEndBB. 846 Builder.CreateCondBr(EndCond, LoopBB, AfterBB); 847 848 // Any new code will be inserted in AfterBB. 849 Builder.SetInsertPoint(AfterBB); 850 851 // Restore the unshadowed variable. 852 if (OldVal) 853 NamedValues[VarName] = OldVal; 854 else 855 NamedValues.erase(VarName); 856 857 858 // for expr always returns 0.0. 859 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext())); 860} 861 862Value *VarExprAST::Codegen() { 863 std::vector<AllocaInst *> OldBindings; 864 865 Function *TheFunction = Builder.GetInsertBlock()->getParent(); 866 867 // Register all variables and emit their initializer. 868 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) { 869 const std::string &VarName = VarNames[i].first; 870 ExprAST *Init = VarNames[i].second; 871 872 // Emit the initializer before adding the variable to scope, this prevents 873 // the initializer from referencing the variable itself, and permits stuff 874 // like this: 875 // var a = 1 in 876 // var a = a in ... # refers to outer 'a'. 877 Value *InitVal; 878 if (Init) { 879 InitVal = Init->Codegen(); 880 if (InitVal == 0) return 0; 881 } else { // If not specified, use 0.0. 882 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0)); 883 } 884 885 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName); 886 Builder.CreateStore(InitVal, Alloca); 887 888 // Remember the old variable binding so that we can restore the binding when 889 // we unrecurse. 890 OldBindings.push_back(NamedValues[VarName]); 891 892 // Remember this binding. 893 NamedValues[VarName] = Alloca; 894 } 895 896 // Codegen the body, now that all vars are in scope. 897 Value *BodyVal = Body->Codegen(); 898 if (BodyVal == 0) return 0; 899 900 // Pop all our variables from scope. 901 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) 902 NamedValues[VarNames[i].first] = OldBindings[i]; 903 904 // Return the body computation. 905 return BodyVal; 906} 907 908Function *PrototypeAST::Codegen() { 909 // Make the function type: double(double,double) etc. 910 std::vector<Type*> Doubles(Args.size(), 911 Type::getDoubleTy(getGlobalContext())); 912 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()), 913 Doubles, false); 914 915 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule); 916 917 // If F conflicted, there was already something named 'Name'. If it has a 918 // body, don't allow redefinition or reextern. 919 if (F->getName() != Name) { 920 // Delete the one we just made and get the existing one. 921 F->eraseFromParent(); 922 F = TheModule->getFunction(Name); 923 924 // If F already has a body, reject this. 925 if (!F->empty()) { 926 ErrorF("redefinition of function"); 927 return 0; 928 } 929 930 // If F took a different number of args, reject. 931 if (F->arg_size() != Args.size()) { 932 ErrorF("redefinition of function with different # args"); 933 return 0; 934 } 935 } 936 937 // Set names for all arguments. 938 unsigned Idx = 0; 939 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size(); 940 ++AI, ++Idx) 941 AI->setName(Args[Idx]); 942 943 return F; 944} 945 946/// CreateArgumentAllocas - Create an alloca for each argument and register the 947/// argument in the symbol table so that references to it will succeed. 948void PrototypeAST::CreateArgumentAllocas(Function *F) { 949 Function::arg_iterator AI = F->arg_begin(); 950 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) { 951 // Create an alloca for this variable. 952 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]); 953 954 // Store the initial value into the alloca. 955 Builder.CreateStore(AI, Alloca); 956 957 // Add arguments to variable symbol table. 958 NamedValues[Args[Idx]] = Alloca; 959 } 960} 961 962Function *FunctionAST::Codegen() { 963 NamedValues.clear(); 964 965 Function *TheFunction = Proto->Codegen(); 966 if (TheFunction == 0) 967 return 0; 968 969 // If this is an operator, install it. 970 if (Proto->isBinaryOp()) 971 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence(); 972 973 // Create a new basic block to start insertion into. 974 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction); 975 Builder.SetInsertPoint(BB); 976 977 // Add all arguments to the symbol table and create their allocas. 978 Proto->CreateArgumentAllocas(TheFunction); 979 980 if (Value *RetVal = Body->Codegen()) { 981 // Finish off the function. 982 Builder.CreateRet(RetVal); 983 984 // Validate the generated code, checking for consistency. 985 verifyFunction(*TheFunction); 986 987 // Optimize the function. 988 TheFPM->run(*TheFunction); 989 990 return TheFunction; 991 } 992 993 // Error reading body, remove function. 994 TheFunction->eraseFromParent(); 995 996 if (Proto->isBinaryOp()) 997 BinopPrecedence.erase(Proto->getOperatorName()); 998 return 0; 999} 1000 1001//===----------------------------------------------------------------------===// 1002// Top-Level parsing and JIT Driver 1003//===----------------------------------------------------------------------===// 1004 1005static ExecutionEngine *TheExecutionEngine; 1006 1007static void HandleDefinition() { 1008 if (FunctionAST *F = ParseDefinition()) { 1009 if (Function *LF = F->Codegen()) { 1010 fprintf(stderr, "Read function definition:"); 1011 LF->dump(); 1012 } 1013 } else { 1014 // Skip token for error recovery. 1015 getNextToken(); 1016 } 1017} 1018 1019static void HandleExtern() { 1020 if (PrototypeAST *P = ParseExtern()) { 1021 if (Function *F = P->Codegen()) { 1022 fprintf(stderr, "Read extern: "); 1023 F->dump(); 1024 } 1025 } else { 1026 // Skip token for error recovery. 1027 getNextToken(); 1028 } 1029} 1030 1031static void HandleTopLevelExpression() { 1032 // Evaluate a top-level expression into an anonymous function. 1033 if (FunctionAST *F = ParseTopLevelExpr()) { 1034 if (Function *LF = F->Codegen()) { 1035 // JIT the function, returning a function pointer. 1036 void *FPtr = TheExecutionEngine->getPointerToFunction(LF); 1037 1038 // Cast it to the right type (takes no arguments, returns a double) so we 1039 // can call it as a native function. 1040 double (*FP)() = (double (*)())(intptr_t)FPtr; 1041 fprintf(stderr, "Evaluated to %f\n", FP()); 1042 } 1043 } else { 1044 // Skip token for error recovery. 1045 getNextToken(); 1046 } 1047} 1048 1049/// top ::= definition | external | expression | ';' 1050static void MainLoop() { 1051 while (1) { 1052 fprintf(stderr, "ready> "); 1053 switch (CurTok) { 1054 case tok_eof: return; 1055 case ';': getNextToken(); break; // ignore top-level semicolons. 1056 case tok_def: HandleDefinition(); break; 1057 case tok_extern: HandleExtern(); break; 1058 default: HandleTopLevelExpression(); break; 1059 } 1060 } 1061} 1062 1063//===----------------------------------------------------------------------===// 1064// "Library" functions that can be "extern'd" from user code. 1065//===----------------------------------------------------------------------===// 1066 1067/// putchard - putchar that takes a double and returns 0. 1068extern "C" 1069double putchard(double X) { 1070 putchar((char)X); 1071 return 0; 1072} 1073 1074/// printd - printf that takes a double prints it as "%f\n", returning 0. 1075extern "C" 1076double printd(double X) { 1077 printf("%f\n", X); 1078 return 0; 1079} 1080 1081//===----------------------------------------------------------------------===// 1082// Main driver code. 1083//===----------------------------------------------------------------------===// 1084 1085int main() { 1086 InitializeNativeTarget(); 1087 LLVMContext &Context = getGlobalContext(); 1088 1089 // Install standard binary operators. 1090 // 1 is lowest precedence. 1091 BinopPrecedence['='] = 2; 1092 BinopPrecedence['<'] = 10; 1093 BinopPrecedence['+'] = 20; 1094 BinopPrecedence['-'] = 20; 1095 BinopPrecedence['*'] = 40; // highest. 1096 1097 // Prime the first token. 1098 fprintf(stderr, "ready> "); 1099 getNextToken(); 1100 1101 // Make the module, which holds all the code. 1102 TheModule = new Module("my cool jit", Context); 1103 1104 // Create the JIT. This takes ownership of the module. 1105 std::string ErrStr; 1106 TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create(); 1107 if (!TheExecutionEngine) { 1108 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str()); 1109 exit(1); 1110 } 1111 1112 FunctionPassManager OurFPM(TheModule); 1113 1114 // Set up the optimizer pipeline. Start with registering info about how the 1115 // target lays out data structures. 1116 TheModule->setDataLayout(TheExecutionEngine->getDataLayout()); 1117 OurFPM.add(new DataLayoutPass(TheModule)); 1118 // Provide basic AliasAnalysis support for GVN. 1119 OurFPM.add(createBasicAliasAnalysisPass()); 1120 // Promote allocas to registers. 1121 OurFPM.add(createPromoteMemoryToRegisterPass()); 1122 // Do simple "peephole" optimizations and bit-twiddling optzns. 1123 OurFPM.add(createInstructionCombiningPass()); 1124 // Reassociate expressions. 1125 OurFPM.add(createReassociatePass()); 1126 // Eliminate Common SubExpressions. 1127 OurFPM.add(createGVNPass()); 1128 // Simplify the control flow graph (deleting unreachable blocks, etc). 1129 OurFPM.add(createCFGSimplificationPass()); 1130 1131 OurFPM.doInitialization(); 1132 1133 // Set the global so the code gen can use this. 1134 TheFPM = &OurFPM; 1135 1136 // Run the main "interpreter loop" now. 1137 MainLoop(); 1138 1139 TheFPM = 0; 1140 1141 // Print out all of the generated code. 1142 TheModule->dump(); 1143 1144 return 0; 1145} 1146