NAKAMURA Takumi | 85c9bac | 2015-03-02 01:04:34 +0000 | [diff] [blame] | 1 | #include "llvm/ADT/STLExtras.h" |
Chandler Carruth | 17e0bc3 | 2015-08-06 07:33:15 +0000 | [diff] [blame^] | 2 | #include "llvm/Analysis/BasicAliasAnalysis.h" |
Chandler Carruth | 605e30e | 2012-12-04 10:16:57 +0000 | [diff] [blame] | 3 | #include "llvm/Analysis/Passes.h" |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 4 | #include "llvm/ExecutionEngine/ExecutionEngine.h" |
Eric Christopher | 1b74b65 | 2014-12-08 18:00:38 +0000 | [diff] [blame] | 5 | #include "llvm/ExecutionEngine/MCJIT.h" |
| 6 | #include "llvm/ExecutionEngine/SectionMemoryManager.h" |
Chandler Carruth | 005f27a | 2013-01-02 11:56:33 +0000 | [diff] [blame] | 7 | #include "llvm/IR/DataLayout.h" |
| 8 | #include "llvm/IR/DerivedTypes.h" |
| 9 | #include "llvm/IR/IRBuilder.h" |
| 10 | #include "llvm/IR/LLVMContext.h" |
Chandler Carruth | 30d69c2 | 2015-02-13 10:01:29 +0000 | [diff] [blame] | 11 | #include "llvm/IR/LegacyPassManager.h" |
Chandler Carruth | 005f27a | 2013-01-02 11:56:33 +0000 | [diff] [blame] | 12 | #include "llvm/IR/Module.h" |
Chandler Carruth | 20d4e6b | 2014-01-13 09:58:03 +0000 | [diff] [blame] | 13 | #include "llvm/IR/Verifier.h" |
Evan Cheng | 2bb4035 | 2011-08-24 18:08:43 +0000 | [diff] [blame] | 14 | #include "llvm/Support/TargetSelect.h" |
Chandler Carruth | 605e30e | 2012-12-04 10:16:57 +0000 | [diff] [blame] | 15 | #include "llvm/Transforms/Scalar.h" |
Will Dietz | 981af00 | 2013-10-12 00:55:57 +0000 | [diff] [blame] | 16 | #include <cctype> |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 17 | #include <cstdio> |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 18 | #include <map> |
Chandler Carruth | 605e30e | 2012-12-04 10:16:57 +0000 | [diff] [blame] | 19 | #include <string> |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 20 | #include <vector> |
| 21 | using namespace llvm; |
| 22 | |
| 23 | //===----------------------------------------------------------------------===// |
| 24 | // Lexer |
| 25 | //===----------------------------------------------------------------------===// |
| 26 | |
| 27 | // The lexer returns tokens [0-255] if it is an unknown character, otherwise one |
| 28 | // of these for known things. |
| 29 | enum Token { |
| 30 | tok_eof = -1, |
| 31 | |
| 32 | // commands |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 33 | tok_def = -2, |
| 34 | tok_extern = -3, |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 35 | |
| 36 | // primary |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 37 | tok_identifier = -4, |
| 38 | tok_number = -5, |
| 39 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 40 | // control |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 41 | tok_if = -6, |
| 42 | tok_then = -7, |
| 43 | tok_else = -8, |
| 44 | tok_for = -9, |
| 45 | tok_in = -10 |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 46 | }; |
| 47 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 48 | static std::string IdentifierStr; // Filled in if tok_identifier |
| 49 | static double NumVal; // Filled in if tok_number |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 50 | |
| 51 | /// gettok - Return the next token from standard input. |
| 52 | static int gettok() { |
| 53 | static int LastChar = ' '; |
| 54 | |
| 55 | // Skip any whitespace. |
| 56 | while (isspace(LastChar)) |
| 57 | LastChar = getchar(); |
| 58 | |
| 59 | if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]* |
| 60 | IdentifierStr = LastChar; |
| 61 | while (isalnum((LastChar = getchar()))) |
| 62 | IdentifierStr += LastChar; |
| 63 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 64 | if (IdentifierStr == "def") |
| 65 | return tok_def; |
| 66 | if (IdentifierStr == "extern") |
| 67 | return tok_extern; |
| 68 | if (IdentifierStr == "if") |
| 69 | return tok_if; |
| 70 | if (IdentifierStr == "then") |
| 71 | return tok_then; |
| 72 | if (IdentifierStr == "else") |
| 73 | return tok_else; |
| 74 | if (IdentifierStr == "for") |
| 75 | return tok_for; |
| 76 | if (IdentifierStr == "in") |
| 77 | return tok_in; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 78 | return tok_identifier; |
| 79 | } |
| 80 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 81 | if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+ |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 82 | std::string NumStr; |
| 83 | do { |
| 84 | NumStr += LastChar; |
| 85 | LastChar = getchar(); |
| 86 | } while (isdigit(LastChar) || LastChar == '.'); |
| 87 | |
| 88 | NumVal = strtod(NumStr.c_str(), 0); |
| 89 | return tok_number; |
| 90 | } |
| 91 | |
| 92 | if (LastChar == '#') { |
| 93 | // Comment until end of line. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 94 | do |
| 95 | LastChar = getchar(); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 96 | while (LastChar != EOF && LastChar != '\n' && LastChar != '\r'); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 97 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 98 | if (LastChar != EOF) |
| 99 | return gettok(); |
| 100 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 101 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 102 | // Check for end of file. Don't eat the EOF. |
| 103 | if (LastChar == EOF) |
| 104 | return tok_eof; |
| 105 | |
| 106 | // Otherwise, just return the character as its ascii value. |
| 107 | int ThisChar = LastChar; |
| 108 | LastChar = getchar(); |
| 109 | return ThisChar; |
| 110 | } |
| 111 | |
| 112 | //===----------------------------------------------------------------------===// |
| 113 | // Abstract Syntax Tree (aka Parse Tree) |
| 114 | //===----------------------------------------------------------------------===// |
Juergen Ributzka | 05c5a93 | 2013-11-19 03:08:35 +0000 | [diff] [blame] | 115 | namespace { |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 116 | /// ExprAST - Base class for all expression nodes. |
| 117 | class ExprAST { |
| 118 | public: |
Juergen Ributzka | 05c5a93 | 2013-11-19 03:08:35 +0000 | [diff] [blame] | 119 | virtual ~ExprAST() {} |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 120 | virtual Value *Codegen() = 0; |
| 121 | }; |
| 122 | |
| 123 | /// NumberExprAST - Expression class for numeric literals like "1.0". |
| 124 | class NumberExprAST : public ExprAST { |
| 125 | double Val; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 126 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 127 | public: |
| 128 | NumberExprAST(double val) : Val(val) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 129 | Value *Codegen() override; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 130 | }; |
| 131 | |
| 132 | /// VariableExprAST - Expression class for referencing a variable, like "a". |
| 133 | class VariableExprAST : public ExprAST { |
| 134 | std::string Name; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 135 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 136 | public: |
| 137 | VariableExprAST(const std::string &name) : Name(name) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 138 | Value *Codegen() override; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 139 | }; |
| 140 | |
| 141 | /// BinaryExprAST - Expression class for a binary operator. |
| 142 | class BinaryExprAST : public ExprAST { |
| 143 | char Op; |
| 144 | ExprAST *LHS, *RHS; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 145 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 146 | public: |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 147 | BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs) |
| 148 | : Op(op), LHS(lhs), RHS(rhs) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 149 | Value *Codegen() override; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 150 | }; |
| 151 | |
| 152 | /// CallExprAST - Expression class for function calls. |
| 153 | class CallExprAST : public ExprAST { |
| 154 | std::string Callee; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 155 | std::vector<ExprAST *> Args; |
| 156 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 157 | public: |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 158 | CallExprAST(const std::string &callee, std::vector<ExprAST *> &args) |
| 159 | : Callee(callee), Args(args) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 160 | Value *Codegen() override; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 161 | }; |
| 162 | |
| 163 | /// IfExprAST - Expression class for if/then/else. |
| 164 | class IfExprAST : public ExprAST { |
| 165 | ExprAST *Cond, *Then, *Else; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 166 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 167 | public: |
| 168 | IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else) |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 169 | : Cond(cond), Then(then), Else(_else) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 170 | Value *Codegen() override; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 171 | }; |
| 172 | |
| 173 | /// ForExprAST - Expression class for for/in. |
| 174 | class ForExprAST : public ExprAST { |
| 175 | std::string VarName; |
| 176 | ExprAST *Start, *End, *Step, *Body; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 177 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 178 | public: |
| 179 | ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end, |
| 180 | ExprAST *step, ExprAST *body) |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 181 | : VarName(varname), Start(start), End(end), Step(step), Body(body) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 182 | Value *Codegen() override; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 183 | }; |
| 184 | |
| 185 | /// PrototypeAST - This class represents the "prototype" for a function, |
| 186 | /// which captures its name, and its argument names (thus implicitly the number |
| 187 | /// of arguments the function takes). |
| 188 | class PrototypeAST { |
| 189 | std::string Name; |
| 190 | std::vector<std::string> Args; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 191 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 192 | public: |
| 193 | PrototypeAST(const std::string &name, const std::vector<std::string> &args) |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 194 | : Name(name), Args(args) {} |
| 195 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 196 | Function *Codegen(); |
| 197 | }; |
| 198 | |
| 199 | /// FunctionAST - This class represents a function definition itself. |
| 200 | class FunctionAST { |
| 201 | PrototypeAST *Proto; |
| 202 | ExprAST *Body; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 203 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 204 | public: |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 205 | FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {} |
| 206 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 207 | Function *Codegen(); |
| 208 | }; |
Juergen Ributzka | 05c5a93 | 2013-11-19 03:08:35 +0000 | [diff] [blame] | 209 | } // end anonymous namespace |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 210 | |
| 211 | //===----------------------------------------------------------------------===// |
| 212 | // Parser |
| 213 | //===----------------------------------------------------------------------===// |
| 214 | |
| 215 | /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current |
| 216 | /// token the parser is looking at. getNextToken reads another token from the |
| 217 | /// lexer and updates CurTok with its results. |
| 218 | static int CurTok; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 219 | static int getNextToken() { return CurTok = gettok(); } |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 220 | |
| 221 | /// BinopPrecedence - This holds the precedence for each binary operator that is |
| 222 | /// defined. |
| 223 | static std::map<char, int> BinopPrecedence; |
| 224 | |
| 225 | /// GetTokPrecedence - Get the precedence of the pending binary operator token. |
| 226 | static int GetTokPrecedence() { |
| 227 | if (!isascii(CurTok)) |
| 228 | return -1; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 229 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 230 | // Make sure it's a declared binop. |
| 231 | int TokPrec = BinopPrecedence[CurTok]; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 232 | if (TokPrec <= 0) |
| 233 | return -1; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 234 | return TokPrec; |
| 235 | } |
| 236 | |
| 237 | /// Error* - These are little helper functions for error handling. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 238 | ExprAST *Error(const char *Str) { |
| 239 | fprintf(stderr, "Error: %s\n", Str); |
| 240 | return 0; |
| 241 | } |
| 242 | PrototypeAST *ErrorP(const char *Str) { |
| 243 | Error(Str); |
| 244 | return 0; |
| 245 | } |
| 246 | FunctionAST *ErrorF(const char *Str) { |
| 247 | Error(Str); |
| 248 | return 0; |
| 249 | } |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 250 | |
| 251 | static ExprAST *ParseExpression(); |
| 252 | |
| 253 | /// identifierexpr |
| 254 | /// ::= identifier |
| 255 | /// ::= identifier '(' expression* ')' |
| 256 | static ExprAST *ParseIdentifierExpr() { |
| 257 | std::string IdName = IdentifierStr; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 258 | |
| 259 | getNextToken(); // eat identifier. |
| 260 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 261 | if (CurTok != '(') // Simple variable ref. |
| 262 | return new VariableExprAST(IdName); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 263 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 264 | // Call. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 265 | getNextToken(); // eat ( |
| 266 | std::vector<ExprAST *> Args; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 267 | if (CurTok != ')') { |
| 268 | while (1) { |
| 269 | ExprAST *Arg = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 270 | if (!Arg) |
| 271 | return 0; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 272 | Args.push_back(Arg); |
| 273 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 274 | if (CurTok == ')') |
| 275 | break; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 276 | |
| 277 | if (CurTok != ',') |
| 278 | return Error("Expected ')' or ',' in argument list"); |
| 279 | getNextToken(); |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | // Eat the ')'. |
| 284 | getNextToken(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 285 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 286 | return new CallExprAST(IdName, Args); |
| 287 | } |
| 288 | |
| 289 | /// numberexpr ::= number |
| 290 | static ExprAST *ParseNumberExpr() { |
| 291 | ExprAST *Result = new NumberExprAST(NumVal); |
| 292 | getNextToken(); // consume the number |
| 293 | return Result; |
| 294 | } |
| 295 | |
| 296 | /// parenexpr ::= '(' expression ')' |
| 297 | static ExprAST *ParseParenExpr() { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 298 | getNextToken(); // eat (. |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 299 | ExprAST *V = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 300 | if (!V) |
| 301 | return 0; |
| 302 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 303 | if (CurTok != ')') |
| 304 | return Error("expected ')'"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 305 | getNextToken(); // eat ). |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 306 | return V; |
| 307 | } |
| 308 | |
| 309 | /// ifexpr ::= 'if' expression 'then' expression 'else' expression |
| 310 | static ExprAST *ParseIfExpr() { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 311 | getNextToken(); // eat the if. |
| 312 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 313 | // condition. |
| 314 | ExprAST *Cond = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 315 | if (!Cond) |
| 316 | return 0; |
| 317 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 318 | if (CurTok != tok_then) |
| 319 | return Error("expected then"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 320 | getNextToken(); // eat the then |
| 321 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 322 | ExprAST *Then = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 323 | if (Then == 0) |
| 324 | return 0; |
| 325 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 326 | if (CurTok != tok_else) |
| 327 | return Error("expected else"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 328 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 329 | getNextToken(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 330 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 331 | ExprAST *Else = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 332 | if (!Else) |
| 333 | return 0; |
| 334 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 335 | return new IfExprAST(Cond, Then, Else); |
| 336 | } |
| 337 | |
| 338 | /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression |
| 339 | static ExprAST *ParseForExpr() { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 340 | getNextToken(); // eat the for. |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 341 | |
| 342 | if (CurTok != tok_identifier) |
| 343 | return Error("expected identifier after for"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 344 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 345 | std::string IdName = IdentifierStr; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 346 | getNextToken(); // eat identifier. |
| 347 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 348 | if (CurTok != '=') |
| 349 | return Error("expected '=' after for"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 350 | getNextToken(); // eat '='. |
| 351 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 352 | ExprAST *Start = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 353 | if (Start == 0) |
| 354 | return 0; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 355 | if (CurTok != ',') |
| 356 | return Error("expected ',' after for start value"); |
| 357 | getNextToken(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 358 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 359 | ExprAST *End = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 360 | if (End == 0) |
| 361 | return 0; |
| 362 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 363 | // The step value is optional. |
| 364 | ExprAST *Step = 0; |
| 365 | if (CurTok == ',') { |
| 366 | getNextToken(); |
| 367 | Step = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 368 | if (Step == 0) |
| 369 | return 0; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 370 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 371 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 372 | if (CurTok != tok_in) |
| 373 | return Error("expected 'in' after for"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 374 | getNextToken(); // eat 'in'. |
| 375 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 376 | ExprAST *Body = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 377 | if (Body == 0) |
| 378 | return 0; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 379 | |
| 380 | return new ForExprAST(IdName, Start, End, Step, Body); |
| 381 | } |
| 382 | |
| 383 | /// primary |
| 384 | /// ::= identifierexpr |
| 385 | /// ::= numberexpr |
| 386 | /// ::= parenexpr |
| 387 | /// ::= ifexpr |
| 388 | /// ::= forexpr |
| 389 | static ExprAST *ParsePrimary() { |
| 390 | switch (CurTok) { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 391 | default: |
| 392 | return Error("unknown token when expecting an expression"); |
| 393 | case tok_identifier: |
| 394 | return ParseIdentifierExpr(); |
| 395 | case tok_number: |
| 396 | return ParseNumberExpr(); |
| 397 | case '(': |
| 398 | return ParseParenExpr(); |
| 399 | case tok_if: |
| 400 | return ParseIfExpr(); |
| 401 | case tok_for: |
| 402 | return ParseForExpr(); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 403 | } |
| 404 | } |
| 405 | |
| 406 | /// binoprhs |
| 407 | /// ::= ('+' primary)* |
| 408 | static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) { |
| 409 | // If this is a binop, find its precedence. |
| 410 | while (1) { |
| 411 | int TokPrec = GetTokPrecedence(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 412 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 413 | // If this is a binop that binds at least as tightly as the current binop, |
| 414 | // consume it, otherwise we are done. |
| 415 | if (TokPrec < ExprPrec) |
| 416 | return LHS; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 417 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 418 | // Okay, we know this is a binop. |
| 419 | int BinOp = CurTok; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 420 | getNextToken(); // eat binop |
| 421 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 422 | // Parse the primary expression after the binary operator. |
| 423 | ExprAST *RHS = ParsePrimary(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 424 | if (!RHS) |
| 425 | return 0; |
| 426 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 427 | // If BinOp binds less tightly with RHS than the operator after RHS, let |
| 428 | // the pending operator take RHS as its LHS. |
| 429 | int NextPrec = GetTokPrecedence(); |
| 430 | if (TokPrec < NextPrec) { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 431 | RHS = ParseBinOpRHS(TokPrec + 1, RHS); |
| 432 | if (RHS == 0) |
| 433 | return 0; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 434 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 435 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 436 | // Merge LHS/RHS. |
| 437 | LHS = new BinaryExprAST(BinOp, LHS, RHS); |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | /// expression |
| 442 | /// ::= primary binoprhs |
| 443 | /// |
| 444 | static ExprAST *ParseExpression() { |
| 445 | ExprAST *LHS = ParsePrimary(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 446 | if (!LHS) |
| 447 | return 0; |
| 448 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 449 | return ParseBinOpRHS(0, LHS); |
| 450 | } |
| 451 | |
| 452 | /// prototype |
| 453 | /// ::= id '(' id* ')' |
| 454 | static PrototypeAST *ParsePrototype() { |
| 455 | if (CurTok != tok_identifier) |
| 456 | return ErrorP("Expected function name in prototype"); |
| 457 | |
| 458 | std::string FnName = IdentifierStr; |
| 459 | getNextToken(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 460 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 461 | if (CurTok != '(') |
| 462 | return ErrorP("Expected '(' in prototype"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 463 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 464 | std::vector<std::string> ArgNames; |
| 465 | while (getNextToken() == tok_identifier) |
| 466 | ArgNames.push_back(IdentifierStr); |
| 467 | if (CurTok != ')') |
| 468 | return ErrorP("Expected ')' in prototype"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 469 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 470 | // success. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 471 | getNextToken(); // eat ')'. |
| 472 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 473 | return new PrototypeAST(FnName, ArgNames); |
| 474 | } |
| 475 | |
| 476 | /// definition ::= 'def' prototype expression |
| 477 | static FunctionAST *ParseDefinition() { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 478 | getNextToken(); // eat def. |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 479 | PrototypeAST *Proto = ParsePrototype(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 480 | if (Proto == 0) |
| 481 | return 0; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 482 | |
| 483 | if (ExprAST *E = ParseExpression()) |
| 484 | return new FunctionAST(Proto, E); |
| 485 | return 0; |
| 486 | } |
| 487 | |
| 488 | /// toplevelexpr ::= expression |
| 489 | static FunctionAST *ParseTopLevelExpr() { |
| 490 | if (ExprAST *E = ParseExpression()) { |
| 491 | // Make an anonymous proto. |
| 492 | PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>()); |
| 493 | return new FunctionAST(Proto, E); |
| 494 | } |
| 495 | return 0; |
| 496 | } |
| 497 | |
| 498 | /// external ::= 'extern' prototype |
| 499 | static PrototypeAST *ParseExtern() { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 500 | getNextToken(); // eat extern. |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 501 | return ParsePrototype(); |
| 502 | } |
| 503 | |
| 504 | //===----------------------------------------------------------------------===// |
| 505 | // Code Generation |
| 506 | //===----------------------------------------------------------------------===// |
| 507 | |
| 508 | static Module *TheModule; |
| 509 | static IRBuilder<> Builder(getGlobalContext()); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 510 | static std::map<std::string, Value *> NamedValues; |
Chandler Carruth | 7ecd991 | 2015-02-13 10:21:05 +0000 | [diff] [blame] | 511 | static legacy::FunctionPassManager *TheFPM; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 512 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 513 | Value *ErrorV(const char *Str) { |
| 514 | Error(Str); |
| 515 | return 0; |
| 516 | } |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 517 | |
| 518 | Value *NumberExprAST::Codegen() { |
| 519 | return ConstantFP::get(getGlobalContext(), APFloat(Val)); |
| 520 | } |
| 521 | |
| 522 | Value *VariableExprAST::Codegen() { |
| 523 | // Look this variable up in the function. |
| 524 | Value *V = NamedValues[Name]; |
| 525 | return V ? V : ErrorV("Unknown variable name"); |
| 526 | } |
| 527 | |
| 528 | Value *BinaryExprAST::Codegen() { |
| 529 | Value *L = LHS->Codegen(); |
| 530 | Value *R = RHS->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 531 | if (L == 0 || R == 0) |
| 532 | return 0; |
| 533 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 534 | switch (Op) { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 535 | case '+': |
| 536 | return Builder.CreateFAdd(L, R, "addtmp"); |
| 537 | case '-': |
| 538 | return Builder.CreateFSub(L, R, "subtmp"); |
| 539 | case '*': |
| 540 | return Builder.CreateFMul(L, R, "multmp"); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 541 | case '<': |
| 542 | L = Builder.CreateFCmpULT(L, R, "cmptmp"); |
| 543 | // Convert bool 0/1 to double 0.0 or 1.0 |
| 544 | return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()), |
| 545 | "booltmp"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 546 | default: |
| 547 | return ErrorV("invalid binary operator"); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 548 | } |
| 549 | } |
| 550 | |
| 551 | Value *CallExprAST::Codegen() { |
| 552 | // Look up the name in the global module table. |
| 553 | Function *CalleeF = TheModule->getFunction(Callee); |
| 554 | if (CalleeF == 0) |
| 555 | return ErrorV("Unknown function referenced"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 556 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 557 | // If argument mismatch error. |
| 558 | if (CalleeF->arg_size() != Args.size()) |
| 559 | return ErrorV("Incorrect # arguments passed"); |
| 560 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 561 | std::vector<Value *> ArgsV; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 562 | for (unsigned i = 0, e = Args.size(); i != e; ++i) { |
| 563 | ArgsV.push_back(Args[i]->Codegen()); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 564 | if (ArgsV.back() == 0) |
| 565 | return 0; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 566 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 567 | |
Francois Pichet | c5d1050 | 2011-07-15 10:59:52 +0000 | [diff] [blame] | 568 | return Builder.CreateCall(CalleeF, ArgsV, "calltmp"); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 569 | } |
| 570 | |
| 571 | Value *IfExprAST::Codegen() { |
| 572 | Value *CondV = Cond->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 573 | if (CondV == 0) |
| 574 | return 0; |
| 575 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 576 | // Convert condition to a bool by comparing equal to 0.0. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 577 | CondV = Builder.CreateFCmpONE( |
| 578 | CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond"); |
| 579 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 580 | Function *TheFunction = Builder.GetInsertBlock()->getParent(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 581 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 582 | // Create blocks for the then and else cases. Insert the 'then' block at the |
| 583 | // end of the function. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 584 | BasicBlock *ThenBB = |
| 585 | BasicBlock::Create(getGlobalContext(), "then", TheFunction); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 586 | BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else"); |
| 587 | BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 588 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 589 | Builder.CreateCondBr(CondV, ThenBB, ElseBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 590 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 591 | // Emit then value. |
| 592 | Builder.SetInsertPoint(ThenBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 593 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 594 | Value *ThenV = Then->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 595 | if (ThenV == 0) |
| 596 | return 0; |
| 597 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 598 | Builder.CreateBr(MergeBB); |
| 599 | // Codegen of 'Then' can change the current block, update ThenBB for the PHI. |
| 600 | ThenBB = Builder.GetInsertBlock(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 601 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 602 | // Emit else block. |
| 603 | TheFunction->getBasicBlockList().push_back(ElseBB); |
| 604 | Builder.SetInsertPoint(ElseBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 605 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 606 | Value *ElseV = Else->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 607 | if (ElseV == 0) |
| 608 | return 0; |
| 609 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 610 | Builder.CreateBr(MergeBB); |
| 611 | // Codegen of 'Else' can change the current block, update ElseBB for the PHI. |
| 612 | ElseBB = Builder.GetInsertBlock(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 613 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 614 | // Emit merge block. |
| 615 | TheFunction->getBasicBlockList().push_back(MergeBB); |
| 616 | Builder.SetInsertPoint(MergeBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 617 | PHINode *PN = |
| 618 | Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp"); |
| 619 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 620 | PN->addIncoming(ThenV, ThenBB); |
| 621 | PN->addIncoming(ElseV, ElseBB); |
| 622 | return PN; |
| 623 | } |
| 624 | |
| 625 | Value *ForExprAST::Codegen() { |
| 626 | // Output this as: |
| 627 | // ... |
| 628 | // start = startexpr |
| 629 | // goto loop |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 630 | // loop: |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 631 | // variable = phi [start, loopheader], [nextvariable, loopend] |
| 632 | // ... |
| 633 | // bodyexpr |
| 634 | // ... |
| 635 | // loopend: |
| 636 | // step = stepexpr |
| 637 | // nextvariable = variable + step |
| 638 | // endcond = endexpr |
| 639 | // br endcond, loop, endloop |
| 640 | // outloop: |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 641 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 642 | // Emit the start code first, without 'variable' in scope. |
| 643 | Value *StartVal = Start->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 644 | if (StartVal == 0) |
| 645 | return 0; |
| 646 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 647 | // Make the new basic block for the loop header, inserting after current |
| 648 | // block. |
| 649 | Function *TheFunction = Builder.GetInsertBlock()->getParent(); |
| 650 | BasicBlock *PreheaderBB = Builder.GetInsertBlock(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 651 | BasicBlock *LoopBB = |
| 652 | BasicBlock::Create(getGlobalContext(), "loop", TheFunction); |
| 653 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 654 | // Insert an explicit fall through from the current block to the LoopBB. |
| 655 | Builder.CreateBr(LoopBB); |
| 656 | |
| 657 | // Start insertion in LoopBB. |
| 658 | Builder.SetInsertPoint(LoopBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 659 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 660 | // Start the PHI node with an entry for Start. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 661 | PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), |
| 662 | 2, VarName.c_str()); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 663 | Variable->addIncoming(StartVal, PreheaderBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 664 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 665 | // Within the loop, the variable is defined equal to the PHI node. If it |
| 666 | // shadows an existing variable, we have to restore it, so save it now. |
| 667 | Value *OldVal = NamedValues[VarName]; |
| 668 | NamedValues[VarName] = Variable; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 669 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 670 | // Emit the body of the loop. This, like any other expr, can change the |
| 671 | // current BB. Note that we ignore the value computed by the body, but don't |
| 672 | // allow an error. |
| 673 | if (Body->Codegen() == 0) |
| 674 | return 0; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 675 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 676 | // Emit the step value. |
| 677 | Value *StepVal; |
| 678 | if (Step) { |
| 679 | StepVal = Step->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 680 | if (StepVal == 0) |
| 681 | return 0; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 682 | } else { |
| 683 | // If not specified, use 1.0. |
| 684 | StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0)); |
| 685 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 686 | |
Chris Lattner | 26d7950 | 2010-06-21 22:51:14 +0000 | [diff] [blame] | 687 | Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar"); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 688 | |
| 689 | // Compute the end condition. |
| 690 | Value *EndCond = End->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 691 | if (EndCond == 0) |
| 692 | return EndCond; |
| 693 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 694 | // Convert condition to a bool by comparing equal to 0.0. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 695 | EndCond = Builder.CreateFCmpONE( |
| 696 | EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond"); |
| 697 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 698 | // Create the "after loop" block and insert it. |
| 699 | BasicBlock *LoopEndBB = Builder.GetInsertBlock(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 700 | BasicBlock *AfterBB = |
| 701 | BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction); |
| 702 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 703 | // Insert the conditional branch into the end of LoopEndBB. |
| 704 | Builder.CreateCondBr(EndCond, LoopBB, AfterBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 705 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 706 | // Any new code will be inserted in AfterBB. |
| 707 | Builder.SetInsertPoint(AfterBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 708 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 709 | // Add a new entry to the PHI node for the backedge. |
| 710 | Variable->addIncoming(NextVar, LoopEndBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 711 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 712 | // Restore the unshadowed variable. |
| 713 | if (OldVal) |
| 714 | NamedValues[VarName] = OldVal; |
| 715 | else |
| 716 | NamedValues.erase(VarName); |
| 717 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 718 | // for expr always returns 0.0. |
| 719 | return Constant::getNullValue(Type::getDoubleTy(getGlobalContext())); |
| 720 | } |
| 721 | |
| 722 | Function *PrototypeAST::Codegen() { |
| 723 | // Make the function type: double(double,double) etc. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 724 | std::vector<Type *> Doubles(Args.size(), |
| 725 | Type::getDoubleTy(getGlobalContext())); |
| 726 | FunctionType *FT = |
| 727 | FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false); |
| 728 | |
| 729 | Function *F = |
| 730 | Function::Create(FT, Function::ExternalLinkage, Name, TheModule); |
| 731 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 732 | // If F conflicted, there was already something named 'Name'. If it has a |
| 733 | // body, don't allow redefinition or reextern. |
| 734 | if (F->getName() != Name) { |
| 735 | // Delete the one we just made and get the existing one. |
| 736 | F->eraseFromParent(); |
| 737 | F = TheModule->getFunction(Name); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 738 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 739 | // If F already has a body, reject this. |
| 740 | if (!F->empty()) { |
| 741 | ErrorF("redefinition of function"); |
| 742 | return 0; |
| 743 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 744 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 745 | // If F took a different number of args, reject. |
| 746 | if (F->arg_size() != Args.size()) { |
| 747 | ErrorF("redefinition of function with different # args"); |
| 748 | return 0; |
| 749 | } |
| 750 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 751 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 752 | // Set names for all arguments. |
| 753 | unsigned Idx = 0; |
| 754 | for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size(); |
| 755 | ++AI, ++Idx) { |
| 756 | AI->setName(Args[Idx]); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 757 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 758 | // Add arguments to variable symbol table. |
| 759 | NamedValues[Args[Idx]] = AI; |
| 760 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 761 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 762 | return F; |
| 763 | } |
| 764 | |
| 765 | Function *FunctionAST::Codegen() { |
| 766 | NamedValues.clear(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 767 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 768 | Function *TheFunction = Proto->Codegen(); |
| 769 | if (TheFunction == 0) |
| 770 | return 0; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 771 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 772 | // Create a new basic block to start insertion into. |
| 773 | BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction); |
| 774 | Builder.SetInsertPoint(BB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 775 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 776 | if (Value *RetVal = Body->Codegen()) { |
| 777 | // Finish off the function. |
| 778 | Builder.CreateRet(RetVal); |
| 779 | |
| 780 | // Validate the generated code, checking for consistency. |
| 781 | verifyFunction(*TheFunction); |
| 782 | |
| 783 | // Optimize the function. |
| 784 | TheFPM->run(*TheFunction); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 785 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 786 | return TheFunction; |
| 787 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 788 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 789 | // Error reading body, remove function. |
| 790 | TheFunction->eraseFromParent(); |
| 791 | return 0; |
| 792 | } |
| 793 | |
| 794 | //===----------------------------------------------------------------------===// |
| 795 | // Top-Level parsing and JIT Driver |
| 796 | //===----------------------------------------------------------------------===// |
| 797 | |
| 798 | static ExecutionEngine *TheExecutionEngine; |
| 799 | |
| 800 | static void HandleDefinition() { |
| 801 | if (FunctionAST *F = ParseDefinition()) { |
| 802 | if (Function *LF = F->Codegen()) { |
| 803 | fprintf(stderr, "Read function definition:"); |
| 804 | LF->dump(); |
| 805 | } |
| 806 | } else { |
| 807 | // Skip token for error recovery. |
| 808 | getNextToken(); |
| 809 | } |
| 810 | } |
| 811 | |
| 812 | static void HandleExtern() { |
| 813 | if (PrototypeAST *P = ParseExtern()) { |
| 814 | if (Function *F = P->Codegen()) { |
| 815 | fprintf(stderr, "Read extern: "); |
| 816 | F->dump(); |
| 817 | } |
| 818 | } else { |
| 819 | // Skip token for error recovery. |
| 820 | getNextToken(); |
| 821 | } |
| 822 | } |
| 823 | |
| 824 | static void HandleTopLevelExpression() { |
| 825 | // Evaluate a top-level expression into an anonymous function. |
| 826 | if (FunctionAST *F = ParseTopLevelExpr()) { |
| 827 | if (Function *LF = F->Codegen()) { |
Eric Christopher | 1b74b65 | 2014-12-08 18:00:38 +0000 | [diff] [blame] | 828 | TheExecutionEngine->finalizeObject(); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 829 | // JIT the function, returning a function pointer. |
| 830 | void *FPtr = TheExecutionEngine->getPointerToFunction(LF); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 831 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 832 | // Cast it to the right type (takes no arguments, returns a double) so we |
| 833 | // can call it as a native function. |
| 834 | double (*FP)() = (double (*)())(intptr_t)FPtr; |
| 835 | fprintf(stderr, "Evaluated to %f\n", FP()); |
| 836 | } |
| 837 | } else { |
| 838 | // Skip token for error recovery. |
| 839 | getNextToken(); |
| 840 | } |
| 841 | } |
| 842 | |
| 843 | /// top ::= definition | external | expression | ';' |
| 844 | static void MainLoop() { |
| 845 | while (1) { |
| 846 | fprintf(stderr, "ready> "); |
| 847 | switch (CurTok) { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 848 | case tok_eof: |
| 849 | return; |
| 850 | case ';': |
| 851 | getNextToken(); |
| 852 | break; // ignore top-level semicolons. |
| 853 | case tok_def: |
| 854 | HandleDefinition(); |
| 855 | break; |
| 856 | case tok_extern: |
| 857 | HandleExtern(); |
| 858 | break; |
| 859 | default: |
| 860 | HandleTopLevelExpression(); |
| 861 | break; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 862 | } |
| 863 | } |
| 864 | } |
| 865 | |
| 866 | //===----------------------------------------------------------------------===// |
| 867 | // "Library" functions that can be "extern'd" from user code. |
| 868 | //===----------------------------------------------------------------------===// |
| 869 | |
| 870 | /// putchard - putchar that takes a double and returns 0. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 871 | extern "C" double putchard(double X) { |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 872 | putchar((char)X); |
| 873 | return 0; |
| 874 | } |
| 875 | |
| 876 | //===----------------------------------------------------------------------===// |
| 877 | // Main driver code. |
| 878 | //===----------------------------------------------------------------------===// |
| 879 | |
| 880 | int main() { |
| 881 | InitializeNativeTarget(); |
Eric Christopher | 1b74b65 | 2014-12-08 18:00:38 +0000 | [diff] [blame] | 882 | InitializeNativeTargetAsmPrinter(); |
| 883 | InitializeNativeTargetAsmParser(); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 884 | LLVMContext &Context = getGlobalContext(); |
| 885 | |
| 886 | // Install standard binary operators. |
| 887 | // 1 is lowest precedence. |
| 888 | BinopPrecedence['<'] = 10; |
| 889 | BinopPrecedence['+'] = 20; |
| 890 | BinopPrecedence['-'] = 20; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 891 | BinopPrecedence['*'] = 40; // highest. |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 892 | |
| 893 | // Prime the first token. |
| 894 | fprintf(stderr, "ready> "); |
| 895 | getNextToken(); |
| 896 | |
| 897 | // Make the module, which holds all the code. |
Rafael Espindola | 2a8a279 | 2014-08-19 04:04:25 +0000 | [diff] [blame] | 898 | std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context); |
| 899 | TheModule = Owner.get(); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 900 | |
Jeffrey Yasskin | 091217b | 2010-01-27 20:34:15 +0000 | [diff] [blame] | 901 | // Create the JIT. This takes ownership of the module. |
Jeffrey Yasskin | 8a30324 | 2010-02-11 19:15:20 +0000 | [diff] [blame] | 902 | std::string ErrStr; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 903 | TheExecutionEngine = |
| 904 | EngineBuilder(std::move(Owner)) |
| 905 | .setErrorStr(&ErrStr) |
| 906 | .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>()) |
| 907 | .create(); |
Jeffrey Yasskin | 8a30324 | 2010-02-11 19:15:20 +0000 | [diff] [blame] | 908 | if (!TheExecutionEngine) { |
| 909 | fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str()); |
| 910 | exit(1); |
| 911 | } |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 912 | |
Chandler Carruth | 7ecd991 | 2015-02-13 10:21:05 +0000 | [diff] [blame] | 913 | legacy::FunctionPassManager OurFPM(TheModule); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 914 | |
| 915 | // Set up the optimizer pipeline. Start with registering info about how the |
| 916 | // target lays out data structures. |
Mehdi Amini | cd253da | 2015-07-16 16:47:18 +0000 | [diff] [blame] | 917 | TheModule->setDataLayout(TheExecutionEngine->getDataLayout()); |
Dan Gohman | 56f3a4c | 2010-11-15 18:41:10 +0000 | [diff] [blame] | 918 | // Provide basic AliasAnalysis support for GVN. |
| 919 | OurFPM.add(createBasicAliasAnalysisPass()); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 920 | // Do simple "peephole" optimizations and bit-twiddling optzns. |
| 921 | OurFPM.add(createInstructionCombiningPass()); |
| 922 | // Reassociate expressions. |
| 923 | OurFPM.add(createReassociatePass()); |
| 924 | // Eliminate Common SubExpressions. |
| 925 | OurFPM.add(createGVNPass()); |
| 926 | // Simplify the control flow graph (deleting unreachable blocks, etc). |
| 927 | OurFPM.add(createCFGSimplificationPass()); |
| 928 | |
| 929 | OurFPM.doInitialization(); |
| 930 | |
| 931 | // Set the global so the code gen can use this. |
| 932 | TheFPM = &OurFPM; |
| 933 | |
| 934 | // Run the main "interpreter loop" now. |
| 935 | MainLoop(); |
| 936 | |
| 937 | TheFPM = 0; |
| 938 | |
| 939 | // Print out all of the generated code. |
| 940 | TheModule->dump(); |
| 941 | |
| 942 | return 0; |
| 943 | } |