1 #include "llvm/Analysis/Passes.h" 2 #include "llvm/Analysis/Verifier.h" 3 #include "llvm/ExecutionEngine/ExecutionEngine.h" 4 #include "llvm/ExecutionEngine/MCJIT.h" 5 #include "llvm/ExecutionEngine/SectionMemoryManager.h" 6 #include "llvm/IR/DataLayout.h" 7 #include "llvm/IR/DerivedTypes.h" 8 #include "llvm/IR/IRBuilder.h" 9 #include "llvm/IR/LLVMContext.h" 10 #include "llvm/IR/Module.h" 11 #include "llvm/PassManager.h" 12 #include "llvm/Support/TargetSelect.h" 13 #include "llvm/Transforms/Scalar.h" 14 #include <cstdio> 15 #include <map> 16 #include <string> 17 #include <vector> 18 using 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. 26 enum 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 46 static std::string IdentifierStr; // Filled in if tok_identifier 47 static double NumVal; // Filled in if tok_number 48 49 /// gettok - Return the next token from standard input. 50 static 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 //===----------------------------------------------------------------------===// 108 109 /// ExprAST - Base class for all expression nodes. 110 class ExprAST { 111 public: 112 virtual ~ExprAST() {} 113 virtual Value *Codegen() = 0; 114 }; 115 116 /// NumberExprAST - Expression class for numeric literals like "1.0". 117 class NumberExprAST : public ExprAST { 118 double Val; 119 public: 120 NumberExprAST(double val) : Val(val) {} 121 virtual Value *Codegen(); 122 }; 123 124 /// VariableExprAST - Expression class for referencing a variable, like "a". 125 class VariableExprAST : public ExprAST { 126 std::string Name; 127 public: 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. 134 class UnaryExprAST : public ExprAST { 135 char Opcode; 136 ExprAST *Operand; 137 public: 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. 144 class BinaryExprAST : public ExprAST { 145 char Op; 146 ExprAST *LHS, *RHS; 147 public: 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. 154 class CallExprAST : public ExprAST { 155 std::string Callee; 156 std::vector<ExprAST*> Args; 157 public: 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. 164 class IfExprAST : public ExprAST { 165 ExprAST *Cond, *Then, *Else; 166 public: 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. 173 class ForExprAST : public ExprAST { 174 std::string VarName; 175 ExprAST *Start, *End, *Step, *Body; 176 public: 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 184 class VarExprAST : public ExprAST { 185 std::vector<std::pair<std::string, ExprAST*> > VarNames; 186 ExprAST *Body; 187 public: 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. 197 class PrototypeAST { 198 std::string Name; 199 std::vector<std::string> Args; 200 bool isOperator; 201 unsigned Precedence; // Precedence if a binary op. 202 public: 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. 223 class FunctionAST { 224 PrototypeAST *Proto; 225 ExprAST *Body; 226 public: 227 FunctionAST(PrototypeAST *proto, ExprAST *body) 228 : Proto(proto), Body(body) {} 229 230 Function *Codegen(); 231 }; 232 233 //===----------------------------------------------------------------------===// 234 // Parser 235 //===----------------------------------------------------------------------===// 236 237 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current 238 /// token the parser is looking at. getNextToken reads another token from the 239 /// lexer and updates CurTok with its results. 240 static int CurTok; 241 static int getNextToken() { 242 return CurTok = gettok(); 243 } 244 245 /// BinopPrecedence - This holds the precedence for each binary operator that is 246 /// defined. 247 static std::map<char, int> BinopPrecedence; 248 249 /// GetTokPrecedence - Get the precedence of the pending binary operator token. 250 static int GetTokPrecedence() { 251 if (!isascii(CurTok)) 252 return -1; 253 254 // Make sure it's a declared binop. 255 int TokPrec = BinopPrecedence[CurTok]; 256 if (TokPrec <= 0) return -1; 257 return TokPrec; 258 } 259 260 /// Error* - These are little helper functions for error handling. 261 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;} 262 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; } 263 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; } 264 265 static ExprAST *ParseExpression(); 266 267 /// identifierexpr 268 /// ::= identifier 269 /// ::= identifier '(' expression* ')' 270 static ExprAST *ParseIdentifierExpr() { 271 std::string IdName = IdentifierStr; 272 273 getNextToken(); // eat identifier. 274 275 if (CurTok != '(') // Simple variable ref. 276 return new VariableExprAST(IdName); 277 278 // Call. 279 getNextToken(); // eat ( 280 std::vector<ExprAST*> Args; 281 if (CurTok != ')') { 282 while (1) { 283 ExprAST *Arg = ParseExpression(); 284 if (!Arg) return 0; 285 Args.push_back(Arg); 286 287 if (CurTok == ')') break; 288 289 if (CurTok != ',') 290 return Error("Expected ')' or ',' in argument list"); 291 getNextToken(); 292 } 293 } 294 295 // Eat the ')'. 296 getNextToken(); 297 298 return new CallExprAST(IdName, Args); 299 } 300 301 /// numberexpr ::= number 302 static ExprAST *ParseNumberExpr() { 303 ExprAST *Result = new NumberExprAST(NumVal); 304 getNextToken(); // consume the number 305 return Result; 306 } 307 308 /// parenexpr ::= '(' expression ')' 309 static ExprAST *ParseParenExpr() { 310 getNextToken(); // eat (. 311 ExprAST *V = ParseExpression(); 312 if (!V) return 0; 313 314 if (CurTok != ')') 315 return Error("expected ')'"); 316 getNextToken(); // eat ). 317 return V; 318 } 319 320 /// ifexpr ::= 'if' expression 'then' expression 'else' expression 321 static ExprAST *ParseIfExpr() { 322 getNextToken(); // eat the if. 323 324 // condition. 325 ExprAST *Cond = ParseExpression(); 326 if (!Cond) return 0; 327 328 if (CurTok != tok_then) 329 return Error("expected then"); 330 getNextToken(); // eat the then 331 332 ExprAST *Then = ParseExpression(); 333 if (Then == 0) return 0; 334 335 if (CurTok != tok_else) 336 return Error("expected else"); 337 338 getNextToken(); 339 340 ExprAST *Else = ParseExpression(); 341 if (!Else) return 0; 342 343 return new IfExprAST(Cond, Then, Else); 344 } 345 346 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression 347 static ExprAST *ParseForExpr() { 348 getNextToken(); // eat the for. 349 350 if (CurTok != tok_identifier) 351 return Error("expected identifier after for"); 352 353 std::string IdName = IdentifierStr; 354 getNextToken(); // eat identifier. 355 356 if (CurTok != '=') 357 return Error("expected '=' after for"); 358 getNextToken(); // eat '='. 359 360 361 ExprAST *Start = ParseExpression(); 362 if (Start == 0) return 0; 363 if (CurTok != ',') 364 return Error("expected ',' after for start value"); 365 getNextToken(); 366 367 ExprAST *End = ParseExpression(); 368 if (End == 0) return 0; 369 370 // The step value is optional. 371 ExprAST *Step = 0; 372 if (CurTok == ',') { 373 getNextToken(); 374 Step = ParseExpression(); 375 if (Step == 0) return 0; 376 } 377 378 if (CurTok != tok_in) 379 return Error("expected 'in' after for"); 380 getNextToken(); // eat 'in'. 381 382 ExprAST *Body = ParseExpression(); 383 if (Body == 0) return 0; 384 385 return new ForExprAST(IdName, Start, End, Step, Body); 386 } 387 388 /// varexpr ::= 'var' identifier ('=' expression)? 389 // (',' identifier ('=' expression)?)* 'in' expression 390 static ExprAST *ParseVarExpr() { 391 getNextToken(); // eat the var. 392 393 std::vector<std::pair<std::string, ExprAST*> > VarNames; 394 395 // At least one variable name is required. 396 if (CurTok != tok_identifier) 397 return Error("expected identifier after var"); 398 399 while (1) { 400 std::string Name = IdentifierStr; 401 getNextToken(); // eat identifier. 402 403 // Read the optional initializer. 404 ExprAST *Init = 0; 405 if (CurTok == '=') { 406 getNextToken(); // eat the '='. 407 408 Init = ParseExpression(); 409 if (Init == 0) return 0; 410 } 411 412 VarNames.push_back(std::make_pair(Name, Init)); 413 414 // End of var list, exit loop. 415 if (CurTok != ',') break; 416 getNextToken(); // eat the ','. 417 418 if (CurTok != tok_identifier) 419 return Error("expected identifier list after var"); 420 } 421 422 // At this point, we have to have 'in'. 423 if (CurTok != tok_in) 424 return Error("expected 'in' keyword after 'var'"); 425 getNextToken(); // eat 'in'. 426 427 ExprAST *Body = ParseExpression(); 428 if (Body == 0) return 0; 429 430 return new VarExprAST(VarNames, Body); 431 } 432 433 /// primary 434 /// ::= identifierexpr 435 /// ::= numberexpr 436 /// ::= parenexpr 437 /// ::= ifexpr 438 /// ::= forexpr 439 /// ::= varexpr 440 static ExprAST *ParsePrimary() { 441 switch (CurTok) { 442 default: return Error("unknown token when expecting an expression"); 443 case tok_identifier: return ParseIdentifierExpr(); 444 case tok_number: return ParseNumberExpr(); 445 case '(': return ParseParenExpr(); 446 case tok_if: return ParseIfExpr(); 447 case tok_for: return ParseForExpr(); 448 case tok_var: return ParseVarExpr(); 449 } 450 } 451 452 /// unary 453 /// ::= primary 454 /// ::= '!' unary 455 static ExprAST *ParseUnary() { 456 // If the current token is not an operator, it must be a primary expr. 457 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',') 458 return ParsePrimary(); 459 460 // If this is a unary operator, read it. 461 int Opc = CurTok; 462 getNextToken(); 463 if (ExprAST *Operand = ParseUnary()) 464 return new UnaryExprAST(Opc, Operand); 465 return 0; 466 } 467 468 /// binoprhs 469 /// ::= ('+' unary)* 470 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) { 471 // If this is a binop, find its precedence. 472 while (1) { 473 int TokPrec = GetTokPrecedence(); 474 475 // If this is a binop that binds at least as tightly as the current binop, 476 // consume it, otherwise we are done. 477 if (TokPrec < ExprPrec) 478 return LHS; 479 480 // Okay, we know this is a binop. 481 int BinOp = CurTok; 482 getNextToken(); // eat binop 483 484 // Parse the unary expression after the binary operator. 485 ExprAST *RHS = ParseUnary(); 486 if (!RHS) return 0; 487 488 // If BinOp binds less tightly with RHS than the operator after RHS, let 489 // the pending operator take RHS as its LHS. 490 int NextPrec = GetTokPrecedence(); 491 if (TokPrec < NextPrec) { 492 RHS = ParseBinOpRHS(TokPrec+1, RHS); 493 if (RHS == 0) return 0; 494 } 495 496 // Merge LHS/RHS. 497 LHS = new BinaryExprAST(BinOp, LHS, RHS); 498 } 499 } 500 501 /// expression 502 /// ::= unary binoprhs 503 /// 504 static ExprAST *ParseExpression() { 505 ExprAST *LHS = ParseUnary(); 506 if (!LHS) return 0; 507 508 return ParseBinOpRHS(0, LHS); 509 } 510 511 /// prototype 512 /// ::= id '(' id* ')' 513 /// ::= binary LETTER number? (id, id) 514 /// ::= unary LETTER (id) 515 static PrototypeAST *ParsePrototype() { 516 std::string FnName; 517 518 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary. 519 unsigned BinaryPrecedence = 30; 520 521 switch (CurTok) { 522 default: 523 return ErrorP("Expected function name in prototype"); 524 case tok_identifier: 525 FnName = IdentifierStr; 526 Kind = 0; 527 getNextToken(); 528 break; 529 case tok_unary: 530 getNextToken(); 531 if (!isascii(CurTok)) 532 return ErrorP("Expected unary operator"); 533 FnName = "unary"; 534 FnName += (char)CurTok; 535 Kind = 1; 536 getNextToken(); 537 break; 538 case tok_binary: 539 getNextToken(); 540 if (!isascii(CurTok)) 541 return ErrorP("Expected binary operator"); 542 FnName = "binary"; 543 FnName += (char)CurTok; 544 Kind = 2; 545 getNextToken(); 546 547 // Read the precedence if present. 548 if (CurTok == tok_number) { 549 if (NumVal < 1 || NumVal > 100) 550 return ErrorP("Invalid precedecnce: must be 1..100"); 551 BinaryPrecedence = (unsigned)NumVal; 552 getNextToken(); 553 } 554 break; 555 } 556 557 if (CurTok != '(') 558 return ErrorP("Expected '(' in prototype"); 559 560 std::vector<std::string> ArgNames; 561 while (getNextToken() == tok_identifier) 562 ArgNames.push_back(IdentifierStr); 563 if (CurTok != ')') 564 return ErrorP("Expected ')' in prototype"); 565 566 // success. 567 getNextToken(); // eat ')'. 568 569 // Verify right number of names for operator. 570 if (Kind && ArgNames.size() != Kind) 571 return ErrorP("Invalid number of operands for operator"); 572 573 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence); 574 } 575 576 /// definition ::= 'def' prototype expression 577 static FunctionAST *ParseDefinition() { 578 getNextToken(); // eat def. 579 PrototypeAST *Proto = ParsePrototype(); 580 if (Proto == 0) return 0; 581 582 if (ExprAST *E = ParseExpression()) 583 return new FunctionAST(Proto, E); 584 return 0; 585 } 586 587 /// toplevelexpr ::= expression 588 static FunctionAST *ParseTopLevelExpr() { 589 if (ExprAST *E = ParseExpression()) { 590 // Make an anonymous proto. 591 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>()); 592 return new FunctionAST(Proto, E); 593 } 594 return 0; 595 } 596 597 /// external ::= 'extern' prototype 598 static PrototypeAST *ParseExtern() { 599 getNextToken(); // eat extern. 600 return ParsePrototype(); 601 } 602 603 //===----------------------------------------------------------------------===// 604 // Quick and dirty hack 605 //===----------------------------------------------------------------------===// 606 607 // FIXME: Obviously we can do better than this 608 std::string GenerateUniqueName(const char *root) 609 { 610 static int i = 0; 611 char s[16]; 612 sprintf(s, "%s%d", root, i++); 613 std::string S = s; 614 return S; 615 } 616 617 std::string MakeLegalFunctionName(std::string Name) 618 { 619 std::string NewName; 620 if (!Name.length()) 621 return GenerateUniqueName("anon_func_"); 622 623 // Start with what we have 624 NewName = Name; 625 626 // Look for a numberic first character 627 if (NewName.find_first_of("0123456789") == 0) { 628 NewName.insert(0, 1, 'n'); 629 } 630 631 // Replace illegal characters with their ASCII equivalent 632 std::string legal_elements = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 633 size_t pos; 634 while ((pos = NewName.find_first_not_of(legal_elements)) != std::string::npos) { 635 char old_c = NewName.at(pos); 636 char new_str[16]; 637 sprintf(new_str, "%d", (int)old_c); 638 NewName = NewName.replace(pos, 1, new_str); 639 } 640 641 return NewName; 642 } 643 644 //===----------------------------------------------------------------------===// 645 // MCJIT helper class 646 //===----------------------------------------------------------------------===// 647 648 class MCJITHelper 649 { 650 public: 651 MCJITHelper(LLVMContext& C) : Context(C), OpenModule(NULL) {} 652 ~MCJITHelper(); 653 654 Function *getFunction(const std::string FnName); 655 Module *getModuleForNewFunction(); 656 void *getPointerToFunction(Function* F); 657 void *getPointerToNamedFunction(const std::string &Name); 658 void dump(); 659 660 private: 661 typedef std::vector<Module*> ModuleVector; 662 typedef std::vector<ExecutionEngine*> EngineVector; 663 664 LLVMContext &Context; 665 Module *OpenModule; 666 ModuleVector Modules; 667 EngineVector Engines; 668 }; 669 670 class HelpingMemoryManager : public SectionMemoryManager 671 { 672 HelpingMemoryManager(const HelpingMemoryManager&) LLVM_DELETED_FUNCTION; 673 void operator=(const HelpingMemoryManager&) LLVM_DELETED_FUNCTION; 674 675 public: 676 HelpingMemoryManager(MCJITHelper *Helper) : MasterHelper(Helper) {} 677 virtual ~HelpingMemoryManager() {} 678 679 /// This method returns the address of the specified function. 680 /// Our implementation will attempt to find functions in other 681 /// modules associated with the MCJITHelper to cross link functions 682 /// from one generated module to another. 683 /// 684 /// If \p AbortOnFailure is false and no function with the given name is 685 /// found, this function returns a null pointer. Otherwise, it prints a 686 /// message to stderr and aborts. 687 virtual void *getPointerToNamedFunction(const std::string &Name, 688 bool AbortOnFailure = true); 689 private: 690 MCJITHelper *MasterHelper; 691 }; 692 693 void *HelpingMemoryManager::getPointerToNamedFunction(const std::string &Name, 694 bool AbortOnFailure) 695 { 696 // Try the standard symbol resolution first, but ask it not to abort. 697 void *pfn = SectionMemoryManager::getPointerToNamedFunction(Name, false); 698 if (pfn) 699 return pfn; 700 701 pfn = MasterHelper->getPointerToNamedFunction(Name); 702 if (!pfn && AbortOnFailure) 703 report_fatal_error("Program used external function '" + Name + 704 "' which could not be resolved!"); 705 return pfn; 706 } 707 708 MCJITHelper::~MCJITHelper() 709 { 710 if (OpenModule) 711 delete OpenModule; 712 EngineVector::iterator begin = Engines.begin(); 713 EngineVector::iterator end = Engines.end(); 714 EngineVector::iterator it; 715 for (it = begin; it != end; ++it) 716 delete *it; 717 } 718 719 Function *MCJITHelper::getFunction(const std::string FnName) { 720 ModuleVector::iterator begin = Modules.begin(); 721 ModuleVector::iterator end = Modules.end(); 722 ModuleVector::iterator it; 723 for (it = begin; it != end; ++it) { 724 Function *F = (*it)->getFunction(FnName); 725 if (F) { 726 if (*it == OpenModule) 727 return F; 728 729 assert(OpenModule != NULL); 730 731 // This function is in a module that has already been JITed. 732 // We need to generate a new prototype for external linkage. 733 Function *PF = OpenModule->getFunction(FnName); 734 if (PF && !PF->empty()) { 735 ErrorF("redefinition of function across modules"); 736 return 0; 737 } 738 739 // If we don't have a prototype yet, create one. 740 if (!PF) 741 PF = Function::Create(F->getFunctionType(), 742 Function::ExternalLinkage, 743 FnName, 744 OpenModule); 745 return PF; 746 } 747 } 748 return NULL; 749 } 750 751 Module *MCJITHelper::getModuleForNewFunction() { 752 // If we have a Module that hasn't been JITed, use that. 753 if (OpenModule) 754 return OpenModule; 755 756 // Otherwise create a new Module. 757 std::string ModName = GenerateUniqueName("mcjit_module_"); 758 Module *M = new Module(ModName, Context); 759 Modules.push_back(M); 760 OpenModule = M; 761 return M; 762 } 763 764 void *MCJITHelper::getPointerToFunction(Function* F) { 765 // See if an existing instance of MCJIT has this function. 766 EngineVector::iterator begin = Engines.begin(); 767 EngineVector::iterator end = Engines.end(); 768 EngineVector::iterator it; 769 for (it = begin; it != end; ++it) { 770 void *P = (*it)->getPointerToFunction(F); 771 if (P) 772 return P; 773 } 774 775 // If we didn't find the function, see if we can generate it. 776 if (OpenModule) { 777 std::string ErrStr; 778 ExecutionEngine *NewEngine = EngineBuilder(OpenModule) 779 .setErrorStr(&ErrStr) 780 .setUseMCJIT(true) 781 .setMCJITMemoryManager(new HelpingMemoryManager(this)) 782 .create(); 783 if (!NewEngine) { 784 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str()); 785 exit(1); 786 } 787 788 // Create a function pass manager for this engine 789 FunctionPassManager *FPM = new FunctionPassManager(OpenModule); 790 791 // Set up the optimizer pipeline. Start with registering info about how the 792 // target lays out data structures. 793 FPM->add(new DataLayout(*NewEngine->getDataLayout())); 794 // Provide basic AliasAnalysis support for GVN. 795 FPM->add(createBasicAliasAnalysisPass()); 796 // Promote allocas to registers. 797 FPM->add(createPromoteMemoryToRegisterPass()); 798 // Do simple "peephole" optimizations and bit-twiddling optzns. 799 FPM->add(createInstructionCombiningPass()); 800 // Reassociate expressions. 801 FPM->add(createReassociatePass()); 802 // Eliminate Common SubExpressions. 803 FPM->add(createGVNPass()); 804 // Simplify the control flow graph (deleting unreachable blocks, etc). 805 FPM->add(createCFGSimplificationPass()); 806 FPM->doInitialization(); 807 808 // For each function in the module 809 Module::iterator it; 810 Module::iterator end = OpenModule->end(); 811 for (it = OpenModule->begin(); it != end; ++it) { 812 // Run the FPM on this function 813 FPM->run(*it); 814 } 815 816 // We don't need this anymore 817 delete FPM; 818 819 OpenModule = NULL; 820 Engines.push_back(NewEngine); 821 NewEngine->finalizeObject(); 822 return NewEngine->getPointerToFunction(F); 823 } 824 return NULL; 825 } 826 827 void *MCJITHelper::getPointerToNamedFunction(const std::string &Name) 828 { 829 // Look for the function in each of our execution engines. 830 EngineVector::iterator begin = Engines.begin(); 831 EngineVector::iterator end = Engines.end(); 832 EngineVector::iterator it; 833 for (it = begin; it != end; ++it) { 834 if (Function *F = (*it)->FindFunctionNamed(Name.c_str())) 835 return (*it)->getPointerToFunction(F); 836 } 837 838 return NULL; 839 } 840 841 void MCJITHelper::dump() 842 { 843 ModuleVector::iterator begin = Modules.begin(); 844 ModuleVector::iterator end = Modules.end(); 845 ModuleVector::iterator it; 846 for (it = begin; it != end; ++it) 847 (*it)->dump(); 848 } 849 850 //===----------------------------------------------------------------------===// 851 // Code Generation 852 //===----------------------------------------------------------------------===// 853 854 static MCJITHelper *TheHelper; 855 static IRBuilder<> Builder(getGlobalContext()); 856 static std::map<std::string, AllocaInst*> NamedValues; 857 858 Value *ErrorV(const char *Str) { Error(Str); return 0; } 859 860 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of 861 /// the function. This is used for mutable variables etc. 862 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction, 863 const std::string &VarName) { 864 IRBuilder<> TmpB(&TheFunction->getEntryBlock(), 865 TheFunction->getEntryBlock().begin()); 866 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0, 867 VarName.c_str()); 868 } 869 870 Value *NumberExprAST::Codegen() { 871 return ConstantFP::get(getGlobalContext(), APFloat(Val)); 872 } 873 874 Value *VariableExprAST::Codegen() { 875 // Look this variable up in the function. 876 Value *V = NamedValues[Name]; 877 char ErrStr[256]; 878 sprintf(ErrStr, "Unknown variable name %s", Name.c_str()); 879 if (V == 0) return ErrorV(ErrStr); 880 881 // Load the value. 882 return Builder.CreateLoad(V, Name.c_str()); 883 } 884 885 Value *UnaryExprAST::Codegen() { 886 Value *OperandV = Operand->Codegen(); 887 if (OperandV == 0) return 0; 888 889 Function *F = TheHelper->getFunction(MakeLegalFunctionName(std::string("unary")+Opcode)); 890 if (F == 0) 891 return ErrorV("Unknown unary operator"); 892 893 return Builder.CreateCall(F, OperandV, "unop"); 894 } 895 896 Value *BinaryExprAST::Codegen() { 897 // Special case '=' because we don't want to emit the LHS as an expression. 898 if (Op == '=') { 899 // Assignment requires the LHS to be an identifier. 900 VariableExprAST *LHSE = reinterpret_cast<VariableExprAST*>(LHS); 901 if (!LHSE) 902 return ErrorV("destination of '=' must be a variable"); 903 // Codegen the RHS. 904 Value *Val = RHS->Codegen(); 905 if (Val == 0) return 0; 906 907 // Look up the name. 908 Value *Variable = NamedValues[LHSE->getName()]; 909 if (Variable == 0) return ErrorV("Unknown variable name"); 910 911 Builder.CreateStore(Val, Variable); 912 return Val; 913 } 914 915 Value *L = LHS->Codegen(); 916 Value *R = RHS->Codegen(); 917 if (L == 0 || R == 0) return 0; 918 919 switch (Op) { 920 case '+': return Builder.CreateFAdd(L, R, "addtmp"); 921 case '-': return Builder.CreateFSub(L, R, "subtmp"); 922 case '*': return Builder.CreateFMul(L, R, "multmp"); 923 case '/': return Builder.CreateFDiv(L, R, "divtmp"); 924 case '<': 925 L = Builder.CreateFCmpULT(L, R, "cmptmp"); 926 // Convert bool 0/1 to double 0.0 or 1.0 927 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()), 928 "booltmp"); 929 default: break; 930 } 931 932 // If it wasn't a builtin binary operator, it must be a user defined one. Emit 933 // a call to it. 934 Function *F = TheHelper->getFunction(MakeLegalFunctionName(std::string("binary")+Op)); 935 assert(F && "binary operator not found!"); 936 937 Value *Ops[] = { L, R }; 938 return Builder.CreateCall(F, Ops, "binop"); 939 } 940 941 Value *CallExprAST::Codegen() { 942 // Look up the name in the global module table. 943 Function *CalleeF = TheHelper->getFunction(Callee); 944 if (CalleeF == 0) 945 return ErrorV("Unknown function referenced"); 946 947 // If argument mismatch error. 948 if (CalleeF->arg_size() != Args.size()) 949 return ErrorV("Incorrect # arguments passed"); 950 951 std::vector<Value*> ArgsV; 952 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 953 ArgsV.push_back(Args[i]->Codegen()); 954 if (ArgsV.back() == 0) return 0; 955 } 956 957 return Builder.CreateCall(CalleeF, ArgsV, "calltmp"); 958 } 959 960 Value *IfExprAST::Codegen() { 961 Value *CondV = Cond->Codegen(); 962 if (CondV == 0) return 0; 963 964 // Convert condition to a bool by comparing equal to 0.0. 965 CondV = Builder.CreateFCmpONE(CondV, 966 ConstantFP::get(getGlobalContext(), APFloat(0.0)), 967 "ifcond"); 968 969 Function *TheFunction = Builder.GetInsertBlock()->getParent(); 970 971 // Create blocks for the then and else cases. Insert the 'then' block at the 972 // end of the function. 973 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction); 974 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else"); 975 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont"); 976 977 Builder.CreateCondBr(CondV, ThenBB, ElseBB); 978 979 // Emit then value. 980 Builder.SetInsertPoint(ThenBB); 981 982 Value *ThenV = Then->Codegen(); 983 if (ThenV == 0) return 0; 984 985 Builder.CreateBr(MergeBB); 986 // Codegen of 'Then' can change the current block, update ThenBB for the PHI. 987 ThenBB = Builder.GetInsertBlock(); 988 989 // Emit else block. 990 TheFunction->getBasicBlockList().push_back(ElseBB); 991 Builder.SetInsertPoint(ElseBB); 992 993 Value *ElseV = Else->Codegen(); 994 if (ElseV == 0) return 0; 995 996 Builder.CreateBr(MergeBB); 997 // Codegen of 'Else' can change the current block, update ElseBB for the PHI. 998 ElseBB = Builder.GetInsertBlock(); 999 1000 // Emit merge block. 1001 TheFunction->getBasicBlockList().push_back(MergeBB); 1002 Builder.SetInsertPoint(MergeBB); 1003 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, 1004 "iftmp"); 1005 1006 PN->addIncoming(ThenV, ThenBB); 1007 PN->addIncoming(ElseV, ElseBB); 1008 return PN; 1009 } 1010 1011 Value *ForExprAST::Codegen() { 1012 // Output this as: 1013 // var = alloca double 1014 // ... 1015 // start = startexpr 1016 // store start -> var 1017 // goto loop 1018 // loop: 1019 // ... 1020 // bodyexpr 1021 // ... 1022 // loopend: 1023 // step = stepexpr 1024 // endcond = endexpr 1025 // 1026 // curvar = load var 1027 // nextvar = curvar + step 1028 // store nextvar -> var 1029 // br endcond, loop, endloop 1030 // outloop: 1031 1032 Function *TheFunction = Builder.GetInsertBlock()->getParent(); 1033 1034 // Create an alloca for the variable in the entry block. 1035 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName); 1036 1037 // Emit the start code first, without 'variable' in scope. 1038 Value *StartVal = Start->Codegen(); 1039 if (StartVal == 0) return 0; 1040 1041 // Store the value into the alloca. 1042 Builder.CreateStore(StartVal, Alloca); 1043 1044 // Make the new basic block for the loop header, inserting after current 1045 // block. 1046 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction); 1047 1048 // Insert an explicit fall through from the current block to the LoopBB. 1049 Builder.CreateBr(LoopBB); 1050 1051 // Start insertion in LoopBB. 1052 Builder.SetInsertPoint(LoopBB); 1053 1054 // Within the loop, the variable is defined equal to the PHI node. If it 1055 // shadows an existing variable, we have to restore it, so save it now. 1056 AllocaInst *OldVal = NamedValues[VarName]; 1057 NamedValues[VarName] = Alloca; 1058 1059 // Emit the body of the loop. This, like any other expr, can change the 1060 // current BB. Note that we ignore the value computed by the body, but don't 1061 // allow an error. 1062 if (Body->Codegen() == 0) 1063 return 0; 1064 1065 // Emit the step value. 1066 Value *StepVal; 1067 if (Step) { 1068 StepVal = Step->Codegen(); 1069 if (StepVal == 0) return 0; 1070 } else { 1071 // If not specified, use 1.0. 1072 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0)); 1073 } 1074 1075 // Compute the end condition. 1076 Value *EndCond = End->Codegen(); 1077 if (EndCond == 0) return EndCond; 1078 1079 // Reload, increment, and restore the alloca. This handles the case where 1080 // the body of the loop mutates the variable. 1081 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str()); 1082 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar"); 1083 Builder.CreateStore(NextVar, Alloca); 1084 1085 // Convert condition to a bool by comparing equal to 0.0. 1086 EndCond = Builder.CreateFCmpONE(EndCond, 1087 ConstantFP::get(getGlobalContext(), APFloat(0.0)), 1088 "loopcond"); 1089 1090 // Create the "after loop" block and insert it. 1091 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction); 1092 1093 // Insert the conditional branch into the end of LoopEndBB. 1094 Builder.CreateCondBr(EndCond, LoopBB, AfterBB); 1095 1096 // Any new code will be inserted in AfterBB. 1097 Builder.SetInsertPoint(AfterBB); 1098 1099 // Restore the unshadowed variable. 1100 if (OldVal) 1101 NamedValues[VarName] = OldVal; 1102 else 1103 NamedValues.erase(VarName); 1104 1105 1106 // for expr always returns 0.0. 1107 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext())); 1108 } 1109 1110 Value *VarExprAST::Codegen() { 1111 std::vector<AllocaInst *> OldBindings; 1112 1113 Function *TheFunction = Builder.GetInsertBlock()->getParent(); 1114 1115 // Register all variables and emit their initializer. 1116 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) { 1117 const std::string &VarName = VarNames[i].first; 1118 ExprAST *Init = VarNames[i].second; 1119 1120 // Emit the initializer before adding the variable to scope, this prevents 1121 // the initializer from referencing the variable itself, and permits stuff 1122 // like this: 1123 // var a = 1 in 1124 // var a = a in ... # refers to outer 'a'. 1125 Value *InitVal; 1126 if (Init) { 1127 InitVal = Init->Codegen(); 1128 if (InitVal == 0) return 0; 1129 } else { // If not specified, use 0.0. 1130 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0)); 1131 } 1132 1133 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName); 1134 Builder.CreateStore(InitVal, Alloca); 1135 1136 // Remember the old variable binding so that we can restore the binding when 1137 // we unrecurse. 1138 OldBindings.push_back(NamedValues[VarName]); 1139 1140 // Remember this binding. 1141 NamedValues[VarName] = Alloca; 1142 } 1143 1144 // Codegen the body, now that all vars are in scope. 1145 Value *BodyVal = Body->Codegen(); 1146 if (BodyVal == 0) return 0; 1147 1148 // Pop all our variables from scope. 1149 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) 1150 NamedValues[VarNames[i].first] = OldBindings[i]; 1151 1152 // Return the body computation. 1153 return BodyVal; 1154 } 1155 1156 Function *PrototypeAST::Codegen() { 1157 // Make the function type: double(double,double) etc. 1158 std::vector<Type*> Doubles(Args.size(), 1159 Type::getDoubleTy(getGlobalContext())); 1160 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()), 1161 Doubles, false); 1162 1163 std::string FnName = MakeLegalFunctionName(Name); 1164 1165 Module* M = TheHelper->getModuleForNewFunction(); 1166 1167 Function *F = Function::Create(FT, Function::ExternalLinkage, FnName, M); 1168 1169 // If F conflicted, there was already something named 'FnName'. If it has a 1170 // body, don't allow redefinition or reextern. 1171 if (F->getName() != FnName) { 1172 // Delete the one we just made and get the existing one. 1173 F->eraseFromParent(); 1174 F = M->getFunction(Name); 1175 1176 // If F already has a body, reject this. 1177 if (!F->empty()) { 1178 ErrorF("redefinition of function"); 1179 return 0; 1180 } 1181 1182 // If F took a different number of args, reject. 1183 if (F->arg_size() != Args.size()) { 1184 ErrorF("redefinition of function with different # args"); 1185 return 0; 1186 } 1187 } 1188 1189 // Set names for all arguments. 1190 unsigned Idx = 0; 1191 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size(); 1192 ++AI, ++Idx) 1193 AI->setName(Args[Idx]); 1194 1195 return F; 1196 } 1197 1198 /// CreateArgumentAllocas - Create an alloca for each argument and register the 1199 /// argument in the symbol table so that references to it will succeed. 1200 void PrototypeAST::CreateArgumentAllocas(Function *F) { 1201 Function::arg_iterator AI = F->arg_begin(); 1202 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) { 1203 // Create an alloca for this variable. 1204 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]); 1205 1206 // Store the initial value into the alloca. 1207 Builder.CreateStore(AI, Alloca); 1208 1209 // Add arguments to variable symbol table. 1210 NamedValues[Args[Idx]] = Alloca; 1211 } 1212 } 1213 1214 Function *FunctionAST::Codegen() { 1215 NamedValues.clear(); 1216 1217 Function *TheFunction = Proto->Codegen(); 1218 if (TheFunction == 0) 1219 return 0; 1220 1221 // If this is an operator, install it. 1222 if (Proto->isBinaryOp()) 1223 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence(); 1224 1225 // Create a new basic block to start insertion into. 1226 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction); 1227 Builder.SetInsertPoint(BB); 1228 1229 // Add all arguments to the symbol table and create their allocas. 1230 Proto->CreateArgumentAllocas(TheFunction); 1231 1232 if (Value *RetVal = Body->Codegen()) { 1233 // Finish off the function. 1234 Builder.CreateRet(RetVal); 1235 1236 // Validate the generated code, checking for consistency. 1237 verifyFunction(*TheFunction); 1238 1239 return TheFunction; 1240 } 1241 1242 // Error reading body, remove function. 1243 TheFunction->eraseFromParent(); 1244 1245 if (Proto->isBinaryOp()) 1246 BinopPrecedence.erase(Proto->getOperatorName()); 1247 return 0; 1248 } 1249 1250 //===----------------------------------------------------------------------===// 1251 // Top-Level parsing and JIT Driver 1252 //===----------------------------------------------------------------------===// 1253 1254 static void HandleDefinition() { 1255 if (FunctionAST *F = ParseDefinition()) { 1256 if (Function *LF = F->Codegen()) { 1257 #ifndef MINIMAL_STDERR_OUTPUT 1258 fprintf(stderr, "Read function definition:"); 1259 LF->dump(); 1260 #endif 1261 } 1262 } else { 1263 // Skip token for error recovery. 1264 getNextToken(); 1265 } 1266 } 1267 1268 static void HandleExtern() { 1269 if (PrototypeAST *P = ParseExtern()) { 1270 if (Function *F = P->Codegen()) { 1271 #ifndef MINIMAL_STDERR_OUTPUT 1272 fprintf(stderr, "Read extern: "); 1273 F->dump(); 1274 #endif 1275 } 1276 } else { 1277 // Skip token for error recovery. 1278 getNextToken(); 1279 } 1280 } 1281 1282 static void HandleTopLevelExpression() { 1283 // Evaluate a top-level expression into an anonymous function. 1284 if (FunctionAST *F = ParseTopLevelExpr()) { 1285 if (Function *LF = F->Codegen()) { 1286 // JIT the function, returning a function pointer. 1287 void *FPtr = TheHelper->getPointerToFunction(LF); 1288 1289 // Cast it to the right type (takes no arguments, returns a double) so we 1290 // can call it as a native function. 1291 double (*FP)() = (double (*)())(intptr_t)FPtr; 1292 #ifdef MINIMAL_STDERR_OUTPUT 1293 FP(); 1294 #else 1295 fprintf(stderr, "Evaluated to %f\n", FP()); 1296 #endif 1297 } 1298 } else { 1299 // Skip token for error recovery. 1300 getNextToken(); 1301 } 1302 } 1303 1304 /// top ::= definition | external | expression | ';' 1305 static void MainLoop() { 1306 while (1) { 1307 #ifndef MINIMAL_STDERR_OUTPUT 1308 fprintf(stderr, "ready> "); 1309 #endif 1310 switch (CurTok) { 1311 case tok_eof: return; 1312 case ';': getNextToken(); break; // ignore top-level semicolons. 1313 case tok_def: HandleDefinition(); break; 1314 case tok_extern: HandleExtern(); break; 1315 default: HandleTopLevelExpression(); break; 1316 } 1317 } 1318 } 1319 1320 //===----------------------------------------------------------------------===// 1321 // "Library" functions that can be "extern'd" from user code. 1322 //===----------------------------------------------------------------------===// 1323 1324 /// putchard - putchar that takes a double and returns 0. 1325 extern "C" 1326 double putchard(double X) { 1327 putchar((char)X); 1328 return 0; 1329 } 1330 1331 /// printd - printf that takes a double prints it as "%f\n", returning 0. 1332 extern "C" 1333 double printd(double X) { 1334 printf("%f", X); 1335 return 0; 1336 } 1337 1338 extern "C" 1339 double printlf() { 1340 printf("\n"); 1341 return 0; 1342 } 1343 1344 //===----------------------------------------------------------------------===// 1345 // Main driver code. 1346 //===----------------------------------------------------------------------===// 1347 1348 int main() { 1349 InitializeNativeTarget(); 1350 InitializeNativeTargetAsmPrinter(); 1351 InitializeNativeTargetAsmParser(); 1352 LLVMContext &Context = getGlobalContext(); 1353 1354 // Install standard binary operators. 1355 // 1 is lowest precedence. 1356 BinopPrecedence['='] = 2; 1357 BinopPrecedence['<'] = 10; 1358 BinopPrecedence['+'] = 20; 1359 BinopPrecedence['-'] = 20; 1360 BinopPrecedence['/'] = 40; 1361 BinopPrecedence['*'] = 40; // highest. 1362 1363 // Prime the first token. 1364 #ifndef MINIMAL_STDERR_OUTPUT 1365 fprintf(stderr, "ready> "); 1366 #endif 1367 getNextToken(); 1368 1369 // Make the helper, which holds all the code. 1370 TheHelper = new MCJITHelper(Context); 1371 1372 // Run the main "interpreter loop" now. 1373 MainLoop(); 1374 1375 #ifndef MINIMAL_STDERR_OUTPUT 1376 // Print out all of the generated code. 1377 TheHelper->dump(); 1378 #endif 1379 1380 return 0; 1381 } 1382