Chapter6.cpp 29 KB

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