blob: a565e52e2eb414c898c7b1b02a0a42239905c56a [file] [log] [blame]
NAKAMURA Takumi85c9bac2015-03-02 01:04:34 +00001#include "llvm/ADT/STLExtras.h"
Eric Christopher05917fa2014-12-08 18:00:47 +00002#include "llvm/ADT/Triple.h"
3#include "llvm/Analysis/Passes.h"
4#include "llvm/ExecutionEngine/ExecutionEngine.h"
5#include "llvm/ExecutionEngine/MCJIT.h"
6#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth1f832f72015-02-13 09:14:30 +00007#include "llvm/IR/DIBuilder.h"
Eric Christopher05917fa2014-12-08 18:00:47 +00008#include "llvm/IR/DataLayout.h"
9#include "llvm/IR/DerivedTypes.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000010#include "llvm/IR/IRBuilder.h"
11#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000012#include "llvm/IR/LegacyPassManager.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000013#include "llvm/IR/Module.h"
14#include "llvm/IR/Verifier.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000015#include "llvm/Support/Host.h"
16#include "llvm/Support/TargetSelect.h"
17#include "llvm/Transforms/Scalar.h"
18#include <cctype>
19#include <cstdio>
Chandler Carruth1f832f72015-02-13 09:14:30 +000020#include <iostream>
Eric Christopher05917fa2014-12-08 18:00:47 +000021#include <map>
22#include <string>
23#include <vector>
Eric Christopher05917fa2014-12-08 18:00:47 +000024using namespace llvm;
25
26//===----------------------------------------------------------------------===//
27// Lexer
28//===----------------------------------------------------------------------===//
29
30// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
31// of these for known things.
32enum Token {
33 tok_eof = -1,
34
35 // commands
36 tok_def = -2,
37 tok_extern = -3,
38
39 // primary
40 tok_identifier = -4,
41 tok_number = -5,
42
43 // control
44 tok_if = -6,
45 tok_then = -7,
46 tok_else = -8,
47 tok_for = -9,
48 tok_in = -10,
49
50 // operators
51 tok_binary = -11,
52 tok_unary = -12,
53
54 // var definition
55 tok_var = -13
56};
57
58std::string getTokName(int Tok) {
59 switch (Tok) {
60 case tok_eof:
61 return "eof";
62 case tok_def:
63 return "def";
64 case tok_extern:
65 return "extern";
66 case tok_identifier:
67 return "identifier";
68 case tok_number:
69 return "number";
70 case tok_if:
71 return "if";
72 case tok_then:
73 return "then";
74 case tok_else:
75 return "else";
76 case tok_for:
77 return "for";
78 case tok_in:
79 return "in";
80 case tok_binary:
81 return "binary";
82 case tok_unary:
83 return "unary";
84 case tok_var:
85 return "var";
86 }
87 return std::string(1, (char)Tok);
88}
89
90namespace {
91class PrototypeAST;
92class ExprAST;
93}
94static IRBuilder<> Builder(getGlobalContext());
95struct DebugInfo {
Duncan P. N. Exon Smithbe9e4fe2015-04-20 18:32:29 +000096 MDCompileUnit *TheCU;
97 MDType *DblTy;
98 std::vector<MDScope *> LexicalBlocks;
99 std::map<const PrototypeAST *, MDScope *> FnScopeMap;
Eric Christopher05917fa2014-12-08 18:00:47 +0000100
101 void emitLocation(ExprAST *AST);
Duncan P. N. Exon Smithbe9e4fe2015-04-20 18:32:29 +0000102 MDType *getDoubleTy();
Eric Christopher05917fa2014-12-08 18:00:47 +0000103} KSDbgInfo;
104
105static std::string IdentifierStr; // Filled in if tok_identifier
106static double NumVal; // Filled in if tok_number
107struct SourceLocation {
108 int Line;
109 int Col;
110};
111static SourceLocation CurLoc;
112static SourceLocation LexLoc = { 1, 0 };
113
114static int advance() {
115 int LastChar = getchar();
116
117 if (LastChar == '\n' || LastChar == '\r') {
118 LexLoc.Line++;
119 LexLoc.Col = 0;
120 } else
121 LexLoc.Col++;
122 return LastChar;
123}
124
125/// gettok - Return the next token from standard input.
126static int gettok() {
127 static int LastChar = ' ';
128
129 // Skip any whitespace.
130 while (isspace(LastChar))
131 LastChar = advance();
132
133 CurLoc = LexLoc;
134
135 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
136 IdentifierStr = LastChar;
137 while (isalnum((LastChar = advance())))
138 IdentifierStr += LastChar;
139
140 if (IdentifierStr == "def")
141 return tok_def;
142 if (IdentifierStr == "extern")
143 return tok_extern;
144 if (IdentifierStr == "if")
145 return tok_if;
146 if (IdentifierStr == "then")
147 return tok_then;
148 if (IdentifierStr == "else")
149 return tok_else;
150 if (IdentifierStr == "for")
151 return tok_for;
152 if (IdentifierStr == "in")
153 return tok_in;
154 if (IdentifierStr == "binary")
155 return tok_binary;
156 if (IdentifierStr == "unary")
157 return tok_unary;
158 if (IdentifierStr == "var")
159 return tok_var;
160 return tok_identifier;
161 }
162
163 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
164 std::string NumStr;
165 do {
166 NumStr += LastChar;
167 LastChar = advance();
168 } while (isdigit(LastChar) || LastChar == '.');
169
170 NumVal = strtod(NumStr.c_str(), 0);
171 return tok_number;
172 }
173
174 if (LastChar == '#') {
175 // Comment until end of line.
176 do
177 LastChar = advance();
178 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
179
180 if (LastChar != EOF)
181 return gettok();
182 }
183
184 // Check for end of file. Don't eat the EOF.
185 if (LastChar == EOF)
186 return tok_eof;
187
188 // Otherwise, just return the character as its ascii value.
189 int ThisChar = LastChar;
190 LastChar = advance();
191 return ThisChar;
192}
193
194//===----------------------------------------------------------------------===//
195// Abstract Syntax Tree (aka Parse Tree)
196//===----------------------------------------------------------------------===//
197namespace {
198
199std::ostream &indent(std::ostream &O, int size) {
200 return O << std::string(size, ' ');
201}
202
203/// ExprAST - Base class for all expression nodes.
204class ExprAST {
205 SourceLocation Loc;
206
207public:
208 int getLine() const { return Loc.Line; }
209 int getCol() const { return Loc.Col; }
210 ExprAST(SourceLocation Loc = CurLoc) : Loc(Loc) {}
211 virtual std::ostream &dump(std::ostream &out, int ind) {
212 return out << ':' << getLine() << ':' << getCol() << '\n';
213 }
214 virtual ~ExprAST() {}
215 virtual Value *Codegen() = 0;
216};
217
218/// NumberExprAST - Expression class for numeric literals like "1.0".
219class NumberExprAST : public ExprAST {
220 double Val;
221
222public:
223 NumberExprAST(double val) : Val(val) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000224 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000225 return ExprAST::dump(out << Val, ind);
226 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000227 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000228};
229
230/// VariableExprAST - Expression class for referencing a variable, like "a".
231class VariableExprAST : public ExprAST {
232 std::string Name;
233
234public:
235 VariableExprAST(SourceLocation Loc, const std::string &name)
236 : ExprAST(Loc), Name(name) {}
237 const std::string &getName() const { return Name; }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000238 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000239 return ExprAST::dump(out << Name, ind);
240 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000241 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000242};
243
244/// UnaryExprAST - Expression class for a unary operator.
245class UnaryExprAST : public ExprAST {
246 char Opcode;
247 ExprAST *Operand;
248
249public:
250 UnaryExprAST(char opcode, ExprAST *operand)
251 : Opcode(opcode), Operand(operand) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000252 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000253 ExprAST::dump(out << "unary" << Opcode, ind);
254 Operand->dump(out, ind + 1);
255 return out;
256 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000257 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000258};
259
260/// BinaryExprAST - Expression class for a binary operator.
261class BinaryExprAST : public ExprAST {
262 char Op;
263 ExprAST *LHS, *RHS;
264
265public:
266 BinaryExprAST(SourceLocation Loc, char op, ExprAST *lhs, ExprAST *rhs)
267 : ExprAST(Loc), Op(op), LHS(lhs), RHS(rhs) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000268 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000269 ExprAST::dump(out << "binary" << Op, ind);
270 LHS->dump(indent(out, ind) << "LHS:", ind + 1);
271 RHS->dump(indent(out, ind) << "RHS:", ind + 1);
272 return out;
273 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000274 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000275};
276
277/// CallExprAST - Expression class for function calls.
278class CallExprAST : public ExprAST {
279 std::string Callee;
280 std::vector<ExprAST *> Args;
281
282public:
283 CallExprAST(SourceLocation Loc, const std::string &callee,
284 std::vector<ExprAST *> &args)
285 : ExprAST(Loc), Callee(callee), Args(args) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000286 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000287 ExprAST::dump(out << "call " << Callee, ind);
288 for (ExprAST *Arg : Args)
289 Arg->dump(indent(out, ind + 1), ind + 1);
290 return out;
291 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000292 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000293};
294
295/// IfExprAST - Expression class for if/then/else.
296class IfExprAST : public ExprAST {
297 ExprAST *Cond, *Then, *Else;
298
299public:
300 IfExprAST(SourceLocation Loc, ExprAST *cond, ExprAST *then, ExprAST *_else)
301 : ExprAST(Loc), Cond(cond), Then(then), Else(_else) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000302 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000303 ExprAST::dump(out << "if", ind);
304 Cond->dump(indent(out, ind) << "Cond:", ind + 1);
305 Then->dump(indent(out, ind) << "Then:", ind + 1);
306 Else->dump(indent(out, ind) << "Else:", ind + 1);
307 return out;
308 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000309 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000310};
311
312/// ForExprAST - Expression class for for/in.
313class ForExprAST : public ExprAST {
314 std::string VarName;
315 ExprAST *Start, *End, *Step, *Body;
316
317public:
318 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
319 ExprAST *step, ExprAST *body)
320 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000321 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000322 ExprAST::dump(out << "for", ind);
323 Start->dump(indent(out, ind) << "Cond:", ind + 1);
324 End->dump(indent(out, ind) << "End:", ind + 1);
325 Step->dump(indent(out, ind) << "Step:", ind + 1);
326 Body->dump(indent(out, ind) << "Body:", ind + 1);
327 return out;
328 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000329 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000330};
331
332/// VarExprAST - Expression class for var/in
333class VarExprAST : public ExprAST {
334 std::vector<std::pair<std::string, ExprAST *> > VarNames;
335 ExprAST *Body;
336
337public:
338 VarExprAST(const std::vector<std::pair<std::string, ExprAST *> > &varnames,
339 ExprAST *body)
340 : VarNames(varnames), Body(body) {}
341
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000342 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000343 ExprAST::dump(out << "var", ind);
344 for (const auto &NamedVar : VarNames)
345 NamedVar.second->dump(indent(out, ind) << NamedVar.first << ':', ind + 1);
346 Body->dump(indent(out, ind) << "Body:", ind + 1);
347 return out;
348 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000349 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000350};
351
352/// PrototypeAST - This class represents the "prototype" for a function,
353/// which captures its argument names as well as if it is an operator.
354class PrototypeAST {
355 std::string Name;
356 std::vector<std::string> Args;
357 bool isOperator;
358 unsigned Precedence; // Precedence if a binary op.
359 int Line;
360
361public:
362 PrototypeAST(SourceLocation Loc, const std::string &name,
363 const std::vector<std::string> &args, bool isoperator = false,
364 unsigned prec = 0)
365 : Name(name), Args(args), isOperator(isoperator), Precedence(prec),
366 Line(Loc.Line) {}
367
368 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
369 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
370
371 char getOperatorName() const {
372 assert(isUnaryOp() || isBinaryOp());
373 return Name[Name.size() - 1];
374 }
375
376 unsigned getBinaryPrecedence() const { return Precedence; }
377
378 Function *Codegen();
379
380 void CreateArgumentAllocas(Function *F);
381 const std::vector<std::string> &getArgs() const { return Args; }
382};
383
384/// FunctionAST - This class represents a function definition itself.
385class FunctionAST {
386 PrototypeAST *Proto;
387 ExprAST *Body;
388
389public:
390 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
391
392 std::ostream &dump(std::ostream &out, int ind) {
393 indent(out, ind) << "FunctionAST\n";
394 ++ind;
395 indent(out, ind) << "Body:";
396 return Body ? Body->dump(out, ind) : out << "null\n";
397 }
398
399 Function *Codegen();
400};
401} // end anonymous namespace
402
403//===----------------------------------------------------------------------===//
404// Parser
405//===----------------------------------------------------------------------===//
406
407/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
408/// token the parser is looking at. getNextToken reads another token from the
409/// lexer and updates CurTok with its results.
410static int CurTok;
411static int getNextToken() { return CurTok = gettok(); }
412
413/// BinopPrecedence - This holds the precedence for each binary operator that is
414/// defined.
415static std::map<char, int> BinopPrecedence;
416
417/// GetTokPrecedence - Get the precedence of the pending binary operator token.
418static int GetTokPrecedence() {
419 if (!isascii(CurTok))
420 return -1;
421
422 // Make sure it's a declared binop.
423 int TokPrec = BinopPrecedence[CurTok];
424 if (TokPrec <= 0)
425 return -1;
426 return TokPrec;
427}
428
429/// Error* - These are little helper functions for error handling.
430ExprAST *Error(const char *Str) {
431 fprintf(stderr, "Error: %s\n", Str);
432 return 0;
433}
434PrototypeAST *ErrorP(const char *Str) {
435 Error(Str);
436 return 0;
437}
438FunctionAST *ErrorF(const char *Str) {
439 Error(Str);
440 return 0;
441}
442
443static ExprAST *ParseExpression();
444
445/// identifierexpr
446/// ::= identifier
447/// ::= identifier '(' expression* ')'
448static ExprAST *ParseIdentifierExpr() {
449 std::string IdName = IdentifierStr;
450
451 SourceLocation LitLoc = CurLoc;
452
453 getNextToken(); // eat identifier.
454
455 if (CurTok != '(') // Simple variable ref.
456 return new VariableExprAST(LitLoc, IdName);
457
458 // Call.
459 getNextToken(); // eat (
460 std::vector<ExprAST *> Args;
461 if (CurTok != ')') {
462 while (1) {
463 ExprAST *Arg = ParseExpression();
464 if (!Arg)
465 return 0;
466 Args.push_back(Arg);
467
468 if (CurTok == ')')
469 break;
470
471 if (CurTok != ',')
472 return Error("Expected ')' or ',' in argument list");
473 getNextToken();
474 }
475 }
476
477 // Eat the ')'.
478 getNextToken();
479
480 return new CallExprAST(LitLoc, IdName, Args);
481}
482
483/// numberexpr ::= number
484static ExprAST *ParseNumberExpr() {
485 ExprAST *Result = new NumberExprAST(NumVal);
486 getNextToken(); // consume the number
487 return Result;
488}
489
490/// parenexpr ::= '(' expression ')'
491static ExprAST *ParseParenExpr() {
492 getNextToken(); // eat (.
493 ExprAST *V = ParseExpression();
494 if (!V)
495 return 0;
496
497 if (CurTok != ')')
498 return Error("expected ')'");
499 getNextToken(); // eat ).
500 return V;
501}
502
503/// ifexpr ::= 'if' expression 'then' expression 'else' expression
504static ExprAST *ParseIfExpr() {
505 SourceLocation IfLoc = CurLoc;
506
507 getNextToken(); // eat the if.
508
509 // condition.
510 ExprAST *Cond = ParseExpression();
511 if (!Cond)
512 return 0;
513
514 if (CurTok != tok_then)
515 return Error("expected then");
516 getNextToken(); // eat the then
517
518 ExprAST *Then = ParseExpression();
519 if (Then == 0)
520 return 0;
521
522 if (CurTok != tok_else)
523 return Error("expected else");
524
525 getNextToken();
526
527 ExprAST *Else = ParseExpression();
528 if (!Else)
529 return 0;
530
531 return new IfExprAST(IfLoc, Cond, Then, Else);
532}
533
534/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
535static ExprAST *ParseForExpr() {
536 getNextToken(); // eat the for.
537
538 if (CurTok != tok_identifier)
539 return Error("expected identifier after for");
540
541 std::string IdName = IdentifierStr;
542 getNextToken(); // eat identifier.
543
544 if (CurTok != '=')
545 return Error("expected '=' after for");
546 getNextToken(); // eat '='.
547
548 ExprAST *Start = ParseExpression();
549 if (Start == 0)
550 return 0;
551 if (CurTok != ',')
552 return Error("expected ',' after for start value");
553 getNextToken();
554
555 ExprAST *End = ParseExpression();
556 if (End == 0)
557 return 0;
558
559 // The step value is optional.
560 ExprAST *Step = 0;
561 if (CurTok == ',') {
562 getNextToken();
563 Step = ParseExpression();
564 if (Step == 0)
565 return 0;
566 }
567
568 if (CurTok != tok_in)
569 return Error("expected 'in' after for");
570 getNextToken(); // eat 'in'.
571
572 ExprAST *Body = ParseExpression();
573 if (Body == 0)
574 return 0;
575
576 return new ForExprAST(IdName, Start, End, Step, Body);
577}
578
579/// varexpr ::= 'var' identifier ('=' expression)?
580// (',' identifier ('=' expression)?)* 'in' expression
581static ExprAST *ParseVarExpr() {
582 getNextToken(); // eat the var.
583
584 std::vector<std::pair<std::string, ExprAST *> > VarNames;
585
586 // At least one variable name is required.
587 if (CurTok != tok_identifier)
588 return Error("expected identifier after var");
589
590 while (1) {
591 std::string Name = IdentifierStr;
592 getNextToken(); // eat identifier.
593
594 // Read the optional initializer.
595 ExprAST *Init = 0;
596 if (CurTok == '=') {
597 getNextToken(); // eat the '='.
598
599 Init = ParseExpression();
600 if (Init == 0)
601 return 0;
602 }
603
604 VarNames.push_back(std::make_pair(Name, Init));
605
606 // End of var list, exit loop.
607 if (CurTok != ',')
608 break;
609 getNextToken(); // eat the ','.
610
611 if (CurTok != tok_identifier)
612 return Error("expected identifier list after var");
613 }
614
615 // At this point, we have to have 'in'.
616 if (CurTok != tok_in)
617 return Error("expected 'in' keyword after 'var'");
618 getNextToken(); // eat 'in'.
619
620 ExprAST *Body = ParseExpression();
621 if (Body == 0)
622 return 0;
623
624 return new VarExprAST(VarNames, Body);
625}
626
627/// primary
628/// ::= identifierexpr
629/// ::= numberexpr
630/// ::= parenexpr
631/// ::= ifexpr
632/// ::= forexpr
633/// ::= varexpr
634static ExprAST *ParsePrimary() {
635 switch (CurTok) {
636 default:
637 return Error("unknown token when expecting an expression");
638 case tok_identifier:
639 return ParseIdentifierExpr();
640 case tok_number:
641 return ParseNumberExpr();
642 case '(':
643 return ParseParenExpr();
644 case tok_if:
645 return ParseIfExpr();
646 case tok_for:
647 return ParseForExpr();
648 case tok_var:
649 return ParseVarExpr();
650 }
651}
652
653/// unary
654/// ::= primary
655/// ::= '!' unary
656static ExprAST *ParseUnary() {
657 // If the current token is not an operator, it must be a primary expr.
658 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
659 return ParsePrimary();
660
661 // If this is a unary operator, read it.
662 int Opc = CurTok;
663 getNextToken();
664 if (ExprAST *Operand = ParseUnary())
665 return new UnaryExprAST(Opc, Operand);
666 return 0;
667}
668
669/// binoprhs
670/// ::= ('+' unary)*
671static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
672 // If this is a binop, find its precedence.
673 while (1) {
674 int TokPrec = GetTokPrecedence();
675
676 // If this is a binop that binds at least as tightly as the current binop,
677 // consume it, otherwise we are done.
678 if (TokPrec < ExprPrec)
679 return LHS;
680
681 // Okay, we know this is a binop.
682 int BinOp = CurTok;
683 SourceLocation BinLoc = CurLoc;
684 getNextToken(); // eat binop
685
686 // Parse the unary expression after the binary operator.
687 ExprAST *RHS = ParseUnary();
688 if (!RHS)
689 return 0;
690
691 // If BinOp binds less tightly with RHS than the operator after RHS, let
692 // the pending operator take RHS as its LHS.
693 int NextPrec = GetTokPrecedence();
694 if (TokPrec < NextPrec) {
695 RHS = ParseBinOpRHS(TokPrec + 1, RHS);
696 if (RHS == 0)
697 return 0;
698 }
699
700 // Merge LHS/RHS.
701 LHS = new BinaryExprAST(BinLoc, BinOp, LHS, RHS);
702 }
703}
704
705/// expression
706/// ::= unary binoprhs
707///
708static ExprAST *ParseExpression() {
709 ExprAST *LHS = ParseUnary();
710 if (!LHS)
711 return 0;
712
713 return ParseBinOpRHS(0, LHS);
714}
715
716/// prototype
717/// ::= id '(' id* ')'
718/// ::= binary LETTER number? (id, id)
719/// ::= unary LETTER (id)
720static PrototypeAST *ParsePrototype() {
721 std::string FnName;
722
723 SourceLocation FnLoc = CurLoc;
724
725 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
726 unsigned BinaryPrecedence = 30;
727
728 switch (CurTok) {
729 default:
730 return ErrorP("Expected function name in prototype");
731 case tok_identifier:
732 FnName = IdentifierStr;
733 Kind = 0;
734 getNextToken();
735 break;
736 case tok_unary:
737 getNextToken();
738 if (!isascii(CurTok))
739 return ErrorP("Expected unary operator");
740 FnName = "unary";
741 FnName += (char)CurTok;
742 Kind = 1;
743 getNextToken();
744 break;
745 case tok_binary:
746 getNextToken();
747 if (!isascii(CurTok))
748 return ErrorP("Expected binary operator");
749 FnName = "binary";
750 FnName += (char)CurTok;
751 Kind = 2;
752 getNextToken();
753
754 // Read the precedence if present.
755 if (CurTok == tok_number) {
756 if (NumVal < 1 || NumVal > 100)
757 return ErrorP("Invalid precedecnce: must be 1..100");
758 BinaryPrecedence = (unsigned)NumVal;
759 getNextToken();
760 }
761 break;
762 }
763
764 if (CurTok != '(')
765 return ErrorP("Expected '(' in prototype");
766
767 std::vector<std::string> ArgNames;
768 while (getNextToken() == tok_identifier)
769 ArgNames.push_back(IdentifierStr);
770 if (CurTok != ')')
771 return ErrorP("Expected ')' in prototype");
772
773 // success.
774 getNextToken(); // eat ')'.
775
776 // Verify right number of names for operator.
777 if (Kind && ArgNames.size() != Kind)
778 return ErrorP("Invalid number of operands for operator");
779
780 return new PrototypeAST(FnLoc, FnName, ArgNames, Kind != 0, BinaryPrecedence);
781}
782
783/// definition ::= 'def' prototype expression
784static FunctionAST *ParseDefinition() {
785 getNextToken(); // eat def.
786 PrototypeAST *Proto = ParsePrototype();
787 if (Proto == 0)
788 return 0;
789
790 if (ExprAST *E = ParseExpression())
791 return new FunctionAST(Proto, E);
792 return 0;
793}
794
795/// toplevelexpr ::= expression
796static FunctionAST *ParseTopLevelExpr() {
797 SourceLocation FnLoc = CurLoc;
798 if (ExprAST *E = ParseExpression()) {
799 // Make an anonymous proto.
800 PrototypeAST *Proto =
801 new PrototypeAST(FnLoc, "main", std::vector<std::string>());
802 return new FunctionAST(Proto, E);
803 }
804 return 0;
805}
806
807/// external ::= 'extern' prototype
808static PrototypeAST *ParseExtern() {
809 getNextToken(); // eat extern.
810 return ParsePrototype();
811}
812
813//===----------------------------------------------------------------------===//
814// Debug Info Support
815//===----------------------------------------------------------------------===//
816
817static DIBuilder *DBuilder;
818
Duncan P. N. Exon Smithbe9e4fe2015-04-20 18:32:29 +0000819MDType *DebugInfo::getDoubleTy() {
Duncan P. N. Exon Smith1d1a8e02015-04-15 23:49:09 +0000820 if (DblTy)
Eric Christopher05917fa2014-12-08 18:00:47 +0000821 return DblTy;
822
823 DblTy = DBuilder->createBasicType("double", 64, 64, dwarf::DW_ATE_float);
824 return DblTy;
825}
826
827void DebugInfo::emitLocation(ExprAST *AST) {
828 if (!AST)
829 return Builder.SetCurrentDebugLocation(DebugLoc());
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000830 MDScope *Scope;
Eric Christopher05917fa2014-12-08 18:00:47 +0000831 if (LexicalBlocks.empty())
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000832 Scope = TheCU;
Eric Christopher05917fa2014-12-08 18:00:47 +0000833 else
Duncan P. N. Exon Smith3b6f1d52015-04-20 21:29:44 +0000834 Scope = LexicalBlocks.back();
Eric Christopher05917fa2014-12-08 18:00:47 +0000835 Builder.SetCurrentDebugLocation(
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000836 DebugLoc::get(AST->getLine(), AST->getCol(), Scope));
Eric Christopher05917fa2014-12-08 18:00:47 +0000837}
838
Duncan P. N. Exon Smithbe9e4fe2015-04-20 18:32:29 +0000839static MDSubroutineType *CreateFunctionType(unsigned NumArgs, MDFile *Unit) {
Duncan P. N. Exon Smith4e752fb2015-01-06 23:48:22 +0000840 SmallVector<Metadata *, 8> EltTys;
Duncan P. N. Exon Smithbe9e4fe2015-04-20 18:32:29 +0000841 MDType *DblTy = KSDbgInfo.getDoubleTy();
Eric Christopher05917fa2014-12-08 18:00:47 +0000842
843 // Add the result type.
844 EltTys.push_back(DblTy);
845
846 for (unsigned i = 0, e = NumArgs; i != e; ++i)
847 EltTys.push_back(DblTy);
848
Duncan P. N. Exon Smithbe9e4fe2015-04-20 18:32:29 +0000849 return DBuilder->createSubroutineType(Unit,
850 DBuilder->getOrCreateTypeArray(EltTys));
Eric Christopher05917fa2014-12-08 18:00:47 +0000851}
852
853//===----------------------------------------------------------------------===//
854// Code Generation
855//===----------------------------------------------------------------------===//
856
857static Module *TheModule;
858static std::map<std::string, AllocaInst *> NamedValues;
Chandler Carruth7ecd9912015-02-13 10:21:05 +0000859static legacy::FunctionPassManager *TheFPM;
Eric Christopher05917fa2014-12-08 18:00:47 +0000860
861Value *ErrorV(const char *Str) {
862 Error(Str);
863 return 0;
864}
865
866/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
867/// the function. This is used for mutable variables etc.
868static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
869 const std::string &VarName) {
870 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
871 TheFunction->getEntryBlock().begin());
872 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
873 VarName.c_str());
874}
875
876Value *NumberExprAST::Codegen() {
877 KSDbgInfo.emitLocation(this);
878 return ConstantFP::get(getGlobalContext(), APFloat(Val));
879}
880
881Value *VariableExprAST::Codegen() {
882 // Look this variable up in the function.
883 Value *V = NamedValues[Name];
884 if (V == 0)
885 return ErrorV("Unknown variable name");
886
887 KSDbgInfo.emitLocation(this);
888 // Load the value.
889 return Builder.CreateLoad(V, Name.c_str());
890}
891
892Value *UnaryExprAST::Codegen() {
893 Value *OperandV = Operand->Codegen();
894 if (OperandV == 0)
895 return 0;
896
897 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
898 if (F == 0)
899 return ErrorV("Unknown unary operator");
900
901 KSDbgInfo.emitLocation(this);
902 return Builder.CreateCall(F, OperandV, "unop");
903}
904
905Value *BinaryExprAST::Codegen() {
906 KSDbgInfo.emitLocation(this);
907
908 // Special case '=' because we don't want to emit the LHS as an expression.
909 if (Op == '=') {
910 // Assignment requires the LHS to be an identifier.
Lang Hamese7c28bc2015-04-22 20:41:34 +0000911 // This assume we're building without RTTI because LLVM builds that way by
912 // default. If you build LLVM with RTTI this can be changed to a
913 // dynamic_cast for automatic error checking.
Lang Hamesa3276442015-04-22 20:58:34 +0000914 VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS);
Eric Christopher05917fa2014-12-08 18:00:47 +0000915 if (!LHSE)
916 return ErrorV("destination of '=' must be a variable");
917 // Codegen the RHS.
918 Value *Val = RHS->Codegen();
919 if (Val == 0)
920 return 0;
921
922 // Look up the name.
923 Value *Variable = NamedValues[LHSE->getName()];
924 if (Variable == 0)
925 return ErrorV("Unknown variable name");
926
927 Builder.CreateStore(Val, Variable);
928 return Val;
929 }
930
931 Value *L = LHS->Codegen();
932 Value *R = RHS->Codegen();
933 if (L == 0 || R == 0)
934 return 0;
935
936 switch (Op) {
937 case '+':
938 return Builder.CreateFAdd(L, R, "addtmp");
939 case '-':
940 return Builder.CreateFSub(L, R, "subtmp");
941 case '*':
942 return Builder.CreateFMul(L, R, "multmp");
943 case '<':
944 L = Builder.CreateFCmpULT(L, R, "cmptmp");
945 // Convert bool 0/1 to double 0.0 or 1.0
946 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
947 "booltmp");
948 default:
949 break;
950 }
951
952 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
953 // a call to it.
954 Function *F = TheModule->getFunction(std::string("binary") + Op);
955 assert(F && "binary operator not found!");
956
957 Value *Ops[] = { L, R };
958 return Builder.CreateCall(F, Ops, "binop");
959}
960
961Value *CallExprAST::Codegen() {
962 KSDbgInfo.emitLocation(this);
963
964 // Look up the name in the global module table.
965 Function *CalleeF = TheModule->getFunction(Callee);
966 if (CalleeF == 0)
967 return ErrorV("Unknown function referenced");
968
969 // If argument mismatch error.
970 if (CalleeF->arg_size() != Args.size())
971 return ErrorV("Incorrect # arguments passed");
972
973 std::vector<Value *> ArgsV;
974 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
975 ArgsV.push_back(Args[i]->Codegen());
976 if (ArgsV.back() == 0)
977 return 0;
978 }
979
980 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
981}
982
983Value *IfExprAST::Codegen() {
984 KSDbgInfo.emitLocation(this);
985
986 Value *CondV = Cond->Codegen();
987 if (CondV == 0)
988 return 0;
989
990 // Convert condition to a bool by comparing equal to 0.0.
991 CondV = Builder.CreateFCmpONE(
992 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
993
994 Function *TheFunction = Builder.GetInsertBlock()->getParent();
995
996 // Create blocks for the then and else cases. Insert the 'then' block at the
997 // end of the function.
998 BasicBlock *ThenBB =
999 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
1000 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
1001 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
1002
1003 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
1004
1005 // Emit then value.
1006 Builder.SetInsertPoint(ThenBB);
1007
1008 Value *ThenV = Then->Codegen();
1009 if (ThenV == 0)
1010 return 0;
1011
1012 Builder.CreateBr(MergeBB);
1013 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
1014 ThenBB = Builder.GetInsertBlock();
1015
1016 // Emit else block.
1017 TheFunction->getBasicBlockList().push_back(ElseBB);
1018 Builder.SetInsertPoint(ElseBB);
1019
1020 Value *ElseV = Else->Codegen();
1021 if (ElseV == 0)
1022 return 0;
1023
1024 Builder.CreateBr(MergeBB);
1025 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
1026 ElseBB = Builder.GetInsertBlock();
1027
1028 // Emit merge block.
1029 TheFunction->getBasicBlockList().push_back(MergeBB);
1030 Builder.SetInsertPoint(MergeBB);
1031 PHINode *PN =
1032 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
1033
1034 PN->addIncoming(ThenV, ThenBB);
1035 PN->addIncoming(ElseV, ElseBB);
1036 return PN;
1037}
1038
1039Value *ForExprAST::Codegen() {
1040 // Output this as:
1041 // var = alloca double
1042 // ...
1043 // start = startexpr
1044 // store start -> var
1045 // goto loop
1046 // loop:
1047 // ...
1048 // bodyexpr
1049 // ...
1050 // loopend:
1051 // step = stepexpr
1052 // endcond = endexpr
1053 //
1054 // curvar = load var
1055 // nextvar = curvar + step
1056 // store nextvar -> var
1057 // br endcond, loop, endloop
1058 // outloop:
1059
1060 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1061
1062 // Create an alloca for the variable in the entry block.
1063 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1064
1065 KSDbgInfo.emitLocation(this);
1066
1067 // Emit the start code first, without 'variable' in scope.
1068 Value *StartVal = Start->Codegen();
1069 if (StartVal == 0)
1070 return 0;
1071
1072 // Store the value into the alloca.
1073 Builder.CreateStore(StartVal, Alloca);
1074
1075 // Make the new basic block for the loop header, inserting after current
1076 // block.
1077 BasicBlock *LoopBB =
1078 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
1079
1080 // Insert an explicit fall through from the current block to the LoopBB.
1081 Builder.CreateBr(LoopBB);
1082
1083 // Start insertion in LoopBB.
1084 Builder.SetInsertPoint(LoopBB);
1085
1086 // Within the loop, the variable is defined equal to the PHI node. If it
1087 // shadows an existing variable, we have to restore it, so save it now.
1088 AllocaInst *OldVal = NamedValues[VarName];
1089 NamedValues[VarName] = Alloca;
1090
1091 // Emit the body of the loop. This, like any other expr, can change the
1092 // current BB. Note that we ignore the value computed by the body, but don't
1093 // allow an error.
1094 if (Body->Codegen() == 0)
1095 return 0;
1096
1097 // Emit the step value.
1098 Value *StepVal;
1099 if (Step) {
1100 StepVal = Step->Codegen();
1101 if (StepVal == 0)
1102 return 0;
1103 } else {
1104 // If not specified, use 1.0.
1105 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
1106 }
1107
1108 // Compute the end condition.
1109 Value *EndCond = End->Codegen();
1110 if (EndCond == 0)
1111 return EndCond;
1112
1113 // Reload, increment, and restore the alloca. This handles the case where
1114 // the body of the loop mutates the variable.
1115 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
1116 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
1117 Builder.CreateStore(NextVar, Alloca);
1118
1119 // Convert condition to a bool by comparing equal to 0.0.
1120 EndCond = Builder.CreateFCmpONE(
1121 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
1122
1123 // Create the "after loop" block and insert it.
1124 BasicBlock *AfterBB =
1125 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
1126
1127 // Insert the conditional branch into the end of LoopEndBB.
1128 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
1129
1130 // Any new code will be inserted in AfterBB.
1131 Builder.SetInsertPoint(AfterBB);
1132
1133 // Restore the unshadowed variable.
1134 if (OldVal)
1135 NamedValues[VarName] = OldVal;
1136 else
1137 NamedValues.erase(VarName);
1138
1139 // for expr always returns 0.0.
1140 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
1141}
1142
1143Value *VarExprAST::Codegen() {
1144 std::vector<AllocaInst *> OldBindings;
1145
1146 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1147
1148 // Register all variables and emit their initializer.
1149 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
1150 const std::string &VarName = VarNames[i].first;
1151 ExprAST *Init = VarNames[i].second;
1152
1153 // Emit the initializer before adding the variable to scope, this prevents
1154 // the initializer from referencing the variable itself, and permits stuff
1155 // like this:
1156 // var a = 1 in
1157 // var a = a in ... # refers to outer 'a'.
1158 Value *InitVal;
1159 if (Init) {
1160 InitVal = Init->Codegen();
1161 if (InitVal == 0)
1162 return 0;
1163 } else { // If not specified, use 0.0.
1164 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1165 }
1166
1167 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1168 Builder.CreateStore(InitVal, Alloca);
1169
1170 // Remember the old variable binding so that we can restore the binding when
1171 // we unrecurse.
1172 OldBindings.push_back(NamedValues[VarName]);
1173
1174 // Remember this binding.
1175 NamedValues[VarName] = Alloca;
1176 }
1177
1178 KSDbgInfo.emitLocation(this);
1179
1180 // Codegen the body, now that all vars are in scope.
1181 Value *BodyVal = Body->Codegen();
1182 if (BodyVal == 0)
1183 return 0;
1184
1185 // Pop all our variables from scope.
1186 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1187 NamedValues[VarNames[i].first] = OldBindings[i];
1188
1189 // Return the body computation.
1190 return BodyVal;
1191}
1192
1193Function *PrototypeAST::Codegen() {
1194 // Make the function type: double(double,double) etc.
1195 std::vector<Type *> Doubles(Args.size(),
1196 Type::getDoubleTy(getGlobalContext()));
1197 FunctionType *FT =
1198 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
1199
1200 Function *F =
1201 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
1202
1203 // If F conflicted, there was already something named 'Name'. If it has a
1204 // body, don't allow redefinition or reextern.
1205 if (F->getName() != Name) {
1206 // Delete the one we just made and get the existing one.
1207 F->eraseFromParent();
1208 F = TheModule->getFunction(Name);
1209
1210 // If F already has a body, reject this.
1211 if (!F->empty()) {
1212 ErrorF("redefinition of function");
1213 return 0;
1214 }
1215
1216 // If F took a different number of args, reject.
1217 if (F->arg_size() != Args.size()) {
1218 ErrorF("redefinition of function with different # args");
1219 return 0;
1220 }
1221 }
1222
1223 // Set names for all arguments.
1224 unsigned Idx = 0;
1225 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1226 ++AI, ++Idx)
1227 AI->setName(Args[Idx]);
1228
1229 // Create a subprogram DIE for this function.
Duncan P. N. Exon Smithbe9e4fe2015-04-20 18:32:29 +00001230 MDFile *Unit = DBuilder->createFile(KSDbgInfo.TheCU->getFilename(),
1231 KSDbgInfo.TheCU->getDirectory());
Duncan P. N. Exon Smith02083532015-04-16 16:36:23 +00001232 MDScope *FContext = Unit;
Eric Christopher05917fa2014-12-08 18:00:47 +00001233 unsigned LineNo = Line;
1234 unsigned ScopeLine = Line;
Duncan P. N. Exon Smithbe9e4fe2015-04-20 18:32:29 +00001235 MDSubprogram *SP = DBuilder->createFunction(
Eric Christopher05917fa2014-12-08 18:00:47 +00001236 FContext, Name, StringRef(), Unit, LineNo,
1237 CreateFunctionType(Args.size(), Unit), false /* internal linkage */,
Duncan P. N. Exon Smithf15c6f82015-04-16 01:53:33 +00001238 true /* definition */, ScopeLine, DebugNode::FlagPrototyped, false, F);
Eric Christopher05917fa2014-12-08 18:00:47 +00001239
Duncan P. N. Exon Smith754cf792015-04-14 16:19:44 +00001240 KSDbgInfo.FnScopeMap[this] = SP;
Eric Christopher05917fa2014-12-08 18:00:47 +00001241 return F;
1242}
1243
1244/// CreateArgumentAllocas - Create an alloca for each argument and register the
1245/// argument in the symbol table so that references to it will succeed.
1246void PrototypeAST::CreateArgumentAllocas(Function *F) {
1247 Function::arg_iterator AI = F->arg_begin();
1248 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1249 // Create an alloca for this variable.
1250 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1251
1252 // Create a debug descriptor for the variable.
Duncan P. N. Exon Smithbe9e4fe2015-04-20 18:32:29 +00001253 MDScope *Scope = KSDbgInfo.LexicalBlocks.back();
1254 MDFile *Unit = DBuilder->createFile(KSDbgInfo.TheCU->getFilename(),
1255 KSDbgInfo.TheCU->getDirectory());
1256 MDLocalVariable *D = DBuilder->createLocalVariable(
1257 dwarf::DW_TAG_arg_variable, Scope, Args[Idx], Unit, Line,
1258 KSDbgInfo.getDoubleTy(), Idx);
Eric Christopher05917fa2014-12-08 18:00:47 +00001259
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +00001260 DBuilder->insertDeclare(Alloca, D, DBuilder->createExpression(),
Duncan P. N. Exon Smithbe9e4fe2015-04-20 18:32:29 +00001261 DebugLoc::get(Line, 0, Scope),
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +00001262 Builder.GetInsertBlock());
Eric Christopher05917fa2014-12-08 18:00:47 +00001263
1264 // Store the initial value into the alloca.
1265 Builder.CreateStore(AI, Alloca);
1266
1267 // Add arguments to variable symbol table.
1268 NamedValues[Args[Idx]] = Alloca;
1269 }
1270}
1271
1272Function *FunctionAST::Codegen() {
1273 NamedValues.clear();
1274
1275 Function *TheFunction = Proto->Codegen();
1276 if (TheFunction == 0)
1277 return 0;
1278
1279 // Push the current scope.
Duncan P. N. Exon Smith3b6f1d52015-04-20 21:29:44 +00001280 KSDbgInfo.LexicalBlocks.push_back(KSDbgInfo.FnScopeMap[Proto]);
Eric Christopher05917fa2014-12-08 18:00:47 +00001281
1282 // Unset the location for the prologue emission (leading instructions with no
1283 // location in a function are considered part of the prologue and the debugger
1284 // will run past them when breaking on a function)
1285 KSDbgInfo.emitLocation(nullptr);
1286
1287 // If this is an operator, install it.
1288 if (Proto->isBinaryOp())
1289 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
1290
1291 // Create a new basic block to start insertion into.
1292 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1293 Builder.SetInsertPoint(BB);
1294
1295 // Add all arguments to the symbol table and create their allocas.
1296 Proto->CreateArgumentAllocas(TheFunction);
1297
1298 KSDbgInfo.emitLocation(Body);
1299
1300 if (Value *RetVal = Body->Codegen()) {
1301 // Finish off the function.
1302 Builder.CreateRet(RetVal);
1303
1304 // Pop off the lexical block for the function.
1305 KSDbgInfo.LexicalBlocks.pop_back();
1306
1307 // Validate the generated code, checking for consistency.
1308 verifyFunction(*TheFunction);
1309
1310 // Optimize the function.
1311 TheFPM->run(*TheFunction);
1312
1313 return TheFunction;
1314 }
1315
1316 // Error reading body, remove function.
1317 TheFunction->eraseFromParent();
1318
1319 if (Proto->isBinaryOp())
1320 BinopPrecedence.erase(Proto->getOperatorName());
1321
1322 // Pop off the lexical block for the function since we added it
1323 // unconditionally.
1324 KSDbgInfo.LexicalBlocks.pop_back();
1325
1326 return 0;
1327}
1328
1329//===----------------------------------------------------------------------===//
1330// Top-Level parsing and JIT Driver
1331//===----------------------------------------------------------------------===//
1332
1333static ExecutionEngine *TheExecutionEngine;
1334
1335static void HandleDefinition() {
1336 if (FunctionAST *F = ParseDefinition()) {
1337 if (!F->Codegen()) {
1338 fprintf(stderr, "Error reading function definition:");
1339 }
1340 } else {
1341 // Skip token for error recovery.
1342 getNextToken();
1343 }
1344}
1345
1346static void HandleExtern() {
1347 if (PrototypeAST *P = ParseExtern()) {
1348 if (!P->Codegen()) {
1349 fprintf(stderr, "Error reading extern");
1350 }
1351 } else {
1352 // Skip token for error recovery.
1353 getNextToken();
1354 }
1355}
1356
1357static void HandleTopLevelExpression() {
1358 // Evaluate a top-level expression into an anonymous function.
1359 if (FunctionAST *F = ParseTopLevelExpr()) {
1360 if (!F->Codegen()) {
1361 fprintf(stderr, "Error generating code for top level expr");
1362 }
1363 } else {
1364 // Skip token for error recovery.
1365 getNextToken();
1366 }
1367}
1368
1369/// top ::= definition | external | expression | ';'
1370static void MainLoop() {
1371 while (1) {
1372 switch (CurTok) {
1373 case tok_eof:
1374 return;
1375 case ';':
1376 getNextToken();
1377 break; // ignore top-level semicolons.
1378 case tok_def:
1379 HandleDefinition();
1380 break;
1381 case tok_extern:
1382 HandleExtern();
1383 break;
1384 default:
1385 HandleTopLevelExpression();
1386 break;
1387 }
1388 }
1389}
1390
1391//===----------------------------------------------------------------------===//
1392// "Library" functions that can be "extern'd" from user code.
1393//===----------------------------------------------------------------------===//
1394
1395/// putchard - putchar that takes a double and returns 0.
1396extern "C" double putchard(double X) {
1397 putchar((char)X);
1398 return 0;
1399}
1400
1401/// printd - printf that takes a double prints it as "%f\n", returning 0.
1402extern "C" double printd(double X) {
1403 printf("%f\n", X);
1404 return 0;
1405}
1406
1407//===----------------------------------------------------------------------===//
1408// Main driver code.
1409//===----------------------------------------------------------------------===//
1410
1411int main() {
1412 InitializeNativeTarget();
1413 InitializeNativeTargetAsmPrinter();
1414 InitializeNativeTargetAsmParser();
1415 LLVMContext &Context = getGlobalContext();
1416
1417 // Install standard binary operators.
1418 // 1 is lowest precedence.
1419 BinopPrecedence['='] = 2;
1420 BinopPrecedence['<'] = 10;
1421 BinopPrecedence['+'] = 20;
1422 BinopPrecedence['-'] = 20;
1423 BinopPrecedence['*'] = 40; // highest.
1424
1425 // Prime the first token.
1426 getNextToken();
1427
1428 // Make the module, which holds all the code.
1429 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1430 TheModule = Owner.get();
1431
1432 // Add the current debug info version into the module.
1433 TheModule->addModuleFlag(Module::Warning, "Debug Info Version",
1434 DEBUG_METADATA_VERSION);
1435
1436 // Darwin only supports dwarf2.
1437 if (Triple(sys::getProcessTriple()).isOSDarwin())
1438 TheModule->addModuleFlag(llvm::Module::Warning, "Dwarf Version", 2);
1439
1440 // Construct the DIBuilder, we do this here because we need the module.
1441 DBuilder = new DIBuilder(*TheModule);
1442
1443 // Create the compile unit for the module.
1444 // Currently down as "fib.ks" as a filename since we're redirecting stdin
1445 // but we'd like actual source locations.
1446 KSDbgInfo.TheCU = DBuilder->createCompileUnit(
1447 dwarf::DW_LANG_C, "fib.ks", ".", "Kaleidoscope Compiler", 0, "", 0);
1448
1449 // Create the JIT. This takes ownership of the module.
1450 std::string ErrStr;
Eric Christopherc0239362014-12-08 18:12:28 +00001451 TheExecutionEngine =
1452 EngineBuilder(std::move(Owner))
1453 .setErrorStr(&ErrStr)
1454 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1455 .create();
Eric Christopher05917fa2014-12-08 18:00:47 +00001456 if (!TheExecutionEngine) {
1457 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1458 exit(1);
1459 }
1460
Chandler Carruth7ecd9912015-02-13 10:21:05 +00001461 legacy::FunctionPassManager OurFPM(TheModule);
Eric Christopher05917fa2014-12-08 18:00:47 +00001462
1463 // Set up the optimizer pipeline. Start with registering info about how the
1464 // target lays out data structures.
Rafael Espindola265ffbe2015-03-04 19:15:29 +00001465 TheModule->setDataLayout(*TheExecutionEngine->getDataLayout());
Eric Christopher05917fa2014-12-08 18:00:47 +00001466#if 0
1467 // Provide basic AliasAnalysis support for GVN.
1468 OurFPM.add(createBasicAliasAnalysisPass());
1469 // Promote allocas to registers.
1470 OurFPM.add(createPromoteMemoryToRegisterPass());
1471 // Do simple "peephole" optimizations and bit-twiddling optzns.
1472 OurFPM.add(createInstructionCombiningPass());
1473 // Reassociate expressions.
1474 OurFPM.add(createReassociatePass());
1475 // Eliminate Common SubExpressions.
1476 OurFPM.add(createGVNPass());
1477 // Simplify the control flow graph (deleting unreachable blocks, etc).
1478 OurFPM.add(createCFGSimplificationPass());
1479 #endif
1480 OurFPM.doInitialization();
1481
1482 // Set the global so the code gen can use this.
1483 TheFPM = &OurFPM;
1484
1485 // Run the main "interpreter loop" now.
1486 MainLoop();
1487
1488 TheFPM = 0;
1489
1490 // Finalize the debug info.
1491 DBuilder->finalize();
1492
1493 // Print out all of the generated code.
1494 TheModule->dump();
1495
1496 return 0;
1497}