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