xref: /openbsd-src/gnu/llvm/llvm/examples/Kaleidoscope/Chapter9/toy.cpp (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
109467b48Spatrick #include "llvm/ADT/STLExtras.h"
209467b48Spatrick #include "llvm/Analysis/BasicAliasAnalysis.h"
309467b48Spatrick #include "llvm/Analysis/Passes.h"
409467b48Spatrick #include "llvm/IR/DIBuilder.h"
509467b48Spatrick #include "llvm/IR/IRBuilder.h"
609467b48Spatrick #include "llvm/IR/LLVMContext.h"
709467b48Spatrick #include "llvm/IR/LegacyPassManager.h"
809467b48Spatrick #include "llvm/IR/Module.h"
909467b48Spatrick #include "llvm/IR/Verifier.h"
10097a140dSpatrick #include "llvm/Support/Host.h"
1109467b48Spatrick #include "llvm/Support/TargetSelect.h"
1209467b48Spatrick #include "llvm/Transforms/Scalar.h"
1309467b48Spatrick #include <cctype>
1409467b48Spatrick #include <cstdio>
1509467b48Spatrick #include <map>
1609467b48Spatrick #include <string>
1709467b48Spatrick #include <vector>
1809467b48Spatrick #include "../include/KaleidoscopeJIT.h"
1909467b48Spatrick 
2009467b48Spatrick using namespace llvm;
2109467b48Spatrick using namespace llvm::orc;
2209467b48Spatrick 
2309467b48Spatrick //===----------------------------------------------------------------------===//
2409467b48Spatrick // Lexer
2509467b48Spatrick //===----------------------------------------------------------------------===//
2609467b48Spatrick 
2709467b48Spatrick // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
2809467b48Spatrick // of these for known things.
2909467b48Spatrick enum Token {
3009467b48Spatrick   tok_eof = -1,
3109467b48Spatrick 
3209467b48Spatrick   // commands
3309467b48Spatrick   tok_def = -2,
3409467b48Spatrick   tok_extern = -3,
3509467b48Spatrick 
3609467b48Spatrick   // primary
3709467b48Spatrick   tok_identifier = -4,
3809467b48Spatrick   tok_number = -5,
3909467b48Spatrick 
4009467b48Spatrick   // control
4109467b48Spatrick   tok_if = -6,
4209467b48Spatrick   tok_then = -7,
4309467b48Spatrick   tok_else = -8,
4409467b48Spatrick   tok_for = -9,
4509467b48Spatrick   tok_in = -10,
4609467b48Spatrick 
4709467b48Spatrick   // operators
4809467b48Spatrick   tok_binary = -11,
4909467b48Spatrick   tok_unary = -12,
5009467b48Spatrick 
5109467b48Spatrick   // var definition
5209467b48Spatrick   tok_var = -13
5309467b48Spatrick };
5409467b48Spatrick 
getTokName(int Tok)5509467b48Spatrick std::string getTokName(int Tok) {
5609467b48Spatrick   switch (Tok) {
5709467b48Spatrick   case tok_eof:
5809467b48Spatrick     return "eof";
5909467b48Spatrick   case tok_def:
6009467b48Spatrick     return "def";
6109467b48Spatrick   case tok_extern:
6209467b48Spatrick     return "extern";
6309467b48Spatrick   case tok_identifier:
6409467b48Spatrick     return "identifier";
6509467b48Spatrick   case tok_number:
6609467b48Spatrick     return "number";
6709467b48Spatrick   case tok_if:
6809467b48Spatrick     return "if";
6909467b48Spatrick   case tok_then:
7009467b48Spatrick     return "then";
7109467b48Spatrick   case tok_else:
7209467b48Spatrick     return "else";
7309467b48Spatrick   case tok_for:
7409467b48Spatrick     return "for";
7509467b48Spatrick   case tok_in:
7609467b48Spatrick     return "in";
7709467b48Spatrick   case tok_binary:
7809467b48Spatrick     return "binary";
7909467b48Spatrick   case tok_unary:
8009467b48Spatrick     return "unary";
8109467b48Spatrick   case tok_var:
8209467b48Spatrick     return "var";
8309467b48Spatrick   }
8409467b48Spatrick   return std::string(1, (char)Tok);
8509467b48Spatrick }
8609467b48Spatrick 
8709467b48Spatrick namespace {
8809467b48Spatrick class PrototypeAST;
8909467b48Spatrick class ExprAST;
9009467b48Spatrick }
9173471bf0Spatrick 
9209467b48Spatrick struct DebugInfo {
9309467b48Spatrick   DICompileUnit *TheCU;
9409467b48Spatrick   DIType *DblTy;
9509467b48Spatrick   std::vector<DIScope *> LexicalBlocks;
9609467b48Spatrick 
9709467b48Spatrick   void emitLocation(ExprAST *AST);
9809467b48Spatrick   DIType *getDoubleTy();
9909467b48Spatrick } KSDbgInfo;
10009467b48Spatrick 
10109467b48Spatrick struct SourceLocation {
10209467b48Spatrick   int Line;
10309467b48Spatrick   int Col;
10409467b48Spatrick };
10509467b48Spatrick static SourceLocation CurLoc;
10609467b48Spatrick static SourceLocation LexLoc = {1, 0};
10709467b48Spatrick 
advance()10809467b48Spatrick static int advance() {
10909467b48Spatrick   int LastChar = getchar();
11009467b48Spatrick 
11109467b48Spatrick   if (LastChar == '\n' || LastChar == '\r') {
11209467b48Spatrick     LexLoc.Line++;
11309467b48Spatrick     LexLoc.Col = 0;
11409467b48Spatrick   } else
11509467b48Spatrick     LexLoc.Col++;
11609467b48Spatrick   return LastChar;
11709467b48Spatrick }
11809467b48Spatrick 
11909467b48Spatrick static std::string IdentifierStr; // Filled in if tok_identifier
12009467b48Spatrick static double NumVal;             // Filled in if tok_number
12109467b48Spatrick 
12209467b48Spatrick /// gettok - Return the next token from standard input.
gettok()12309467b48Spatrick static int gettok() {
12409467b48Spatrick   static int LastChar = ' ';
12509467b48Spatrick 
12609467b48Spatrick   // Skip any whitespace.
12709467b48Spatrick   while (isspace(LastChar))
12809467b48Spatrick     LastChar = advance();
12909467b48Spatrick 
13009467b48Spatrick   CurLoc = LexLoc;
13109467b48Spatrick 
13209467b48Spatrick   if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
13309467b48Spatrick     IdentifierStr = LastChar;
13409467b48Spatrick     while (isalnum((LastChar = advance())))
13509467b48Spatrick       IdentifierStr += LastChar;
13609467b48Spatrick 
13709467b48Spatrick     if (IdentifierStr == "def")
13809467b48Spatrick       return tok_def;
13909467b48Spatrick     if (IdentifierStr == "extern")
14009467b48Spatrick       return tok_extern;
14109467b48Spatrick     if (IdentifierStr == "if")
14209467b48Spatrick       return tok_if;
14309467b48Spatrick     if (IdentifierStr == "then")
14409467b48Spatrick       return tok_then;
14509467b48Spatrick     if (IdentifierStr == "else")
14609467b48Spatrick       return tok_else;
14709467b48Spatrick     if (IdentifierStr == "for")
14809467b48Spatrick       return tok_for;
14909467b48Spatrick     if (IdentifierStr == "in")
15009467b48Spatrick       return tok_in;
15109467b48Spatrick     if (IdentifierStr == "binary")
15209467b48Spatrick       return tok_binary;
15309467b48Spatrick     if (IdentifierStr == "unary")
15409467b48Spatrick       return tok_unary;
15509467b48Spatrick     if (IdentifierStr == "var")
15609467b48Spatrick       return tok_var;
15709467b48Spatrick     return tok_identifier;
15809467b48Spatrick   }
15909467b48Spatrick 
16009467b48Spatrick   if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
16109467b48Spatrick     std::string NumStr;
16209467b48Spatrick     do {
16309467b48Spatrick       NumStr += LastChar;
16409467b48Spatrick       LastChar = advance();
16509467b48Spatrick     } while (isdigit(LastChar) || LastChar == '.');
16609467b48Spatrick 
16709467b48Spatrick     NumVal = strtod(NumStr.c_str(), nullptr);
16809467b48Spatrick     return tok_number;
16909467b48Spatrick   }
17009467b48Spatrick 
17109467b48Spatrick   if (LastChar == '#') {
17209467b48Spatrick     // Comment until end of line.
17309467b48Spatrick     do
17409467b48Spatrick       LastChar = advance();
17509467b48Spatrick     while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
17609467b48Spatrick 
17709467b48Spatrick     if (LastChar != EOF)
17809467b48Spatrick       return gettok();
17909467b48Spatrick   }
18009467b48Spatrick 
18109467b48Spatrick   // Check for end of file.  Don't eat the EOF.
18209467b48Spatrick   if (LastChar == EOF)
18309467b48Spatrick     return tok_eof;
18409467b48Spatrick 
18509467b48Spatrick   // Otherwise, just return the character as its ascii value.
18609467b48Spatrick   int ThisChar = LastChar;
18709467b48Spatrick   LastChar = advance();
18809467b48Spatrick   return ThisChar;
18909467b48Spatrick }
19009467b48Spatrick 
19109467b48Spatrick //===----------------------------------------------------------------------===//
19209467b48Spatrick // Abstract Syntax Tree (aka Parse Tree)
19309467b48Spatrick //===----------------------------------------------------------------------===//
19409467b48Spatrick namespace {
19509467b48Spatrick 
indent(raw_ostream & O,int size)19609467b48Spatrick raw_ostream &indent(raw_ostream &O, int size) {
19709467b48Spatrick   return O << std::string(size, ' ');
19809467b48Spatrick }
19909467b48Spatrick 
20009467b48Spatrick /// ExprAST - Base class for all expression nodes.
20109467b48Spatrick class ExprAST {
20209467b48Spatrick   SourceLocation Loc;
20309467b48Spatrick 
20409467b48Spatrick public:
ExprAST(SourceLocation Loc=CurLoc)20509467b48Spatrick   ExprAST(SourceLocation Loc = CurLoc) : Loc(Loc) {}
~ExprAST()20609467b48Spatrick   virtual ~ExprAST() {}
20709467b48Spatrick   virtual Value *codegen() = 0;
getLine() const20809467b48Spatrick   int getLine() const { return Loc.Line; }
getCol() const20909467b48Spatrick   int getCol() const { return Loc.Col; }
dump(raw_ostream & out,int ind)21009467b48Spatrick   virtual raw_ostream &dump(raw_ostream &out, int ind) {
21109467b48Spatrick     return out << ':' << getLine() << ':' << getCol() << '\n';
21209467b48Spatrick   }
21309467b48Spatrick };
21409467b48Spatrick 
21509467b48Spatrick /// NumberExprAST - Expression class for numeric literals like "1.0".
21609467b48Spatrick class NumberExprAST : public ExprAST {
21709467b48Spatrick   double Val;
21809467b48Spatrick 
21909467b48Spatrick public:
NumberExprAST(double Val)22009467b48Spatrick   NumberExprAST(double Val) : Val(Val) {}
dump(raw_ostream & out,int ind)22109467b48Spatrick   raw_ostream &dump(raw_ostream &out, int ind) override {
22209467b48Spatrick     return ExprAST::dump(out << Val, ind);
22309467b48Spatrick   }
22409467b48Spatrick   Value *codegen() override;
22509467b48Spatrick };
22609467b48Spatrick 
22709467b48Spatrick /// VariableExprAST - Expression class for referencing a variable, like "a".
22809467b48Spatrick class VariableExprAST : public ExprAST {
22909467b48Spatrick   std::string Name;
23009467b48Spatrick 
23109467b48Spatrick public:
VariableExprAST(SourceLocation Loc,const std::string & Name)23209467b48Spatrick   VariableExprAST(SourceLocation Loc, const std::string &Name)
23309467b48Spatrick       : ExprAST(Loc), Name(Name) {}
getName() const23409467b48Spatrick   const std::string &getName() const { return Name; }
23509467b48Spatrick   Value *codegen() override;
dump(raw_ostream & out,int ind)23609467b48Spatrick   raw_ostream &dump(raw_ostream &out, int ind) override {
23709467b48Spatrick     return ExprAST::dump(out << Name, ind);
23809467b48Spatrick   }
23909467b48Spatrick };
24009467b48Spatrick 
24109467b48Spatrick /// UnaryExprAST - Expression class for a unary operator.
24209467b48Spatrick class UnaryExprAST : public ExprAST {
24309467b48Spatrick   char Opcode;
24409467b48Spatrick   std::unique_ptr<ExprAST> Operand;
24509467b48Spatrick 
24609467b48Spatrick public:
UnaryExprAST(char Opcode,std::unique_ptr<ExprAST> Operand)24709467b48Spatrick   UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
24809467b48Spatrick       : Opcode(Opcode), Operand(std::move(Operand)) {}
24909467b48Spatrick   Value *codegen() override;
dump(raw_ostream & out,int ind)25009467b48Spatrick   raw_ostream &dump(raw_ostream &out, int ind) override {
25109467b48Spatrick     ExprAST::dump(out << "unary" << Opcode, ind);
25209467b48Spatrick     Operand->dump(out, ind + 1);
25309467b48Spatrick     return out;
25409467b48Spatrick   }
25509467b48Spatrick };
25609467b48Spatrick 
25709467b48Spatrick /// BinaryExprAST - Expression class for a binary operator.
25809467b48Spatrick class BinaryExprAST : public ExprAST {
25909467b48Spatrick   char Op;
26009467b48Spatrick   std::unique_ptr<ExprAST> LHS, RHS;
26109467b48Spatrick 
26209467b48Spatrick public:
BinaryExprAST(SourceLocation Loc,char Op,std::unique_ptr<ExprAST> LHS,std::unique_ptr<ExprAST> RHS)26309467b48Spatrick   BinaryExprAST(SourceLocation Loc, char Op, std::unique_ptr<ExprAST> LHS,
26409467b48Spatrick                 std::unique_ptr<ExprAST> RHS)
26509467b48Spatrick       : ExprAST(Loc), Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
26609467b48Spatrick   Value *codegen() override;
dump(raw_ostream & out,int ind)26709467b48Spatrick   raw_ostream &dump(raw_ostream &out, int ind) override {
26809467b48Spatrick     ExprAST::dump(out << "binary" << Op, ind);
26909467b48Spatrick     LHS->dump(indent(out, ind) << "LHS:", ind + 1);
27009467b48Spatrick     RHS->dump(indent(out, ind) << "RHS:", ind + 1);
27109467b48Spatrick     return out;
27209467b48Spatrick   }
27309467b48Spatrick };
27409467b48Spatrick 
27509467b48Spatrick /// CallExprAST - Expression class for function calls.
27609467b48Spatrick class CallExprAST : public ExprAST {
27709467b48Spatrick   std::string Callee;
27809467b48Spatrick   std::vector<std::unique_ptr<ExprAST>> Args;
27909467b48Spatrick 
28009467b48Spatrick public:
CallExprAST(SourceLocation Loc,const std::string & Callee,std::vector<std::unique_ptr<ExprAST>> Args)28109467b48Spatrick   CallExprAST(SourceLocation Loc, const std::string &Callee,
28209467b48Spatrick               std::vector<std::unique_ptr<ExprAST>> Args)
28309467b48Spatrick       : ExprAST(Loc), Callee(Callee), Args(std::move(Args)) {}
28409467b48Spatrick   Value *codegen() override;
dump(raw_ostream & out,int ind)28509467b48Spatrick   raw_ostream &dump(raw_ostream &out, int ind) override {
28609467b48Spatrick     ExprAST::dump(out << "call " << Callee, ind);
28709467b48Spatrick     for (const auto &Arg : Args)
28809467b48Spatrick       Arg->dump(indent(out, ind + 1), ind + 1);
28909467b48Spatrick     return out;
29009467b48Spatrick   }
29109467b48Spatrick };
29209467b48Spatrick 
29309467b48Spatrick /// IfExprAST - Expression class for if/then/else.
29409467b48Spatrick class IfExprAST : public ExprAST {
29509467b48Spatrick   std::unique_ptr<ExprAST> Cond, Then, Else;
29609467b48Spatrick 
29709467b48Spatrick public:
IfExprAST(SourceLocation Loc,std::unique_ptr<ExprAST> Cond,std::unique_ptr<ExprAST> Then,std::unique_ptr<ExprAST> Else)29809467b48Spatrick   IfExprAST(SourceLocation Loc, std::unique_ptr<ExprAST> Cond,
29909467b48Spatrick             std::unique_ptr<ExprAST> Then, std::unique_ptr<ExprAST> Else)
30009467b48Spatrick       : ExprAST(Loc), Cond(std::move(Cond)), Then(std::move(Then)),
30109467b48Spatrick         Else(std::move(Else)) {}
30209467b48Spatrick   Value *codegen() override;
dump(raw_ostream & out,int ind)30309467b48Spatrick   raw_ostream &dump(raw_ostream &out, int ind) override {
30409467b48Spatrick     ExprAST::dump(out << "if", ind);
30509467b48Spatrick     Cond->dump(indent(out, ind) << "Cond:", ind + 1);
30609467b48Spatrick     Then->dump(indent(out, ind) << "Then:", ind + 1);
30709467b48Spatrick     Else->dump(indent(out, ind) << "Else:", ind + 1);
30809467b48Spatrick     return out;
30909467b48Spatrick   }
31009467b48Spatrick };
31109467b48Spatrick 
31209467b48Spatrick /// ForExprAST - Expression class for for/in.
31309467b48Spatrick class ForExprAST : public ExprAST {
31409467b48Spatrick   std::string VarName;
31509467b48Spatrick   std::unique_ptr<ExprAST> Start, End, Step, Body;
31609467b48Spatrick 
31709467b48Spatrick public:
ForExprAST(const std::string & VarName,std::unique_ptr<ExprAST> Start,std::unique_ptr<ExprAST> End,std::unique_ptr<ExprAST> Step,std::unique_ptr<ExprAST> Body)31809467b48Spatrick   ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
31909467b48Spatrick              std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
32009467b48Spatrick              std::unique_ptr<ExprAST> Body)
32109467b48Spatrick       : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
32209467b48Spatrick         Step(std::move(Step)), Body(std::move(Body)) {}
32309467b48Spatrick   Value *codegen() override;
dump(raw_ostream & out,int ind)32409467b48Spatrick   raw_ostream &dump(raw_ostream &out, int ind) override {
32509467b48Spatrick     ExprAST::dump(out << "for", ind);
32609467b48Spatrick     Start->dump(indent(out, ind) << "Cond:", ind + 1);
32709467b48Spatrick     End->dump(indent(out, ind) << "End:", ind + 1);
32809467b48Spatrick     Step->dump(indent(out, ind) << "Step:", ind + 1);
32909467b48Spatrick     Body->dump(indent(out, ind) << "Body:", ind + 1);
33009467b48Spatrick     return out;
33109467b48Spatrick   }
33209467b48Spatrick };
33309467b48Spatrick 
33409467b48Spatrick /// VarExprAST - Expression class for var/in
33509467b48Spatrick class VarExprAST : public ExprAST {
33609467b48Spatrick   std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
33709467b48Spatrick   std::unique_ptr<ExprAST> Body;
33809467b48Spatrick 
33909467b48Spatrick public:
VarExprAST(std::vector<std::pair<std::string,std::unique_ptr<ExprAST>>> VarNames,std::unique_ptr<ExprAST> Body)34009467b48Spatrick   VarExprAST(
34109467b48Spatrick       std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
34209467b48Spatrick       std::unique_ptr<ExprAST> Body)
34309467b48Spatrick       : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
34409467b48Spatrick   Value *codegen() override;
dump(raw_ostream & out,int ind)34509467b48Spatrick   raw_ostream &dump(raw_ostream &out, int ind) override {
34609467b48Spatrick     ExprAST::dump(out << "var", ind);
34709467b48Spatrick     for (const auto &NamedVar : VarNames)
34809467b48Spatrick       NamedVar.second->dump(indent(out, ind) << NamedVar.first << ':', ind + 1);
34909467b48Spatrick     Body->dump(indent(out, ind) << "Body:", ind + 1);
35009467b48Spatrick     return out;
35109467b48Spatrick   }
35209467b48Spatrick };
35309467b48Spatrick 
35409467b48Spatrick /// PrototypeAST - This class represents the "prototype" for a function,
35509467b48Spatrick /// which captures its name, and its argument names (thus implicitly the number
35609467b48Spatrick /// of arguments the function takes), as well as if it is an operator.
35709467b48Spatrick class PrototypeAST {
35809467b48Spatrick   std::string Name;
35909467b48Spatrick   std::vector<std::string> Args;
36009467b48Spatrick   bool IsOperator;
36109467b48Spatrick   unsigned Precedence; // Precedence if a binary op.
36209467b48Spatrick   int Line;
36309467b48Spatrick 
36409467b48Spatrick public:
PrototypeAST(SourceLocation Loc,const std::string & Name,std::vector<std::string> Args,bool IsOperator=false,unsigned Prec=0)36509467b48Spatrick   PrototypeAST(SourceLocation Loc, const std::string &Name,
36609467b48Spatrick                std::vector<std::string> Args, bool IsOperator = false,
36709467b48Spatrick                unsigned Prec = 0)
36809467b48Spatrick       : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
36909467b48Spatrick         Precedence(Prec), Line(Loc.Line) {}
37009467b48Spatrick   Function *codegen();
getName() const37109467b48Spatrick   const std::string &getName() const { return Name; }
37209467b48Spatrick 
isUnaryOp() const37309467b48Spatrick   bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
isBinaryOp() const37409467b48Spatrick   bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
37509467b48Spatrick 
getOperatorName() const37609467b48Spatrick   char getOperatorName() const {
37709467b48Spatrick     assert(isUnaryOp() || isBinaryOp());
37809467b48Spatrick     return Name[Name.size() - 1];
37909467b48Spatrick   }
38009467b48Spatrick 
getBinaryPrecedence() const38109467b48Spatrick   unsigned getBinaryPrecedence() const { return Precedence; }
getLine() const38209467b48Spatrick   int getLine() const { return Line; }
38309467b48Spatrick };
38409467b48Spatrick 
38509467b48Spatrick /// FunctionAST - This class represents a function definition itself.
38609467b48Spatrick class FunctionAST {
38709467b48Spatrick   std::unique_ptr<PrototypeAST> Proto;
38809467b48Spatrick   std::unique_ptr<ExprAST> Body;
38909467b48Spatrick 
39009467b48Spatrick public:
FunctionAST(std::unique_ptr<PrototypeAST> Proto,std::unique_ptr<ExprAST> Body)39109467b48Spatrick   FunctionAST(std::unique_ptr<PrototypeAST> Proto,
39209467b48Spatrick               std::unique_ptr<ExprAST> Body)
39309467b48Spatrick       : Proto(std::move(Proto)), Body(std::move(Body)) {}
39409467b48Spatrick   Function *codegen();
dump(raw_ostream & out,int ind)39509467b48Spatrick   raw_ostream &dump(raw_ostream &out, int ind) {
39609467b48Spatrick     indent(out, ind) << "FunctionAST\n";
39709467b48Spatrick     ++ind;
39809467b48Spatrick     indent(out, ind) << "Body:";
39909467b48Spatrick     return Body ? Body->dump(out, ind) : out << "null\n";
40009467b48Spatrick   }
40109467b48Spatrick };
40209467b48Spatrick } // end anonymous namespace
40309467b48Spatrick 
40409467b48Spatrick //===----------------------------------------------------------------------===//
40509467b48Spatrick // Parser
40609467b48Spatrick //===----------------------------------------------------------------------===//
40709467b48Spatrick 
40809467b48Spatrick /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
40909467b48Spatrick /// token the parser is looking at.  getNextToken reads another token from the
41009467b48Spatrick /// lexer and updates CurTok with its results.
41109467b48Spatrick static int CurTok;
getNextToken()41209467b48Spatrick static int getNextToken() { return CurTok = gettok(); }
41309467b48Spatrick 
41409467b48Spatrick /// BinopPrecedence - This holds the precedence for each binary operator that is
41509467b48Spatrick /// defined.
41609467b48Spatrick static std::map<char, int> BinopPrecedence;
41709467b48Spatrick 
41809467b48Spatrick /// GetTokPrecedence - Get the precedence of the pending binary operator token.
GetTokPrecedence()41909467b48Spatrick static int GetTokPrecedence() {
42009467b48Spatrick   if (!isascii(CurTok))
42109467b48Spatrick     return -1;
42209467b48Spatrick 
42309467b48Spatrick   // Make sure it's a declared binop.
42409467b48Spatrick   int TokPrec = BinopPrecedence[CurTok];
42509467b48Spatrick   if (TokPrec <= 0)
42609467b48Spatrick     return -1;
42709467b48Spatrick   return TokPrec;
42809467b48Spatrick }
42909467b48Spatrick 
43009467b48Spatrick /// LogError* - These are little helper functions for error handling.
LogError(const char * Str)43109467b48Spatrick std::unique_ptr<ExprAST> LogError(const char *Str) {
43209467b48Spatrick   fprintf(stderr, "Error: %s\n", Str);
43309467b48Spatrick   return nullptr;
43409467b48Spatrick }
43509467b48Spatrick 
LogErrorP(const char * Str)43609467b48Spatrick std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
43709467b48Spatrick   LogError(Str);
43809467b48Spatrick   return nullptr;
43909467b48Spatrick }
44009467b48Spatrick 
44109467b48Spatrick static std::unique_ptr<ExprAST> ParseExpression();
44209467b48Spatrick 
44309467b48Spatrick /// numberexpr ::= number
ParseNumberExpr()44409467b48Spatrick static std::unique_ptr<ExprAST> ParseNumberExpr() {
44509467b48Spatrick   auto Result = std::make_unique<NumberExprAST>(NumVal);
44609467b48Spatrick   getNextToken(); // consume the number
44709467b48Spatrick   return std::move(Result);
44809467b48Spatrick }
44909467b48Spatrick 
45009467b48Spatrick /// parenexpr ::= '(' expression ')'
ParseParenExpr()45109467b48Spatrick static std::unique_ptr<ExprAST> ParseParenExpr() {
45209467b48Spatrick   getNextToken(); // eat (.
45309467b48Spatrick   auto V = ParseExpression();
45409467b48Spatrick   if (!V)
45509467b48Spatrick     return nullptr;
45609467b48Spatrick 
45709467b48Spatrick   if (CurTok != ')')
45809467b48Spatrick     return LogError("expected ')'");
45909467b48Spatrick   getNextToken(); // eat ).
46009467b48Spatrick   return V;
46109467b48Spatrick }
46209467b48Spatrick 
46309467b48Spatrick /// identifierexpr
46409467b48Spatrick ///   ::= identifier
46509467b48Spatrick ///   ::= identifier '(' expression* ')'
ParseIdentifierExpr()46609467b48Spatrick static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
46709467b48Spatrick   std::string IdName = IdentifierStr;
46809467b48Spatrick 
46909467b48Spatrick   SourceLocation LitLoc = CurLoc;
47009467b48Spatrick 
47109467b48Spatrick   getNextToken(); // eat identifier.
47209467b48Spatrick 
47309467b48Spatrick   if (CurTok != '(') // Simple variable ref.
47409467b48Spatrick     return std::make_unique<VariableExprAST>(LitLoc, IdName);
47509467b48Spatrick 
47609467b48Spatrick   // Call.
47709467b48Spatrick   getNextToken(); // eat (
47809467b48Spatrick   std::vector<std::unique_ptr<ExprAST>> Args;
47909467b48Spatrick   if (CurTok != ')') {
480*d415bd75Srobert     while (true) {
48109467b48Spatrick       if (auto Arg = ParseExpression())
48209467b48Spatrick         Args.push_back(std::move(Arg));
48309467b48Spatrick       else
48409467b48Spatrick         return nullptr;
48509467b48Spatrick 
48609467b48Spatrick       if (CurTok == ')')
48709467b48Spatrick         break;
48809467b48Spatrick 
48909467b48Spatrick       if (CurTok != ',')
49009467b48Spatrick         return LogError("Expected ')' or ',' in argument list");
49109467b48Spatrick       getNextToken();
49209467b48Spatrick     }
49309467b48Spatrick   }
49409467b48Spatrick 
49509467b48Spatrick   // Eat the ')'.
49609467b48Spatrick   getNextToken();
49709467b48Spatrick 
49809467b48Spatrick   return std::make_unique<CallExprAST>(LitLoc, IdName, std::move(Args));
49909467b48Spatrick }
50009467b48Spatrick 
50109467b48Spatrick /// ifexpr ::= 'if' expression 'then' expression 'else' expression
ParseIfExpr()50209467b48Spatrick static std::unique_ptr<ExprAST> ParseIfExpr() {
50309467b48Spatrick   SourceLocation IfLoc = CurLoc;
50409467b48Spatrick 
50509467b48Spatrick   getNextToken(); // eat the if.
50609467b48Spatrick 
50709467b48Spatrick   // condition.
50809467b48Spatrick   auto Cond = ParseExpression();
50909467b48Spatrick   if (!Cond)
51009467b48Spatrick     return nullptr;
51109467b48Spatrick 
51209467b48Spatrick   if (CurTok != tok_then)
51309467b48Spatrick     return LogError("expected then");
51409467b48Spatrick   getNextToken(); // eat the then
51509467b48Spatrick 
51609467b48Spatrick   auto Then = ParseExpression();
51709467b48Spatrick   if (!Then)
51809467b48Spatrick     return nullptr;
51909467b48Spatrick 
52009467b48Spatrick   if (CurTok != tok_else)
52109467b48Spatrick     return LogError("expected else");
52209467b48Spatrick 
52309467b48Spatrick   getNextToken();
52409467b48Spatrick 
52509467b48Spatrick   auto Else = ParseExpression();
52609467b48Spatrick   if (!Else)
52709467b48Spatrick     return nullptr;
52809467b48Spatrick 
52909467b48Spatrick   return std::make_unique<IfExprAST>(IfLoc, std::move(Cond), std::move(Then),
53009467b48Spatrick                                       std::move(Else));
53109467b48Spatrick }
53209467b48Spatrick 
53309467b48Spatrick /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
ParseForExpr()53409467b48Spatrick static std::unique_ptr<ExprAST> ParseForExpr() {
53509467b48Spatrick   getNextToken(); // eat the for.
53609467b48Spatrick 
53709467b48Spatrick   if (CurTok != tok_identifier)
53809467b48Spatrick     return LogError("expected identifier after for");
53909467b48Spatrick 
54009467b48Spatrick   std::string IdName = IdentifierStr;
54109467b48Spatrick   getNextToken(); // eat identifier.
54209467b48Spatrick 
54309467b48Spatrick   if (CurTok != '=')
54409467b48Spatrick     return LogError("expected '=' after for");
54509467b48Spatrick   getNextToken(); // eat '='.
54609467b48Spatrick 
54709467b48Spatrick   auto Start = ParseExpression();
54809467b48Spatrick   if (!Start)
54909467b48Spatrick     return nullptr;
55009467b48Spatrick   if (CurTok != ',')
55109467b48Spatrick     return LogError("expected ',' after for start value");
55209467b48Spatrick   getNextToken();
55309467b48Spatrick 
55409467b48Spatrick   auto End = ParseExpression();
55509467b48Spatrick   if (!End)
55609467b48Spatrick     return nullptr;
55709467b48Spatrick 
55809467b48Spatrick   // The step value is optional.
55909467b48Spatrick   std::unique_ptr<ExprAST> Step;
56009467b48Spatrick   if (CurTok == ',') {
56109467b48Spatrick     getNextToken();
56209467b48Spatrick     Step = ParseExpression();
56309467b48Spatrick     if (!Step)
56409467b48Spatrick       return nullptr;
56509467b48Spatrick   }
56609467b48Spatrick 
56709467b48Spatrick   if (CurTok != tok_in)
56809467b48Spatrick     return LogError("expected 'in' after for");
56909467b48Spatrick   getNextToken(); // eat 'in'.
57009467b48Spatrick 
57109467b48Spatrick   auto Body = ParseExpression();
57209467b48Spatrick   if (!Body)
57309467b48Spatrick     return nullptr;
57409467b48Spatrick 
57509467b48Spatrick   return std::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
57609467b48Spatrick                                        std::move(Step), std::move(Body));
57709467b48Spatrick }
57809467b48Spatrick 
57909467b48Spatrick /// varexpr ::= 'var' identifier ('=' expression)?
58009467b48Spatrick //                    (',' identifier ('=' expression)?)* 'in' expression
ParseVarExpr()58109467b48Spatrick static std::unique_ptr<ExprAST> ParseVarExpr() {
58209467b48Spatrick   getNextToken(); // eat the var.
58309467b48Spatrick 
58409467b48Spatrick   std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
58509467b48Spatrick 
58609467b48Spatrick   // At least one variable name is required.
58709467b48Spatrick   if (CurTok != tok_identifier)
58809467b48Spatrick     return LogError("expected identifier after var");
58909467b48Spatrick 
590*d415bd75Srobert   while (true) {
59109467b48Spatrick     std::string Name = IdentifierStr;
59209467b48Spatrick     getNextToken(); // eat identifier.
59309467b48Spatrick 
59409467b48Spatrick     // Read the optional initializer.
59509467b48Spatrick     std::unique_ptr<ExprAST> Init = nullptr;
59609467b48Spatrick     if (CurTok == '=') {
59709467b48Spatrick       getNextToken(); // eat the '='.
59809467b48Spatrick 
59909467b48Spatrick       Init = ParseExpression();
60009467b48Spatrick       if (!Init)
60109467b48Spatrick         return nullptr;
60209467b48Spatrick     }
60309467b48Spatrick 
60409467b48Spatrick     VarNames.push_back(std::make_pair(Name, std::move(Init)));
60509467b48Spatrick 
60609467b48Spatrick     // End of var list, exit loop.
60709467b48Spatrick     if (CurTok != ',')
60809467b48Spatrick       break;
60909467b48Spatrick     getNextToken(); // eat the ','.
61009467b48Spatrick 
61109467b48Spatrick     if (CurTok != tok_identifier)
61209467b48Spatrick       return LogError("expected identifier list after var");
61309467b48Spatrick   }
61409467b48Spatrick 
61509467b48Spatrick   // At this point, we have to have 'in'.
61609467b48Spatrick   if (CurTok != tok_in)
61709467b48Spatrick     return LogError("expected 'in' keyword after 'var'");
61809467b48Spatrick   getNextToken(); // eat 'in'.
61909467b48Spatrick 
62009467b48Spatrick   auto Body = ParseExpression();
62109467b48Spatrick   if (!Body)
62209467b48Spatrick     return nullptr;
62309467b48Spatrick 
62409467b48Spatrick   return std::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
62509467b48Spatrick }
62609467b48Spatrick 
62709467b48Spatrick /// primary
62809467b48Spatrick ///   ::= identifierexpr
62909467b48Spatrick ///   ::= numberexpr
63009467b48Spatrick ///   ::= parenexpr
63109467b48Spatrick ///   ::= ifexpr
63209467b48Spatrick ///   ::= forexpr
63309467b48Spatrick ///   ::= varexpr
ParsePrimary()63409467b48Spatrick static std::unique_ptr<ExprAST> ParsePrimary() {
63509467b48Spatrick   switch (CurTok) {
63609467b48Spatrick   default:
63709467b48Spatrick     return LogError("unknown token when expecting an expression");
63809467b48Spatrick   case tok_identifier:
63909467b48Spatrick     return ParseIdentifierExpr();
64009467b48Spatrick   case tok_number:
64109467b48Spatrick     return ParseNumberExpr();
64209467b48Spatrick   case '(':
64309467b48Spatrick     return ParseParenExpr();
64409467b48Spatrick   case tok_if:
64509467b48Spatrick     return ParseIfExpr();
64609467b48Spatrick   case tok_for:
64709467b48Spatrick     return ParseForExpr();
64809467b48Spatrick   case tok_var:
64909467b48Spatrick     return ParseVarExpr();
65009467b48Spatrick   }
65109467b48Spatrick }
65209467b48Spatrick 
65309467b48Spatrick /// unary
65409467b48Spatrick ///   ::= primary
65509467b48Spatrick ///   ::= '!' unary
ParseUnary()65609467b48Spatrick static std::unique_ptr<ExprAST> ParseUnary() {
65709467b48Spatrick   // If the current token is not an operator, it must be a primary expr.
65809467b48Spatrick   if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
65909467b48Spatrick     return ParsePrimary();
66009467b48Spatrick 
66109467b48Spatrick   // If this is a unary operator, read it.
66209467b48Spatrick   int Opc = CurTok;
66309467b48Spatrick   getNextToken();
66409467b48Spatrick   if (auto Operand = ParseUnary())
66509467b48Spatrick     return std::make_unique<UnaryExprAST>(Opc, std::move(Operand));
66609467b48Spatrick   return nullptr;
66709467b48Spatrick }
66809467b48Spatrick 
66909467b48Spatrick /// binoprhs
67009467b48Spatrick ///   ::= ('+' unary)*
ParseBinOpRHS(int ExprPrec,std::unique_ptr<ExprAST> LHS)67109467b48Spatrick static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
67209467b48Spatrick                                               std::unique_ptr<ExprAST> LHS) {
67309467b48Spatrick   // If this is a binop, find its precedence.
674*d415bd75Srobert   while (true) {
67509467b48Spatrick     int TokPrec = GetTokPrecedence();
67609467b48Spatrick 
67709467b48Spatrick     // If this is a binop that binds at least as tightly as the current binop,
67809467b48Spatrick     // consume it, otherwise we are done.
67909467b48Spatrick     if (TokPrec < ExprPrec)
68009467b48Spatrick       return LHS;
68109467b48Spatrick 
68209467b48Spatrick     // Okay, we know this is a binop.
68309467b48Spatrick     int BinOp = CurTok;
68409467b48Spatrick     SourceLocation BinLoc = CurLoc;
68509467b48Spatrick     getNextToken(); // eat binop
68609467b48Spatrick 
68709467b48Spatrick     // Parse the unary expression after the binary operator.
68809467b48Spatrick     auto RHS = ParseUnary();
68909467b48Spatrick     if (!RHS)
69009467b48Spatrick       return nullptr;
69109467b48Spatrick 
69209467b48Spatrick     // If BinOp binds less tightly with RHS than the operator after RHS, let
69309467b48Spatrick     // the pending operator take RHS as its LHS.
69409467b48Spatrick     int NextPrec = GetTokPrecedence();
69509467b48Spatrick     if (TokPrec < NextPrec) {
69609467b48Spatrick       RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
69709467b48Spatrick       if (!RHS)
69809467b48Spatrick         return nullptr;
69909467b48Spatrick     }
70009467b48Spatrick 
70109467b48Spatrick     // Merge LHS/RHS.
70209467b48Spatrick     LHS = std::make_unique<BinaryExprAST>(BinLoc, BinOp, std::move(LHS),
70309467b48Spatrick                                            std::move(RHS));
70409467b48Spatrick   }
70509467b48Spatrick }
70609467b48Spatrick 
70709467b48Spatrick /// expression
70809467b48Spatrick ///   ::= unary binoprhs
70909467b48Spatrick ///
ParseExpression()71009467b48Spatrick static std::unique_ptr<ExprAST> ParseExpression() {
71109467b48Spatrick   auto LHS = ParseUnary();
71209467b48Spatrick   if (!LHS)
71309467b48Spatrick     return nullptr;
71409467b48Spatrick 
71509467b48Spatrick   return ParseBinOpRHS(0, std::move(LHS));
71609467b48Spatrick }
71709467b48Spatrick 
71809467b48Spatrick /// prototype
71909467b48Spatrick ///   ::= id '(' id* ')'
72009467b48Spatrick ///   ::= binary LETTER number? (id, id)
72109467b48Spatrick ///   ::= unary LETTER (id)
ParsePrototype()72209467b48Spatrick static std::unique_ptr<PrototypeAST> ParsePrototype() {
72309467b48Spatrick   std::string FnName;
72409467b48Spatrick 
72509467b48Spatrick   SourceLocation FnLoc = CurLoc;
72609467b48Spatrick 
72709467b48Spatrick   unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
72809467b48Spatrick   unsigned BinaryPrecedence = 30;
72909467b48Spatrick 
73009467b48Spatrick   switch (CurTok) {
73109467b48Spatrick   default:
73209467b48Spatrick     return LogErrorP("Expected function name in prototype");
73309467b48Spatrick   case tok_identifier:
73409467b48Spatrick     FnName = IdentifierStr;
73509467b48Spatrick     Kind = 0;
73609467b48Spatrick     getNextToken();
73709467b48Spatrick     break;
73809467b48Spatrick   case tok_unary:
73909467b48Spatrick     getNextToken();
74009467b48Spatrick     if (!isascii(CurTok))
74109467b48Spatrick       return LogErrorP("Expected unary operator");
74209467b48Spatrick     FnName = "unary";
74309467b48Spatrick     FnName += (char)CurTok;
74409467b48Spatrick     Kind = 1;
74509467b48Spatrick     getNextToken();
74609467b48Spatrick     break;
74709467b48Spatrick   case tok_binary:
74809467b48Spatrick     getNextToken();
74909467b48Spatrick     if (!isascii(CurTok))
75009467b48Spatrick       return LogErrorP("Expected binary operator");
75109467b48Spatrick     FnName = "binary";
75209467b48Spatrick     FnName += (char)CurTok;
75309467b48Spatrick     Kind = 2;
75409467b48Spatrick     getNextToken();
75509467b48Spatrick 
75609467b48Spatrick     // Read the precedence if present.
75709467b48Spatrick     if (CurTok == tok_number) {
75809467b48Spatrick       if (NumVal < 1 || NumVal > 100)
75909467b48Spatrick         return LogErrorP("Invalid precedence: must be 1..100");
76009467b48Spatrick       BinaryPrecedence = (unsigned)NumVal;
76109467b48Spatrick       getNextToken();
76209467b48Spatrick     }
76309467b48Spatrick     break;
76409467b48Spatrick   }
76509467b48Spatrick 
76609467b48Spatrick   if (CurTok != '(')
76709467b48Spatrick     return LogErrorP("Expected '(' in prototype");
76809467b48Spatrick 
76909467b48Spatrick   std::vector<std::string> ArgNames;
77009467b48Spatrick   while (getNextToken() == tok_identifier)
77109467b48Spatrick     ArgNames.push_back(IdentifierStr);
77209467b48Spatrick   if (CurTok != ')')
77309467b48Spatrick     return LogErrorP("Expected ')' in prototype");
77409467b48Spatrick 
77509467b48Spatrick   // success.
77609467b48Spatrick   getNextToken(); // eat ')'.
77709467b48Spatrick 
77809467b48Spatrick   // Verify right number of names for operator.
77909467b48Spatrick   if (Kind && ArgNames.size() != Kind)
78009467b48Spatrick     return LogErrorP("Invalid number of operands for operator");
78109467b48Spatrick 
78209467b48Spatrick   return std::make_unique<PrototypeAST>(FnLoc, FnName, ArgNames, Kind != 0,
78309467b48Spatrick                                          BinaryPrecedence);
78409467b48Spatrick }
78509467b48Spatrick 
78609467b48Spatrick /// definition ::= 'def' prototype expression
ParseDefinition()78709467b48Spatrick static std::unique_ptr<FunctionAST> ParseDefinition() {
78809467b48Spatrick   getNextToken(); // eat def.
78909467b48Spatrick   auto Proto = ParsePrototype();
79009467b48Spatrick   if (!Proto)
79109467b48Spatrick     return nullptr;
79209467b48Spatrick 
79309467b48Spatrick   if (auto E = ParseExpression())
79409467b48Spatrick     return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
79509467b48Spatrick   return nullptr;
79609467b48Spatrick }
79709467b48Spatrick 
79809467b48Spatrick /// toplevelexpr ::= expression
ParseTopLevelExpr()79909467b48Spatrick static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
80009467b48Spatrick   SourceLocation FnLoc = CurLoc;
80109467b48Spatrick   if (auto E = ParseExpression()) {
80209467b48Spatrick     // Make an anonymous proto.
80309467b48Spatrick     auto Proto = std::make_unique<PrototypeAST>(FnLoc, "__anon_expr",
80409467b48Spatrick                                                  std::vector<std::string>());
80509467b48Spatrick     return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
80609467b48Spatrick   }
80709467b48Spatrick   return nullptr;
80809467b48Spatrick }
80909467b48Spatrick 
81009467b48Spatrick /// external ::= 'extern' prototype
ParseExtern()81109467b48Spatrick static std::unique_ptr<PrototypeAST> ParseExtern() {
81209467b48Spatrick   getNextToken(); // eat extern.
81309467b48Spatrick   return ParsePrototype();
81409467b48Spatrick }
81509467b48Spatrick 
81609467b48Spatrick //===----------------------------------------------------------------------===//
81773471bf0Spatrick // Code Generation Globals
81873471bf0Spatrick //===----------------------------------------------------------------------===//
81973471bf0Spatrick 
82073471bf0Spatrick static std::unique_ptr<LLVMContext> TheContext;
82173471bf0Spatrick static std::unique_ptr<Module> TheModule;
82273471bf0Spatrick static std::unique_ptr<IRBuilder<>> Builder;
82373471bf0Spatrick static ExitOnError ExitOnErr;
82473471bf0Spatrick 
82573471bf0Spatrick static std::map<std::string, AllocaInst *> NamedValues;
82673471bf0Spatrick static std::unique_ptr<KaleidoscopeJIT> TheJIT;
82773471bf0Spatrick static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
82873471bf0Spatrick 
82973471bf0Spatrick //===----------------------------------------------------------------------===//
83009467b48Spatrick // Debug Info Support
83109467b48Spatrick //===----------------------------------------------------------------------===//
83209467b48Spatrick 
83309467b48Spatrick static std::unique_ptr<DIBuilder> DBuilder;
83409467b48Spatrick 
getDoubleTy()83509467b48Spatrick DIType *DebugInfo::getDoubleTy() {
83609467b48Spatrick   if (DblTy)
83709467b48Spatrick     return DblTy;
83809467b48Spatrick 
83909467b48Spatrick   DblTy = DBuilder->createBasicType("double", 64, dwarf::DW_ATE_float);
84009467b48Spatrick   return DblTy;
84109467b48Spatrick }
84209467b48Spatrick 
emitLocation(ExprAST * AST)84309467b48Spatrick void DebugInfo::emitLocation(ExprAST *AST) {
84409467b48Spatrick   if (!AST)
84573471bf0Spatrick     return Builder->SetCurrentDebugLocation(DebugLoc());
84609467b48Spatrick   DIScope *Scope;
84709467b48Spatrick   if (LexicalBlocks.empty())
84809467b48Spatrick     Scope = TheCU;
84909467b48Spatrick   else
85009467b48Spatrick     Scope = LexicalBlocks.back();
85173471bf0Spatrick   Builder->SetCurrentDebugLocation(DILocation::get(
85273471bf0Spatrick       Scope->getContext(), AST->getLine(), AST->getCol(), Scope));
85309467b48Spatrick }
85409467b48Spatrick 
CreateFunctionType(unsigned NumArgs)855*d415bd75Srobert static DISubroutineType *CreateFunctionType(unsigned NumArgs) {
85609467b48Spatrick   SmallVector<Metadata *, 8> EltTys;
85709467b48Spatrick   DIType *DblTy = KSDbgInfo.getDoubleTy();
85809467b48Spatrick 
85909467b48Spatrick   // Add the result type.
86009467b48Spatrick   EltTys.push_back(DblTy);
86109467b48Spatrick 
86209467b48Spatrick   for (unsigned i = 0, e = NumArgs; i != e; ++i)
86309467b48Spatrick     EltTys.push_back(DblTy);
86409467b48Spatrick 
86509467b48Spatrick   return DBuilder->createSubroutineType(DBuilder->getOrCreateTypeArray(EltTys));
86609467b48Spatrick }
86709467b48Spatrick 
86809467b48Spatrick //===----------------------------------------------------------------------===//
86909467b48Spatrick // Code Generation
87009467b48Spatrick //===----------------------------------------------------------------------===//
87109467b48Spatrick 
LogErrorV(const char * Str)87209467b48Spatrick Value *LogErrorV(const char *Str) {
87309467b48Spatrick   LogError(Str);
87409467b48Spatrick   return nullptr;
87509467b48Spatrick }
87609467b48Spatrick 
getFunction(std::string Name)87709467b48Spatrick Function *getFunction(std::string Name) {
87809467b48Spatrick   // First, see if the function has already been added to the current module.
87909467b48Spatrick   if (auto *F = TheModule->getFunction(Name))
88009467b48Spatrick     return F;
88109467b48Spatrick 
88209467b48Spatrick   // If not, check whether we can codegen the declaration from some existing
88309467b48Spatrick   // prototype.
88409467b48Spatrick   auto FI = FunctionProtos.find(Name);
88509467b48Spatrick   if (FI != FunctionProtos.end())
88609467b48Spatrick     return FI->second->codegen();
88709467b48Spatrick 
88809467b48Spatrick   // If no existing prototype exists, return null.
88909467b48Spatrick   return nullptr;
89009467b48Spatrick }
89109467b48Spatrick 
89209467b48Spatrick /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
89309467b48Spatrick /// the function.  This is used for mutable variables etc.
CreateEntryBlockAlloca(Function * TheFunction,StringRef VarName)89409467b48Spatrick static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
895097a140dSpatrick                                           StringRef VarName) {
89609467b48Spatrick   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
89709467b48Spatrick                    TheFunction->getEntryBlock().begin());
89873471bf0Spatrick   return TmpB.CreateAlloca(Type::getDoubleTy(*TheContext), nullptr, VarName);
89909467b48Spatrick }
90009467b48Spatrick 
codegen()90109467b48Spatrick Value *NumberExprAST::codegen() {
90209467b48Spatrick   KSDbgInfo.emitLocation(this);
90373471bf0Spatrick   return ConstantFP::get(*TheContext, APFloat(Val));
90409467b48Spatrick }
90509467b48Spatrick 
codegen()90609467b48Spatrick Value *VariableExprAST::codegen() {
90709467b48Spatrick   // Look this variable up in the function.
90809467b48Spatrick   Value *V = NamedValues[Name];
90909467b48Spatrick   if (!V)
91009467b48Spatrick     return LogErrorV("Unknown variable name");
91109467b48Spatrick 
91209467b48Spatrick   KSDbgInfo.emitLocation(this);
91309467b48Spatrick   // Load the value.
91473471bf0Spatrick   return Builder->CreateLoad(Type::getDoubleTy(*TheContext), V, Name.c_str());
91509467b48Spatrick }
91609467b48Spatrick 
codegen()91709467b48Spatrick Value *UnaryExprAST::codegen() {
91809467b48Spatrick   Value *OperandV = Operand->codegen();
91909467b48Spatrick   if (!OperandV)
92009467b48Spatrick     return nullptr;
92109467b48Spatrick 
92209467b48Spatrick   Function *F = getFunction(std::string("unary") + Opcode);
92309467b48Spatrick   if (!F)
92409467b48Spatrick     return LogErrorV("Unknown unary operator");
92509467b48Spatrick 
92609467b48Spatrick   KSDbgInfo.emitLocation(this);
92773471bf0Spatrick   return Builder->CreateCall(F, OperandV, "unop");
92809467b48Spatrick }
92909467b48Spatrick 
codegen()93009467b48Spatrick Value *BinaryExprAST::codegen() {
93109467b48Spatrick   KSDbgInfo.emitLocation(this);
93209467b48Spatrick 
93309467b48Spatrick   // Special case '=' because we don't want to emit the LHS as an expression.
93409467b48Spatrick   if (Op == '=') {
93509467b48Spatrick     // Assignment requires the LHS to be an identifier.
93609467b48Spatrick     // This assume we're building without RTTI because LLVM builds that way by
93709467b48Spatrick     // default.  If you build LLVM with RTTI this can be changed to a
93809467b48Spatrick     // dynamic_cast for automatic error checking.
93909467b48Spatrick     VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS.get());
94009467b48Spatrick     if (!LHSE)
94109467b48Spatrick       return LogErrorV("destination of '=' must be a variable");
94209467b48Spatrick     // Codegen the RHS.
94309467b48Spatrick     Value *Val = RHS->codegen();
94409467b48Spatrick     if (!Val)
94509467b48Spatrick       return nullptr;
94609467b48Spatrick 
94709467b48Spatrick     // Look up the name.
94809467b48Spatrick     Value *Variable = NamedValues[LHSE->getName()];
94909467b48Spatrick     if (!Variable)
95009467b48Spatrick       return LogErrorV("Unknown variable name");
95109467b48Spatrick 
95273471bf0Spatrick     Builder->CreateStore(Val, Variable);
95309467b48Spatrick     return Val;
95409467b48Spatrick   }
95509467b48Spatrick 
95609467b48Spatrick   Value *L = LHS->codegen();
95709467b48Spatrick   Value *R = RHS->codegen();
95809467b48Spatrick   if (!L || !R)
95909467b48Spatrick     return nullptr;
96009467b48Spatrick 
96109467b48Spatrick   switch (Op) {
96209467b48Spatrick   case '+':
96373471bf0Spatrick     return Builder->CreateFAdd(L, R, "addtmp");
96409467b48Spatrick   case '-':
96573471bf0Spatrick     return Builder->CreateFSub(L, R, "subtmp");
96609467b48Spatrick   case '*':
96773471bf0Spatrick     return Builder->CreateFMul(L, R, "multmp");
96809467b48Spatrick   case '<':
96973471bf0Spatrick     L = Builder->CreateFCmpULT(L, R, "cmptmp");
97009467b48Spatrick     // Convert bool 0/1 to double 0.0 or 1.0
97173471bf0Spatrick     return Builder->CreateUIToFP(L, Type::getDoubleTy(*TheContext), "booltmp");
97209467b48Spatrick   default:
97309467b48Spatrick     break;
97409467b48Spatrick   }
97509467b48Spatrick 
97609467b48Spatrick   // If it wasn't a builtin binary operator, it must be a user defined one. Emit
97709467b48Spatrick   // a call to it.
97809467b48Spatrick   Function *F = getFunction(std::string("binary") + Op);
97909467b48Spatrick   assert(F && "binary operator not found!");
98009467b48Spatrick 
98109467b48Spatrick   Value *Ops[] = {L, R};
98273471bf0Spatrick   return Builder->CreateCall(F, Ops, "binop");
98309467b48Spatrick }
98409467b48Spatrick 
codegen()98509467b48Spatrick Value *CallExprAST::codegen() {
98609467b48Spatrick   KSDbgInfo.emitLocation(this);
98709467b48Spatrick 
98809467b48Spatrick   // Look up the name in the global module table.
98909467b48Spatrick   Function *CalleeF = getFunction(Callee);
99009467b48Spatrick   if (!CalleeF)
99109467b48Spatrick     return LogErrorV("Unknown function referenced");
99209467b48Spatrick 
99309467b48Spatrick   // If argument mismatch error.
99409467b48Spatrick   if (CalleeF->arg_size() != Args.size())
99509467b48Spatrick     return LogErrorV("Incorrect # arguments passed");
99609467b48Spatrick 
99709467b48Spatrick   std::vector<Value *> ArgsV;
99809467b48Spatrick   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
99909467b48Spatrick     ArgsV.push_back(Args[i]->codegen());
100009467b48Spatrick     if (!ArgsV.back())
100109467b48Spatrick       return nullptr;
100209467b48Spatrick   }
100309467b48Spatrick 
100473471bf0Spatrick   return Builder->CreateCall(CalleeF, ArgsV, "calltmp");
100509467b48Spatrick }
100609467b48Spatrick 
codegen()100709467b48Spatrick Value *IfExprAST::codegen() {
100809467b48Spatrick   KSDbgInfo.emitLocation(this);
100909467b48Spatrick 
101009467b48Spatrick   Value *CondV = Cond->codegen();
101109467b48Spatrick   if (!CondV)
101209467b48Spatrick     return nullptr;
101309467b48Spatrick 
101409467b48Spatrick   // Convert condition to a bool by comparing non-equal to 0.0.
101573471bf0Spatrick   CondV = Builder->CreateFCmpONE(
101673471bf0Spatrick       CondV, ConstantFP::get(*TheContext, APFloat(0.0)), "ifcond");
101709467b48Spatrick 
101873471bf0Spatrick   Function *TheFunction = Builder->GetInsertBlock()->getParent();
101909467b48Spatrick 
102009467b48Spatrick   // Create blocks for the then and else cases.  Insert the 'then' block at the
102109467b48Spatrick   // end of the function.
102273471bf0Spatrick   BasicBlock *ThenBB = BasicBlock::Create(*TheContext, "then", TheFunction);
102373471bf0Spatrick   BasicBlock *ElseBB = BasicBlock::Create(*TheContext, "else");
102473471bf0Spatrick   BasicBlock *MergeBB = BasicBlock::Create(*TheContext, "ifcont");
102509467b48Spatrick 
102673471bf0Spatrick   Builder->CreateCondBr(CondV, ThenBB, ElseBB);
102709467b48Spatrick 
102809467b48Spatrick   // Emit then value.
102973471bf0Spatrick   Builder->SetInsertPoint(ThenBB);
103009467b48Spatrick 
103109467b48Spatrick   Value *ThenV = Then->codegen();
103209467b48Spatrick   if (!ThenV)
103309467b48Spatrick     return nullptr;
103409467b48Spatrick 
103573471bf0Spatrick   Builder->CreateBr(MergeBB);
103609467b48Spatrick   // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
103773471bf0Spatrick   ThenBB = Builder->GetInsertBlock();
103809467b48Spatrick 
103909467b48Spatrick   // Emit else block.
1040*d415bd75Srobert   TheFunction->insert(TheFunction->end(), ElseBB);
104173471bf0Spatrick   Builder->SetInsertPoint(ElseBB);
104209467b48Spatrick 
104309467b48Spatrick   Value *ElseV = Else->codegen();
104409467b48Spatrick   if (!ElseV)
104509467b48Spatrick     return nullptr;
104609467b48Spatrick 
104773471bf0Spatrick   Builder->CreateBr(MergeBB);
104809467b48Spatrick   // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
104973471bf0Spatrick   ElseBB = Builder->GetInsertBlock();
105009467b48Spatrick 
105109467b48Spatrick   // Emit merge block.
1052*d415bd75Srobert   TheFunction->insert(TheFunction->end(), MergeBB);
105373471bf0Spatrick   Builder->SetInsertPoint(MergeBB);
105473471bf0Spatrick   PHINode *PN = Builder->CreatePHI(Type::getDoubleTy(*TheContext), 2, "iftmp");
105509467b48Spatrick 
105609467b48Spatrick   PN->addIncoming(ThenV, ThenBB);
105709467b48Spatrick   PN->addIncoming(ElseV, ElseBB);
105809467b48Spatrick   return PN;
105909467b48Spatrick }
106009467b48Spatrick 
106109467b48Spatrick // Output for-loop as:
106209467b48Spatrick //   var = alloca double
106309467b48Spatrick //   ...
106409467b48Spatrick //   start = startexpr
106509467b48Spatrick //   store start -> var
106609467b48Spatrick //   goto loop
106709467b48Spatrick // loop:
106809467b48Spatrick //   ...
106909467b48Spatrick //   bodyexpr
107009467b48Spatrick //   ...
107109467b48Spatrick // loopend:
107209467b48Spatrick //   step = stepexpr
107309467b48Spatrick //   endcond = endexpr
107409467b48Spatrick //
107509467b48Spatrick //   curvar = load var
107609467b48Spatrick //   nextvar = curvar + step
107709467b48Spatrick //   store nextvar -> var
107809467b48Spatrick //   br endcond, loop, endloop
107909467b48Spatrick // outloop:
codegen()108009467b48Spatrick Value *ForExprAST::codegen() {
108173471bf0Spatrick   Function *TheFunction = Builder->GetInsertBlock()->getParent();
108209467b48Spatrick 
108309467b48Spatrick   // Create an alloca for the variable in the entry block.
108409467b48Spatrick   AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
108509467b48Spatrick 
108609467b48Spatrick   KSDbgInfo.emitLocation(this);
108709467b48Spatrick 
108809467b48Spatrick   // Emit the start code first, without 'variable' in scope.
108909467b48Spatrick   Value *StartVal = Start->codegen();
109009467b48Spatrick   if (!StartVal)
109109467b48Spatrick     return nullptr;
109209467b48Spatrick 
109309467b48Spatrick   // Store the value into the alloca.
109473471bf0Spatrick   Builder->CreateStore(StartVal, Alloca);
109509467b48Spatrick 
109609467b48Spatrick   // Make the new basic block for the loop header, inserting after current
109709467b48Spatrick   // block.
109873471bf0Spatrick   BasicBlock *LoopBB = BasicBlock::Create(*TheContext, "loop", TheFunction);
109909467b48Spatrick 
110009467b48Spatrick   // Insert an explicit fall through from the current block to the LoopBB.
110173471bf0Spatrick   Builder->CreateBr(LoopBB);
110209467b48Spatrick 
110309467b48Spatrick   // Start insertion in LoopBB.
110473471bf0Spatrick   Builder->SetInsertPoint(LoopBB);
110509467b48Spatrick 
110609467b48Spatrick   // Within the loop, the variable is defined equal to the PHI node.  If it
110709467b48Spatrick   // shadows an existing variable, we have to restore it, so save it now.
110809467b48Spatrick   AllocaInst *OldVal = NamedValues[VarName];
110909467b48Spatrick   NamedValues[VarName] = Alloca;
111009467b48Spatrick 
111109467b48Spatrick   // Emit the body of the loop.  This, like any other expr, can change the
111209467b48Spatrick   // current BB.  Note that we ignore the value computed by the body, but don't
111309467b48Spatrick   // allow an error.
111409467b48Spatrick   if (!Body->codegen())
111509467b48Spatrick     return nullptr;
111609467b48Spatrick 
111709467b48Spatrick   // Emit the step value.
111809467b48Spatrick   Value *StepVal = nullptr;
111909467b48Spatrick   if (Step) {
112009467b48Spatrick     StepVal = Step->codegen();
112109467b48Spatrick     if (!StepVal)
112209467b48Spatrick       return nullptr;
112309467b48Spatrick   } else {
112409467b48Spatrick     // If not specified, use 1.0.
112573471bf0Spatrick     StepVal = ConstantFP::get(*TheContext, APFloat(1.0));
112609467b48Spatrick   }
112709467b48Spatrick 
112809467b48Spatrick   // Compute the end condition.
112909467b48Spatrick   Value *EndCond = End->codegen();
113009467b48Spatrick   if (!EndCond)
113109467b48Spatrick     return nullptr;
113209467b48Spatrick 
113309467b48Spatrick   // Reload, increment, and restore the alloca.  This handles the case where
113409467b48Spatrick   // the body of the loop mutates the variable.
113573471bf0Spatrick   Value *CurVar = Builder->CreateLoad(Type::getDoubleTy(*TheContext), Alloca,
113673471bf0Spatrick                                       VarName.c_str());
113773471bf0Spatrick   Value *NextVar = Builder->CreateFAdd(CurVar, StepVal, "nextvar");
113873471bf0Spatrick   Builder->CreateStore(NextVar, Alloca);
113909467b48Spatrick 
114009467b48Spatrick   // Convert condition to a bool by comparing non-equal to 0.0.
114173471bf0Spatrick   EndCond = Builder->CreateFCmpONE(
114273471bf0Spatrick       EndCond, ConstantFP::get(*TheContext, APFloat(0.0)), "loopcond");
114309467b48Spatrick 
114409467b48Spatrick   // Create the "after loop" block and insert it.
114509467b48Spatrick   BasicBlock *AfterBB =
114673471bf0Spatrick       BasicBlock::Create(*TheContext, "afterloop", TheFunction);
114709467b48Spatrick 
114809467b48Spatrick   // Insert the conditional branch into the end of LoopEndBB.
114973471bf0Spatrick   Builder->CreateCondBr(EndCond, LoopBB, AfterBB);
115009467b48Spatrick 
115109467b48Spatrick   // Any new code will be inserted in AfterBB.
115273471bf0Spatrick   Builder->SetInsertPoint(AfterBB);
115309467b48Spatrick 
115409467b48Spatrick   // Restore the unshadowed variable.
115509467b48Spatrick   if (OldVal)
115609467b48Spatrick     NamedValues[VarName] = OldVal;
115709467b48Spatrick   else
115809467b48Spatrick     NamedValues.erase(VarName);
115909467b48Spatrick 
116009467b48Spatrick   // for expr always returns 0.0.
116173471bf0Spatrick   return Constant::getNullValue(Type::getDoubleTy(*TheContext));
116209467b48Spatrick }
116309467b48Spatrick 
codegen()116409467b48Spatrick Value *VarExprAST::codegen() {
116509467b48Spatrick   std::vector<AllocaInst *> OldBindings;
116609467b48Spatrick 
116773471bf0Spatrick   Function *TheFunction = Builder->GetInsertBlock()->getParent();
116809467b48Spatrick 
116909467b48Spatrick   // Register all variables and emit their initializer.
117009467b48Spatrick   for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
117109467b48Spatrick     const std::string &VarName = VarNames[i].first;
117209467b48Spatrick     ExprAST *Init = VarNames[i].second.get();
117309467b48Spatrick 
117409467b48Spatrick     // Emit the initializer before adding the variable to scope, this prevents
117509467b48Spatrick     // the initializer from referencing the variable itself, and permits stuff
117609467b48Spatrick     // like this:
117709467b48Spatrick     //  var a = 1 in
117809467b48Spatrick     //    var a = a in ...   # refers to outer 'a'.
117909467b48Spatrick     Value *InitVal;
118009467b48Spatrick     if (Init) {
118109467b48Spatrick       InitVal = Init->codegen();
118209467b48Spatrick       if (!InitVal)
118309467b48Spatrick         return nullptr;
118409467b48Spatrick     } else { // If not specified, use 0.0.
118573471bf0Spatrick       InitVal = ConstantFP::get(*TheContext, APFloat(0.0));
118609467b48Spatrick     }
118709467b48Spatrick 
118809467b48Spatrick     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
118973471bf0Spatrick     Builder->CreateStore(InitVal, Alloca);
119009467b48Spatrick 
119109467b48Spatrick     // Remember the old variable binding so that we can restore the binding when
119209467b48Spatrick     // we unrecurse.
119309467b48Spatrick     OldBindings.push_back(NamedValues[VarName]);
119409467b48Spatrick 
119509467b48Spatrick     // Remember this binding.
119609467b48Spatrick     NamedValues[VarName] = Alloca;
119709467b48Spatrick   }
119809467b48Spatrick 
119909467b48Spatrick   KSDbgInfo.emitLocation(this);
120009467b48Spatrick 
120109467b48Spatrick   // Codegen the body, now that all vars are in scope.
120209467b48Spatrick   Value *BodyVal = Body->codegen();
120309467b48Spatrick   if (!BodyVal)
120409467b48Spatrick     return nullptr;
120509467b48Spatrick 
120609467b48Spatrick   // Pop all our variables from scope.
120709467b48Spatrick   for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
120809467b48Spatrick     NamedValues[VarNames[i].first] = OldBindings[i];
120909467b48Spatrick 
121009467b48Spatrick   // Return the body computation.
121109467b48Spatrick   return BodyVal;
121209467b48Spatrick }
121309467b48Spatrick 
codegen()121409467b48Spatrick Function *PrototypeAST::codegen() {
121509467b48Spatrick   // Make the function type:  double(double,double) etc.
121673471bf0Spatrick   std::vector<Type *> Doubles(Args.size(), Type::getDoubleTy(*TheContext));
121709467b48Spatrick   FunctionType *FT =
121873471bf0Spatrick       FunctionType::get(Type::getDoubleTy(*TheContext), Doubles, false);
121909467b48Spatrick 
122009467b48Spatrick   Function *F =
122109467b48Spatrick       Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
122209467b48Spatrick 
122309467b48Spatrick   // Set names for all arguments.
122409467b48Spatrick   unsigned Idx = 0;
122509467b48Spatrick   for (auto &Arg : F->args())
122609467b48Spatrick     Arg.setName(Args[Idx++]);
122709467b48Spatrick 
122809467b48Spatrick   return F;
122909467b48Spatrick }
123009467b48Spatrick 
codegen()123109467b48Spatrick Function *FunctionAST::codegen() {
123209467b48Spatrick   // Transfer ownership of the prototype to the FunctionProtos map, but keep a
123309467b48Spatrick   // reference to it for use below.
123409467b48Spatrick   auto &P = *Proto;
123509467b48Spatrick   FunctionProtos[Proto->getName()] = std::move(Proto);
123609467b48Spatrick   Function *TheFunction = getFunction(P.getName());
123709467b48Spatrick   if (!TheFunction)
123809467b48Spatrick     return nullptr;
123909467b48Spatrick 
124009467b48Spatrick   // If this is an operator, install it.
124109467b48Spatrick   if (P.isBinaryOp())
124209467b48Spatrick     BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
124309467b48Spatrick 
124409467b48Spatrick   // Create a new basic block to start insertion into.
124573471bf0Spatrick   BasicBlock *BB = BasicBlock::Create(*TheContext, "entry", TheFunction);
124673471bf0Spatrick   Builder->SetInsertPoint(BB);
124709467b48Spatrick 
124809467b48Spatrick   // Create a subprogram DIE for this function.
124909467b48Spatrick   DIFile *Unit = DBuilder->createFile(KSDbgInfo.TheCU->getFilename(),
125009467b48Spatrick                                       KSDbgInfo.TheCU->getDirectory());
125109467b48Spatrick   DIScope *FContext = Unit;
125209467b48Spatrick   unsigned LineNo = P.getLine();
125309467b48Spatrick   unsigned ScopeLine = LineNo;
125409467b48Spatrick   DISubprogram *SP = DBuilder->createFunction(
125509467b48Spatrick       FContext, P.getName(), StringRef(), Unit, LineNo,
1256*d415bd75Srobert       CreateFunctionType(TheFunction->arg_size()), ScopeLine,
125709467b48Spatrick       DINode::FlagPrototyped, DISubprogram::SPFlagDefinition);
125809467b48Spatrick   TheFunction->setSubprogram(SP);
125909467b48Spatrick 
126009467b48Spatrick   // Push the current scope.
126109467b48Spatrick   KSDbgInfo.LexicalBlocks.push_back(SP);
126209467b48Spatrick 
126309467b48Spatrick   // Unset the location for the prologue emission (leading instructions with no
126409467b48Spatrick   // location in a function are considered part of the prologue and the debugger
126509467b48Spatrick   // will run past them when breaking on a function)
126609467b48Spatrick   KSDbgInfo.emitLocation(nullptr);
126709467b48Spatrick 
126809467b48Spatrick   // Record the function arguments in the NamedValues map.
126909467b48Spatrick   NamedValues.clear();
127009467b48Spatrick   unsigned ArgIdx = 0;
127109467b48Spatrick   for (auto &Arg : TheFunction->args()) {
127209467b48Spatrick     // Create an alloca for this variable.
127309467b48Spatrick     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
127409467b48Spatrick 
127509467b48Spatrick     // Create a debug descriptor for the variable.
127609467b48Spatrick     DILocalVariable *D = DBuilder->createParameterVariable(
127709467b48Spatrick         SP, Arg.getName(), ++ArgIdx, Unit, LineNo, KSDbgInfo.getDoubleTy(),
127809467b48Spatrick         true);
127909467b48Spatrick 
128009467b48Spatrick     DBuilder->insertDeclare(Alloca, D, DBuilder->createExpression(),
128173471bf0Spatrick                             DILocation::get(SP->getContext(), LineNo, 0, SP),
128273471bf0Spatrick                             Builder->GetInsertBlock());
128309467b48Spatrick 
128409467b48Spatrick     // Store the initial value into the alloca.
128573471bf0Spatrick     Builder->CreateStore(&Arg, Alloca);
128609467b48Spatrick 
128709467b48Spatrick     // Add arguments to variable symbol table.
1288097a140dSpatrick     NamedValues[std::string(Arg.getName())] = Alloca;
128909467b48Spatrick   }
129009467b48Spatrick 
129109467b48Spatrick   KSDbgInfo.emitLocation(Body.get());
129209467b48Spatrick 
129309467b48Spatrick   if (Value *RetVal = Body->codegen()) {
129409467b48Spatrick     // Finish off the function.
129573471bf0Spatrick     Builder->CreateRet(RetVal);
129609467b48Spatrick 
129709467b48Spatrick     // Pop off the lexical block for the function.
129809467b48Spatrick     KSDbgInfo.LexicalBlocks.pop_back();
129909467b48Spatrick 
130009467b48Spatrick     // Validate the generated code, checking for consistency.
130109467b48Spatrick     verifyFunction(*TheFunction);
130209467b48Spatrick 
130309467b48Spatrick     return TheFunction;
130409467b48Spatrick   }
130509467b48Spatrick 
130609467b48Spatrick   // Error reading body, remove function.
130709467b48Spatrick   TheFunction->eraseFromParent();
130809467b48Spatrick 
130909467b48Spatrick   if (P.isBinaryOp())
131009467b48Spatrick     BinopPrecedence.erase(Proto->getOperatorName());
131109467b48Spatrick 
131209467b48Spatrick   // Pop off the lexical block for the function since we added it
131309467b48Spatrick   // unconditionally.
131409467b48Spatrick   KSDbgInfo.LexicalBlocks.pop_back();
131509467b48Spatrick 
131609467b48Spatrick   return nullptr;
131709467b48Spatrick }
131809467b48Spatrick 
131909467b48Spatrick //===----------------------------------------------------------------------===//
132009467b48Spatrick // Top-Level parsing and JIT Driver
132109467b48Spatrick //===----------------------------------------------------------------------===//
132209467b48Spatrick 
InitializeModule()132309467b48Spatrick static void InitializeModule() {
132409467b48Spatrick   // Open a new module.
132573471bf0Spatrick   TheContext = std::make_unique<LLVMContext>();
132673471bf0Spatrick   TheModule = std::make_unique<Module>("my cool jit", *TheContext);
132773471bf0Spatrick   TheModule->setDataLayout(TheJIT->getDataLayout());
132873471bf0Spatrick 
132973471bf0Spatrick   Builder = std::make_unique<IRBuilder<>>(*TheContext);
133009467b48Spatrick }
133109467b48Spatrick 
HandleDefinition()133209467b48Spatrick static void HandleDefinition() {
133309467b48Spatrick   if (auto FnAST = ParseDefinition()) {
133409467b48Spatrick     if (!FnAST->codegen())
133509467b48Spatrick       fprintf(stderr, "Error reading function definition:");
133609467b48Spatrick   } else {
133709467b48Spatrick     // Skip token for error recovery.
133809467b48Spatrick     getNextToken();
133909467b48Spatrick   }
134009467b48Spatrick }
134109467b48Spatrick 
HandleExtern()134209467b48Spatrick static void HandleExtern() {
134309467b48Spatrick   if (auto ProtoAST = ParseExtern()) {
134409467b48Spatrick     if (!ProtoAST->codegen())
134509467b48Spatrick       fprintf(stderr, "Error reading extern");
134609467b48Spatrick     else
134709467b48Spatrick       FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
134809467b48Spatrick   } else {
134909467b48Spatrick     // Skip token for error recovery.
135009467b48Spatrick     getNextToken();
135109467b48Spatrick   }
135209467b48Spatrick }
135309467b48Spatrick 
HandleTopLevelExpression()135409467b48Spatrick static void HandleTopLevelExpression() {
135509467b48Spatrick   // Evaluate a top-level expression into an anonymous function.
135609467b48Spatrick   if (auto FnAST = ParseTopLevelExpr()) {
135709467b48Spatrick     if (!FnAST->codegen()) {
135809467b48Spatrick       fprintf(stderr, "Error generating code for top level expr");
135909467b48Spatrick     }
136009467b48Spatrick   } else {
136109467b48Spatrick     // Skip token for error recovery.
136209467b48Spatrick     getNextToken();
136309467b48Spatrick   }
136409467b48Spatrick }
136509467b48Spatrick 
136609467b48Spatrick /// top ::= definition | external | expression | ';'
MainLoop()136709467b48Spatrick static void MainLoop() {
1368*d415bd75Srobert   while (true) {
136909467b48Spatrick     switch (CurTok) {
137009467b48Spatrick     case tok_eof:
137109467b48Spatrick       return;
137209467b48Spatrick     case ';': // ignore top-level semicolons.
137309467b48Spatrick       getNextToken();
137409467b48Spatrick       break;
137509467b48Spatrick     case tok_def:
137609467b48Spatrick       HandleDefinition();
137709467b48Spatrick       break;
137809467b48Spatrick     case tok_extern:
137909467b48Spatrick       HandleExtern();
138009467b48Spatrick       break;
138109467b48Spatrick     default:
138209467b48Spatrick       HandleTopLevelExpression();
138309467b48Spatrick       break;
138409467b48Spatrick     }
138509467b48Spatrick   }
138609467b48Spatrick }
138709467b48Spatrick 
138809467b48Spatrick //===----------------------------------------------------------------------===//
138909467b48Spatrick // "Library" functions that can be "extern'd" from user code.
139009467b48Spatrick //===----------------------------------------------------------------------===//
139109467b48Spatrick 
139209467b48Spatrick #ifdef _WIN32
139309467b48Spatrick #define DLLEXPORT __declspec(dllexport)
139409467b48Spatrick #else
139509467b48Spatrick #define DLLEXPORT
139609467b48Spatrick #endif
139709467b48Spatrick 
139809467b48Spatrick /// putchard - putchar that takes a double and returns 0.
putchard(double X)139909467b48Spatrick extern "C" DLLEXPORT double putchard(double X) {
140009467b48Spatrick   fputc((char)X, stderr);
140109467b48Spatrick   return 0;
140209467b48Spatrick }
140309467b48Spatrick 
140409467b48Spatrick /// printd - printf that takes a double prints it as "%f\n", returning 0.
printd(double X)140509467b48Spatrick extern "C" DLLEXPORT double printd(double X) {
140609467b48Spatrick   fprintf(stderr, "%f\n", X);
140709467b48Spatrick   return 0;
140809467b48Spatrick }
140909467b48Spatrick 
141009467b48Spatrick //===----------------------------------------------------------------------===//
141109467b48Spatrick // Main driver code.
141209467b48Spatrick //===----------------------------------------------------------------------===//
141309467b48Spatrick 
main()141409467b48Spatrick int main() {
141509467b48Spatrick   InitializeNativeTarget();
141609467b48Spatrick   InitializeNativeTargetAsmPrinter();
141709467b48Spatrick   InitializeNativeTargetAsmParser();
141809467b48Spatrick 
141909467b48Spatrick   // Install standard binary operators.
142009467b48Spatrick   // 1 is lowest precedence.
142109467b48Spatrick   BinopPrecedence['='] = 2;
142209467b48Spatrick   BinopPrecedence['<'] = 10;
142309467b48Spatrick   BinopPrecedence['+'] = 20;
142409467b48Spatrick   BinopPrecedence['-'] = 20;
142509467b48Spatrick   BinopPrecedence['*'] = 40; // highest.
142609467b48Spatrick 
142709467b48Spatrick   // Prime the first token.
142809467b48Spatrick   getNextToken();
142909467b48Spatrick 
143073471bf0Spatrick   TheJIT = ExitOnErr(KaleidoscopeJIT::Create());
143109467b48Spatrick 
143209467b48Spatrick   InitializeModule();
143309467b48Spatrick 
143409467b48Spatrick   // Add the current debug info version into the module.
143509467b48Spatrick   TheModule->addModuleFlag(Module::Warning, "Debug Info Version",
143609467b48Spatrick                            DEBUG_METADATA_VERSION);
143709467b48Spatrick 
143809467b48Spatrick   // Darwin only supports dwarf2.
143909467b48Spatrick   if (Triple(sys::getProcessTriple()).isOSDarwin())
144009467b48Spatrick     TheModule->addModuleFlag(llvm::Module::Warning, "Dwarf Version", 2);
144109467b48Spatrick 
144209467b48Spatrick   // Construct the DIBuilder, we do this here because we need the module.
144309467b48Spatrick   DBuilder = std::make_unique<DIBuilder>(*TheModule);
144409467b48Spatrick 
144509467b48Spatrick   // Create the compile unit for the module.
144609467b48Spatrick   // Currently down as "fib.ks" as a filename since we're redirecting stdin
144709467b48Spatrick   // but we'd like actual source locations.
144809467b48Spatrick   KSDbgInfo.TheCU = DBuilder->createCompileUnit(
144909467b48Spatrick       dwarf::DW_LANG_C, DBuilder->createFile("fib.ks", "."),
1450*d415bd75Srobert       "Kaleidoscope Compiler", false, "", 0);
145109467b48Spatrick 
145209467b48Spatrick   // Run the main "interpreter loop" now.
145309467b48Spatrick   MainLoop();
145409467b48Spatrick 
145509467b48Spatrick   // Finalize the debug info.
145609467b48Spatrick   DBuilder->finalize();
145709467b48Spatrick 
145809467b48Spatrick   // Print out all of the generated code.
145909467b48Spatrick   TheModule->print(errs(), nullptr);
146009467b48Spatrick 
146109467b48Spatrick   return 0;
146209467b48Spatrick }
1463