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