{"id":29,"date":"2020-08-13T12:05:42","date_gmt":"2020-08-13T04:05:42","guid":{"rendered":"http:\/\/47.108.144.50\/?p=29"},"modified":"2020-08-13T20:37:49","modified_gmt":"2020-08-13T12:37:49","slug":"llvm%e5%ae%98%e6%96%b9%e4%b8%87%e8%8a%b1%e7%ad%92%e6%95%99%e7%a8%8b2-%e4%ba%a7%e7%94%9fllvm%e4%b8%ad%e9%97%b4%e4%bb%a3%e7%a0%81","status":"publish","type":"post","link":"http:\/\/pareto.fun\/?p=29","title":{"rendered":"llvm\u524d\u7aef-\u5b98\u65b9\u4e07\u82b1\u7b52\u6559\u7a0b2-\u4ea7\u751fllvm\u4e2d\u95f4\u4ee3\u7801"},"content":{"rendered":"\n<p><strong>\u82f1\u6587\u770b\u591a\u4e86\u8fd8\u662f\u5934\u75db\uff0c\u8fd8\u662f\u76f4\u63a5\u4e0a\u4ee3\u7801<\/strong><\/p>\n\n\n\n<p>\u4ee3\u7801\u76f8\u6bd4\u4e8e\u4e0a\u4e00\u7bc7\u4e3a\u6bcf\u4e2a\u8bed\u6cd5\u6811\u65b0\u589e\u4e86\u751f\u6210\u6307\u4ee4\u7684\u51fd\u6570codegen\uff0c\u5e76\u4e14\u65b0\u589e\u4e86\u4e00\u4e9b\u5168\u5c40\u53d8\u91cf\u3002<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">static LLVMContext TheContext;<br>static IRBuilder&lt;&gt; Builder(TheContext);<br>static std::unique_ptr&lt;Module&gt; TheModule;<br>static std::map&lt;std::string, Value *&gt; NamedValues;<\/pre>\n\n\n\n<p>TheContext \u8fd9\u662f\u4e2a\u795e\u5947\u7684\u53d8\u91cf\uff0c\u5f88\u591a\u51fd\u6570\u53c2\u6570\u90fd\u8981\u7528\u5b83\uff0c\u5b98\u65b9\u89e3\u91ca\u8bf4\u8fd9\u4e2a\u5bf9\u8c61\u6709llvm\u7edd\u5927\u591a\u6570\u7684\u6570\u636e\u7ed3\u6784\uff0c\u7c7b\u578b\u548c\u5e38\u91cf\u8868\u3002<\/p>\n\n\n\n<p>Builder \u4e00\u4e2a\u751f\u6210IR\u6307\u4ee4\u7684\u8f85\u52a9\u7c7b\u3002<\/p>\n\n\n\n<p>TheModule \u6240\u6709\u751f\u6210\u7684\u6307\u4ee4\u90fd\u4f1a\u653e\u5728\u8fd9\u91cc\u3002<\/p>\n\n\n\n<p>NameValues \u5c31\u5f53\u4f5c\u4e00\u4e2a\u7b26\u53f7\u8868\uff0c\u53d1\u751f\u51fd\u6570\u8c03\u7528\u65f6\u5176\u4e2d\u7684\u53c2\u6570\u5c31\u4f1a\u4ece\u8fd9\u627e\u3002<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Value *NumberExprAST::codegen() {<br>  return ConstantFP::get(TheContext, APFloat(Val));<br>}<br>\u200b<br>Value *VariableExprAST::codegen() {<br>  \/\/ Look this variable up in the function.<br>  Value *V = NamedValues[Name];<br>  if (!V)<br> &nbsp;  LogErrorV(\"Unknown variable name\");<br>  return V;<br>}<\/pre>\n\n\n\n<p>\u5b9e\u9645\u4e0a\uff0cNumberExprAST\u548cVariableExprAST\u7684codegen\u65b9\u6cd5\u90fd\u4e0d\u4ea7\u751fIR\u6307\u4ee4\uff0c\u4ec5\u4e3a\u4e0a\u5c42\u7684\u6307\u4ee4\u63d0\u4f9b\u5bf9\u8c61\uff0c\u60f3\u60f3\u4e5f\u89c9\u5f97\u5408\u7406\uff0c\u6bd5\u7adf\u7eaf\u6570\u5b57\u548c\u6807\u8bc6\u7b26\u6ca1\u6709\u4efb\u4f55\u610f\u4e49\u3002<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Value *BinaryExprAST::codegen() {<br>  Value *L = LHS-&gt;codegen();<br>  Value *R = RHS-&gt;codegen();<br>  if (!L || !R)<br> &nbsp;  return nullptr;<br>\u200b<br>  switch (Op) {<br>  case '+':<br> &nbsp;  return Builder.CreateFAdd(L, R, \"addtmp\");<br>  case '-':<br> &nbsp;  return Builder.CreateFSub(L, R, \"subtmp\");<br>  case '*':<br> &nbsp;  return Builder.CreateFMul(L, R, \"multmp\");<br>  case '&lt;':<br> &nbsp;  L = Builder.CreateFCmpULT(L, R, \"cmptmp\");<br> &nbsp;  \/\/ Convert bool 0\/1 to double 0.0 or 1.0<br> &nbsp;  return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext),<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;  \"booltmp\");<br>  default:<br> &nbsp;  return LogErrorV(\"invalid binary operator\");<br>  }<br>}<\/pre>\n\n\n\n<p>\u4ee3\u7801\u7b80\u5355\u53d6\u51fa\u4e24\u4e2a\u64cd\u4f5c\u6570\uff0c\u6839\u636e\u5177\u4f53\u7684\u64cd\u4f5c\u7b26\u5229\u7528Builder\u6765\u751f\u6210\u6307\u4ee4\u3002Builder.CreateF(,,)\u7684\u7b2c\u4e09\u4e2a\u53c2\u6570\u662f\u751f\u6210\u6307\u4ee4\u4e2d\u53d8\u91cf\u7684\u540d\u79f0\u3002<\/p>\n\n\n\n<p>\u7279\u6b8a\u70b9\u7684\u5c31\u662f &#8216;&lt;&#8216; , \u6bd4\u8f83\u540e\u7684bool \u503c\u6216\u8005bool vector \u8f6c\u5316\u4e3a double\u3002<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Value *CallExprAST::codegen() {<br>  \/\/ Look up the name in the global module table.<br>  Function *CalleeF = TheModule-&gt;getFunction(Callee);<br>  if (!CalleeF)<br> &nbsp;  return LogErrorV(\"Unknown function referenced\");<br>\u200b<br>  \/\/ If argument mismatch error.<br>  if (CalleeF-&gt;arg_size() != Args.size())<br> &nbsp;  return LogErrorV(\"Incorrect # arguments passed\");<br>\u200b<br>  std::vector&lt;Value *&gt; ArgsV;<br>  for (unsigned i = 0, e = Args.size(); i != e; ++i) {<br> &nbsp;  ArgsV.push_back(Args[i]-&gt;codegen());<br> &nbsp;  if (!ArgsV.back())<br> &nbsp; &nbsp;  return nullptr;<br>  }<br>\u200b<br>  return Builder.CreateCall(CalleeF, ArgsV, \"calltmp\");<br>}<\/pre>\n\n\n\n<p>\u8fd9\u662f\u4ea7\u751f\u8c03\u7528\u51fd\u6570\u7684IR\uff0c\u5224\u65ad\u662f\u5426\u5df2\u7ecf\u5b9a\u4e49\u4e86\u51fd\u6570\uff0c\u5df2\u5b9a\u4e49\u5219\u5224\u65ad\u53c2\u6570\u4e2a\u6570\u662f\u5426\u76f8\u540c\uff0c\u76f8\u540c\u5219\u751f\u6210\u8c03\u7528\u6307\u4ee4\u3002<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Function *PrototypeAST::codegen() {<br>  \/\/ Make the function type:  double(double,double) etc.<br>  std::vector&lt;Type*&gt; Doubles(Args.size(),<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Type::getDoubleTy(TheContext));<br>  FunctionType *FT =<br> &nbsp;  FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);<br>\u200b<br>  Function *F =<br> &nbsp;  Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());<\/pre>\n\n\n\n<p>PrototypeAST \u4e3adef \u548cexternal \u670d\u52a1\uff0c\u662fFunctionAST\u7684\u6210\u5458\u4e4b\u4e00\uff0c\u8fd9\u6bb5\u4ee3\u7801\u662f\u4e3aFunctionAST-&gt;codegen\u505a\u94fa\u57ab\u3002\u8fd9\u4e2a\u51fd\u6570\u4e0e\u5176\u4ed6codegen\u51fd\u6570\u4e0d\u540c\u7684\u662f\u8fd4\u56defunction* \u4e0d\u662fvalues*\uff0c\u539f\u56e0\u5982\u4e0a\uff0c\u4e3adef \u548c external\u670d\u52a1\u3002\u7b2c\u4e00\u884c\u521b\u5efa\u4e3aArg.size() \u4e2adouble\u7684vector\u3002\u7b2c\u4e8c\u884c\u521b\u5efa\u4e86\u4f7f\u7528Arg.size()\u4e2adouble\u4f5c\u4e3a\u53c2\u6570\uff0c\u8fd4\u56de\u503c\u4e3adouble\u7684\u51fd\u6570\u7c7b\u578b\uff0c\u6700\u540e\u4e00\u884c\u521b\u5efa\u4e86\u51fd\u6570\u6307\u5b9a\u4e86\u51fd\u6570\u7c7b\u578b\u3001linkage\uff0c\u540d\u79f0\u548c\u63d2\u5165\u4ee3\u7801\u7684\u6a21\u5757\u3002\u8fd9\u91cc\u51fd\u6570\u662f\u6ca1\u6709\u51fd\u6570\u4f53\u7684\uff0c\u5c31\u662fllvm \u6765\u8868\u793a\u51fd\u6570\u5b9a\u4e49\u7684\u65b9\u6cd5\u3002\u5982\u679c\u662f\u4e00\u4e2aexternal\u51fd\u6570\u5230\u8fd9\u91cc\u5c31\u7ed3\u675f\u4e86\u3002\u4f46\u5bf9\u4e8e\u51fd\u6570\u5b9a\u4e49\u6211\u4eec\u9700\u8981\u51fd\u6570\u4f53\u3002<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Function *FunctionAST::codegen() {<br>  \/\/ First, check for an existing function from a previous 'extern' declaration.<br>  Function *TheFunction = TheModule-&gt;getFunction(Proto-&gt;getName());<br>\u200b<br>  if (!TheFunction)<br> &nbsp;  TheFunction = Proto-&gt;codegen();<br>\u200b<br>  if (!TheFunction)<br> &nbsp;  return nullptr;<br>\u200b<br>  \/\/ Create a new basic block to start insertion into.<br>  BasicBlock *BB = BasicBlock::Create(TheContext, \"entry\", TheFunction);<br>  Builder.SetInsertPoint(BB);<br>\u200b<br>  \/\/ Record the function arguments in the NamedValues map.<br>  NamedValues.clear();<br>  for (auto &amp;Arg : TheFunction-&gt;args())<br> &nbsp;  NamedValues[std::string(Arg.getName())] = &amp;Arg;<br>\u200b<br>  if (Value *RetVal = Body-&gt;codegen()) {<br> &nbsp;  \/\/ Finish off the function.<br> &nbsp;  Builder.CreateRet(RetVal);<br>\u200b<br> &nbsp;  \/\/ Validate the generated code, checking for consistency.<br> &nbsp;  verifyFunction(*TheFunction);<br>\u200b<br> &nbsp;  return TheFunction;<br>  }<br>\u200b<br>  \/\/ Error reading body, remove function.<br>  TheFunction-&gt;eraseFromParent();<br>  return nullptr;<br>}<\/pre>\n\n\n\n<p>\u5224\u65ad\u6a21\u5757\u4e2d\u662f\u5426\u5b9a\u4e49\u4e86\u51fd\u6570\uff0c\u672a\u5b9a\u4e49\u5219\u91cd\u65b0\u5b9a\u4e49\uff0cbody-&gt;codegen()\u751f\u6210\u51fd\u6570\u4f53\u7684\u8fd0\u7b97\u6267\u884c\uff0c\u5728\u751f\u6210ret\u6307\u4ee4\uff0c\u68c0\u67e5\u6307\u4ee4\u662f\u5426\u6b63\u5e38\uff0c\u8fd4\u56de\u51fd\u6570\u3002<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#include \"llvm\/ADT\/STLExtras.h\"<br>#include \"llvm\/IR\/BasicBlock.h\"<br>#include \"llvm\/IR\/Constants.h\"<br>#include \"llvm\/IR\/DerivedTypes.h\"<br>#include \"llvm\/IR\/Function.h\"<br>#include \"llvm\/IR\/IRBuilder.h\"<br>#include \"llvm\/IR\/LLVMContext.h\"<br>#include \"llvm\/IR\/Module.h\"<br>#include \"llvm\/IR\/Type.h\"<br>#include \"llvm\/IR\/Verifier.h\"<br>#include &lt;algorithm&gt;<br>#include &lt;cctype&gt;<br>#include &lt;cstdio&gt;<br>#include &lt;cstdlib&gt;<br>#include &lt;map&gt;<br>#include &lt;memory&gt;<br>#include &lt;string&gt;<br>#include &lt;vector&gt;<br>\u200b<br>using namespace llvm;<br>\u200b<br>\/\/===----------------------------------------------------------------------===\/\/<br>\/\/ Lexer<br>\/\/===----------------------------------------------------------------------===\/\/<br>\u200b<br>\/\/ The lexer returns tokens [0-255] if it is an unknown character, otherwise one<br>\/\/ of these for known things.<br>enum Token {<br>  tok_eof = -1,<br>\u200b<br>  \/\/ commands<br>  tok_def = -2,<br>  tok_extern = -3,<br>\u200b<br>  \/\/ primary<br>  tok_identifier = -4,<br>  tok_number = -5<br>};<br>\u200b<br>static std::string IdentifierStr; \/\/ Filled in if tok_identifier<br>static double NumVal; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; \/\/ Filled in if tok_number<br>\u200b<br>\/\/\/ gettok - Return the next token from standard input.<br>static int gettok() {<br>  static int LastChar = ' ';<br>\u200b<br>  \/\/ Skip any whitespace.<br>  while (isspace(LastChar))<br> &nbsp;  LastChar = getchar();<br>\u200b<br>  if (isalpha(LastChar)) { \/\/ identifier: [a-zA-Z][a-zA-Z0-9]*<br> &nbsp;  IdentifierStr = LastChar;<br> &nbsp;  while (isalnum((LastChar = getchar())))<br> &nbsp; &nbsp;  IdentifierStr += LastChar;<br>\u200b<br> &nbsp;  if (IdentifierStr == \"def\")<br> &nbsp; &nbsp;  return tok_def;<br> &nbsp;  if (IdentifierStr == \"extern\")<br> &nbsp; &nbsp;  return tok_extern;<br> &nbsp;  return tok_identifier;<br>  }<br>\u200b<br>  if (isdigit(LastChar) || LastChar == '.') { \/\/ Number: [0-9.]+<br> &nbsp;  std::string NumStr;<br> &nbsp;  do {<br> &nbsp; &nbsp;  NumStr += LastChar;<br> &nbsp; &nbsp;  LastChar = getchar();<br> &nbsp;  } while (isdigit(LastChar) || LastChar == '.');<br>\u200b<br> &nbsp;  NumVal = strtod(NumStr.c_str(), nullptr);<br> &nbsp;  return tok_number;<br>  }<br>\u200b<br>  if (LastChar == '#') {<br> &nbsp;  \/\/ Comment until end of line.<br> &nbsp;  do<br> &nbsp; &nbsp;  LastChar = getchar();<br> &nbsp;  while (LastChar != EOF &amp;&amp; LastChar != '\\n' &amp;&amp; LastChar != '\\r');<br>\u200b<br> &nbsp;  if (LastChar != EOF)<br> &nbsp; &nbsp;  return gettok();<br>  }<br>\u200b<br>  \/\/ Check for end of file.  Don't eat the EOF.<br>  if (LastChar == EOF)<br> &nbsp;  return tok_eof;<br>\u200b<br>  \/\/ Otherwise, just return the character as its ascii value.<br>  int ThisChar = LastChar;<br>  LastChar = getchar();<br>  return ThisChar;<br>}<br>\u200b<br>\/\/===----------------------------------------------------------------------===\/\/<br>\/\/ Abstract Syntax Tree (aka Parse Tree)<br>\/\/===----------------------------------------------------------------------===\/\/<br>\u200b<br>namespace {<br>\u200b<br>\/\/\/ ExprAST - Base class for all expression nodes.<br>class ExprAST {<br>public:<br>  virtual ~ExprAST() = default;<br>\u200b<br>  virtual Value *codegen() = 0;<br>};<br>\u200b<br>\/\/\/ NumberExprAST - Expression class for numeric literals like \"1.0\".<br>class NumberExprAST : public ExprAST {<br>  double Val;<br>\u200b<br>public:<br>  NumberExprAST(double Val) : Val(Val) {}<br>\u200b<br>  Value *codegen() override;<br>};<br>\u200b<br>\/\/\/ VariableExprAST - Expression class for referencing a variable, like \"a\".<br>class VariableExprAST : public ExprAST {<br>  std::string Name;<br>\u200b<br>public:<br>  VariableExprAST(const std::string &amp;Name) : Name(Name) {}<br>\u200b<br>  Value *codegen() override;<br>};<br>\u200b<br>\/\/\/ BinaryExprAST - Expression class for a binary operator.<br>class BinaryExprAST : public ExprAST {<br>  char Op;<br>  std::unique_ptr&lt;ExprAST&gt; LHS, RHS;<br>\u200b<br>public:<br>  BinaryExprAST(char Op, std::unique_ptr&lt;ExprAST&gt; LHS,<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;  std::unique_ptr&lt;ExprAST&gt; RHS)<br> &nbsp; &nbsp;  : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}<br>\u200b<br>  Value *codegen() override;<br>};<br>\u200b<br>\/\/\/ CallExprAST - Expression class for function calls.<br>class CallExprAST : public ExprAST {<br>  std::string Callee;<br>  std::vector&lt;std::unique_ptr&lt;ExprAST&gt;&gt; Args;<br>\u200b<br>public:<br>  CallExprAST(const std::string &amp;Callee,<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;  std::vector&lt;std::unique_ptr&lt;ExprAST&gt;&gt; Args)<br> &nbsp; &nbsp;  : Callee(Callee), Args(std::move(Args)) {}<br>\u200b<br>  Value *codegen() override;<br>};<br>\u200b<br>\/\/\/ PrototypeAST - This class represents the \"prototype\" for a function,<br>\/\/\/ which captures its name, and its argument names (thus implicitly the number<br>\/\/\/ of arguments the function takes).<br>class PrototypeAST {<br>  std::string Name;<br>  std::vector&lt;std::string&gt; Args;<br>\u200b<br>public:<br>  PrototypeAST(const std::string &amp;Name, std::vector&lt;std::string&gt; Args)<br> &nbsp; &nbsp;  : Name(Name), Args(std::move(Args)) {}<br>\u200b<br>  Function *codegen();<br>  const std::string &amp;getName() const { return Name; }<br>};<br>\u200b<br>\/\/\/ FunctionAST - This class represents a function definition itself.<br>class FunctionAST {<br>  std::unique_ptr&lt;PrototypeAST&gt; Proto;<br>  std::unique_ptr&lt;ExprAST&gt; Body;<br>\u200b<br>public:<br>  FunctionAST(std::unique_ptr&lt;PrototypeAST&gt; Proto,<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;  std::unique_ptr&lt;ExprAST&gt; Body)<br> &nbsp; &nbsp;  : Proto(std::move(Proto)), Body(std::move(Body)) {}<br>\u200b<br>  Function *codegen();<br>};<br>\u200b<br>} \/\/ end anonymous namespace<br>\u200b<br>\/\/===----------------------------------------------------------------------===\/\/<br>\/\/ Parser<br>\/\/===----------------------------------------------------------------------===\/\/<br>\u200b<br>\/\/\/ CurTok\/getNextToken - Provide a simple token buffer.  CurTok is the current<br>\/\/\/ token the parser is looking at.  getNextToken reads another token from the<br>\/\/\/ lexer and updates CurTok with its results.<br>static int CurTok;<br>static int getNextToken() { return CurTok = gettok(); }<br>\u200b<br>\/\/\/ BinopPrecedence - This holds the precedence for each binary operator that is<br>\/\/\/ defined.<br>static std::map&lt;char, int&gt; BinopPrecedence;<br>\u200b<br>\/\/\/ GetTokPrecedence - Get the precedence of the pending binary operator token.<br>static int GetTokPrecedence() {<br>  if (!isascii(CurTok))<br> &nbsp;  return -1;<br>\u200b<br>  \/\/ Make sure it's a declared binop.<br>  int TokPrec = BinopPrecedence[CurTok];<br>  if (TokPrec &lt;= 0)<br> &nbsp;  return -1;<br>  return TokPrec;<br>}<br>\u200b<br>\/\/\/ LogError* - These are little helper functions for error handling.<br>std::unique_ptr&lt;ExprAST&gt; LogError(const char *Str) {<br>  fprintf(stderr, \"Error: %s\\n\", Str);<br>  return nullptr;<br>}<br>\u200b<br>std::unique_ptr&lt;PrototypeAST&gt; LogErrorP(const char *Str) {<br>  LogError(Str);<br>  return nullptr;<br>}<br>\u200b<br>static std::unique_ptr&lt;ExprAST&gt; ParseExpression();<br>\u200b<br>\/\/\/ numberexpr ::= number<br>static std::unique_ptr&lt;ExprAST&gt; ParseNumberExpr() {<br>  auto Result = std::make_unique&lt;NumberExprAST&gt;(NumVal);<br>  getNextToken(); \/\/ consume the number<br>  return std::move(Result);<br>}<br>\u200b<br>\/\/\/ parenexpr ::= '(' expression ')'<br>static std::unique_ptr&lt;ExprAST&gt; ParseParenExpr() {<br>  getNextToken(); \/\/ eat (.<br>  auto V = ParseExpression();<br>  if (!V)<br> &nbsp;  return nullptr;<br>\u200b<br>  if (CurTok != ')')<br> &nbsp;  return LogError(\"expected ')'\");<br>  getNextToken(); \/\/ eat ).<br>  return V;<br>}<br>\u200b<br>\/\/\/ identifierexpr<br>\/\/\/ &nbsp; ::= identifier<br>\/\/\/ &nbsp; ::= identifier '(' expression* ')'<br>static std::unique_ptr&lt;ExprAST&gt; ParseIdentifierExpr() {<br>  std::string IdName = IdentifierStr;<br>\u200b<br>  getNextToken(); \/\/ eat identifier.<br>\u200b<br>  if (CurTok != '(') \/\/ Simple variable ref.<br> &nbsp;  return std::make_unique&lt;VariableExprAST&gt;(IdName);<br>\u200b<br>  \/\/ Call.<br>  getNextToken(); \/\/ eat (<br>  std::vector&lt;std::unique_ptr&lt;ExprAST&gt;&gt; Args;<br>  if (CurTok != ')') {<br> &nbsp;  while (true) {<br> &nbsp; &nbsp;  if (auto Arg = ParseExpression())<br> &nbsp; &nbsp; &nbsp;  Args.push_back(std::move(Arg));<br> &nbsp; &nbsp;  else<br> &nbsp; &nbsp; &nbsp;  return nullptr;<br>\u200b<br> &nbsp; &nbsp;  if (CurTok == ')')<br> &nbsp; &nbsp; &nbsp;  break;<br>\u200b<br> &nbsp; &nbsp;  if (CurTok != ',')<br> &nbsp; &nbsp; &nbsp;  return LogError(\"Expected ')' or ',' in argument list\");<br> &nbsp; &nbsp;  getNextToken();<br> &nbsp;  }<br>  }<br>\u200b<br>  \/\/ Eat the ')'.<br>  getNextToken();<br>\u200b<br>  return std::make_unique&lt;CallExprAST&gt;(IdName, std::move(Args));<br>}<br>\u200b<br>\/\/\/ primary<br>\/\/\/ &nbsp; ::= identifierexpr<br>\/\/\/ &nbsp; ::= numberexpr<br>\/\/\/ &nbsp; ::= parenexpr<br>static std::unique_ptr&lt;ExprAST&gt; ParsePrimary() {<br>  switch (CurTok) {<br>  default:<br> &nbsp;  return LogError(\"unknown token when expecting an expression\");<br>  case tok_identifier:<br> &nbsp;  return ParseIdentifierExpr();<br>  case tok_number:<br> &nbsp;  return ParseNumberExpr();<br>  case '(':<br> &nbsp;  return ParseParenExpr();<br>  }<br>}<br>\u200b<br>\/\/\/ binoprhs<br>\/\/\/ &nbsp; ::= ('+' primary)*<br>static std::unique_ptr&lt;ExprAST&gt; ParseBinOpRHS(int ExprPrec,<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;  std::unique_ptr&lt;ExprAST&gt; LHS) {<br>  \/\/ If this is a binop, find its precedence.<br>  while (true) {<br> &nbsp;  int TokPrec = GetTokPrecedence();<br>\u200b<br> &nbsp;  \/\/ If this is a binop that binds at least as tightly as the current binop,<br> &nbsp;  \/\/ consume it, otherwise we are done.<br> &nbsp;  if (TokPrec &lt; ExprPrec)<br> &nbsp; &nbsp;  return LHS;<br>\u200b<br> &nbsp;  \/\/ Okay, we know this is a binop.<br> &nbsp;  int BinOp = CurTok;<br> &nbsp;  getNextToken(); \/\/ eat binop<br>\u200b<br> &nbsp;  \/\/ Parse the primary expression after the binary operator.<br> &nbsp;  auto RHS = ParsePrimary();<br> &nbsp;  if (!RHS)<br> &nbsp; &nbsp;  return nullptr;<br>\u200b<br> &nbsp;  \/\/ If BinOp binds less tightly with RHS than the operator after RHS, let<br> &nbsp;  \/\/ the pending operator take RHS as its LHS.<br> &nbsp;  int NextPrec = GetTokPrecedence();<br> &nbsp;  if (TokPrec &lt; NextPrec) {<br> &nbsp; &nbsp;  RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));<br> &nbsp; &nbsp;  if (!RHS)<br> &nbsp; &nbsp; &nbsp;  return nullptr;<br> &nbsp;  }<br>\u200b<br> &nbsp;  \/\/ Merge LHS\/RHS.<br> &nbsp;  LHS =<br> &nbsp; &nbsp; &nbsp;  std::make_unique&lt;BinaryExprAST&gt;(BinOp, std::move(LHS), std::move(RHS));<br>  }<br>}<br>\u200b<br>\/\/\/ expression<br>\/\/\/ &nbsp; ::= primary binoprhs<br>\/\/\/<br>static std::unique_ptr&lt;ExprAST&gt; ParseExpression() {<br>  auto LHS = ParsePrimary();<br>  if (!LHS)<br> &nbsp;  return nullptr;<br>\u200b<br>  return ParseBinOpRHS(0, std::move(LHS));<br>}<br>\u200b<br>\/\/\/ prototype<br>\/\/\/ &nbsp; ::= id '(' id* ')'<br>static std::unique_ptr&lt;PrototypeAST&gt; ParsePrototype() {<br>  if (CurTok != tok_identifier)<br> &nbsp;  return LogErrorP(\"Expected function name in prototype\");<br>\u200b<br>  std::string FnName = IdentifierStr;<br>  getNextToken();<br>\u200b<br>  if (CurTok != '(')<br> &nbsp;  return LogErrorP(\"Expected '(' in prototype\");<br>\u200b<br>  std::vector&lt;std::string&gt; ArgNames;<br>  while (getNextToken() == tok_identifier)<br> &nbsp;  ArgNames.push_back(IdentifierStr);<br>  if (CurTok != ')')<br> &nbsp;  return LogErrorP(\"Expected ')' in prototype\");<br>\u200b<br>  \/\/ success.<br>  getNextToken(); \/\/ eat ')'.<br>\u200b<br>  return std::make_unique&lt;PrototypeAST&gt;(FnName, std::move(ArgNames));<br>}<br>\u200b<br>\/\/\/ definition ::= 'def' prototype expression<br>static std::unique_ptr&lt;FunctionAST&gt; ParseDefinition() {<br>  getNextToken(); \/\/ eat def.<br>  auto Proto = ParsePrototype();<br>  if (!Proto)<br> &nbsp;  return nullptr;<br>\u200b<br>  if (auto E = ParseExpression())<br> &nbsp;  return std::make_unique&lt;FunctionAST&gt;(std::move(Proto), std::move(E));<br>  return nullptr;<br>}<br>\u200b<br>\/\/\/ toplevelexpr ::= expression<br>static std::unique_ptr&lt;FunctionAST&gt; ParseTopLevelExpr() {<br>  if (auto E = ParseExpression()) {<br> &nbsp;  \/\/ Make an anonymous proto.<br> &nbsp;  auto Proto = std::make_unique&lt;PrototypeAST&gt;(\"__anon_expr\",<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; std::vector&lt;std::string&gt;());<br> &nbsp;  return std::make_unique&lt;FunctionAST&gt;(std::move(Proto), std::move(E));<br>  }<br>  return nullptr;<br>}<br>\u200b<br>\/\/\/ external ::= 'extern' prototype<br>static std::unique_ptr&lt;PrototypeAST&gt; ParseExtern() {<br>  getNextToken(); \/\/ eat extern.<br>  return ParsePrototype();<br>}<br>\u200b<br>\/\/===----------------------------------------------------------------------===\/\/<br>\/\/ Code Generation<br>\/\/===----------------------------------------------------------------------===\/\/<br>\u200b<br>static LLVMContext TheContext;<br>static IRBuilder&lt;&gt; Builder(TheContext);<br>static std::unique_ptr&lt;Module&gt; TheModule;<br>static std::map&lt;std::string, Value *&gt; NamedValues;<br>\u200b<br>Value *LogErrorV(const char *Str) {<br>  LogError(Str);<br>  return nullptr;<br>}<br>\u200b<br>Value *NumberExprAST::codegen() {<br>  return ConstantFP::get(TheContext, APFloat(Val));<br>}<br>\u200b<br>Value *VariableExprAST::codegen() {<br>  \/\/ Look this variable up in the function.<br>  Value *V = NamedValues[Name];<br>  if (!V)<br> &nbsp;  return LogErrorV(\"Unknown variable name\");<br>  return V;<br>}<br>\u200b<br>Value *BinaryExprAST::codegen() {<br>  Value *L = LHS-&gt;codegen();<br>  Value *R = RHS-&gt;codegen();<br>  if (!L || !R)<br> &nbsp;  return nullptr;<br>\u200b<br>  switch (Op) {<br>  case '+':<br> &nbsp;  return Builder.CreateFAdd(L, R, \"addtmp\");<br>  case '-':<br> &nbsp;  return Builder.CreateFSub(L, R, \"subtmp\");<br>  case '*':<br> &nbsp;  return Builder.CreateFMul(L, R, \"multmp\");<br>  case '&lt;':<br> &nbsp;  L = Builder.CreateFCmpULT(L, R, \"cmptmp\");<br> &nbsp;  \/\/ Convert bool 0\/1 to double 0.0 or 1.0<br> &nbsp;  return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext), \"booltmp\");<br>  default:<br> &nbsp;  return LogErrorV(\"invalid binary operator\");<br>  }<br>}<br>\u200b<br>Value *CallExprAST::codegen() {<br>  \/\/ Look up the name in the global module table.<br>  Function *CalleeF = TheModule-&gt;getFunction(Callee);<br>  if (!CalleeF)<br> &nbsp;  return LogErrorV(\"Unknown function referenced\");<br>\u200b<br>  \/\/ If argument mismatch error.<br>  if (CalleeF-&gt;arg_size() != Args.size())<br> &nbsp;  return LogErrorV(\"Incorrect # arguments passed\");<br>\u200b<br>  std::vector&lt;Value *&gt; ArgsV;<br>  for (unsigned i = 0, e = Args.size(); i != e; ++i) {<br> &nbsp;  ArgsV.push_back(Args[i]-&gt;codegen());<br> &nbsp;  if (!ArgsV.back())<br> &nbsp; &nbsp;  return nullptr;<br>  }<br>\u200b<br>  return Builder.CreateCall(CalleeF, ArgsV, \"calltmp\");<br>}<br>\u200b<br>Function *PrototypeAST::codegen() {<br>  \/\/ Make the function type:  double(double,double) etc.<br>  std::vector&lt;Type *&gt; Doubles(Args.size(), Type::getDoubleTy(TheContext));<br>  FunctionType *FT =<br> &nbsp; &nbsp;  FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);<br>\u200b<br>  Function *F =<br> &nbsp; &nbsp;  Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());<br>\u200b<br>  \/\/ Set names for all arguments.<br>  unsigned Idx = 0;<br>  for (auto &amp;Arg : F-&gt;args())<br> &nbsp;  Arg.setName(Args[Idx++]);<br>\u200b<br>  return F;<br>}<br>\u200b<br>Function *FunctionAST::codegen() {<br>  \/\/ First, check for an existing function from a previous 'extern' declaration.<br>  Function *TheFunction = TheModule-&gt;getFunction(Proto-&gt;getName());<br>\u200b<br>  if (!TheFunction)<br> &nbsp;  TheFunction = Proto-&gt;codegen();<br>\u200b<br>  if (!TheFunction)<br> &nbsp;  return nullptr;<br>\u200b<br>  \/\/ Create a new basic block to start insertion into.<br>  BasicBlock *BB = BasicBlock::Create(TheContext, \"entry\", TheFunction);<br>  Builder.SetInsertPoint(BB);<br>\u200b<br>  \/\/ Record the function arguments in the NamedValues map.<br>  NamedValues.clear();<br>  for (auto &amp;Arg : TheFunction-&gt;args())<br> &nbsp;  NamedValues[std::string(Arg.getName())] = &amp;Arg;<br>\u200b<br>  if (Value *RetVal = Body-&gt;codegen()) {<br> &nbsp;  \/\/ Finish off the function.<br> &nbsp;  Builder.CreateRet(RetVal);<br>\u200b<br> &nbsp;  \/\/ Validate the generated code, checking for consistency.<br> &nbsp;  verifyFunction(*TheFunction);<br>\u200b<br> &nbsp;  return TheFunction;<br>  }<br>\u200b<br>  \/\/ Error reading body, remove function.<br>  TheFunction-&gt;eraseFromParent();<br>  return nullptr;<br>}<br>\u200b<br>\/\/===----------------------------------------------------------------------===\/\/<br>\/\/ Top-Level parsing and JIT Driver<br>\/\/===----------------------------------------------------------------------===\/\/<br>\u200b<br>static void HandleDefinition() {<br>  if (auto FnAST = ParseDefinition()) {<br> &nbsp;  if (auto *FnIR = FnAST-&gt;codegen()) {<br> &nbsp; &nbsp;  fprintf(stderr, \"Read function definition:\");<br> &nbsp; &nbsp;  FnIR-&gt;print(errs());<br> &nbsp; &nbsp;  fprintf(stderr, \"\\n\");<br> &nbsp;  }<br>  } else {<br> &nbsp;  \/\/ Skip token for error recovery.<br> &nbsp;  getNextToken();<br>  }<br>}<br>\u200b<br>static void HandleExtern() {<br>  if (auto ProtoAST = ParseExtern()) {<br> &nbsp;  if (auto *FnIR = ProtoAST-&gt;codegen()) {<br> &nbsp; &nbsp;  fprintf(stderr, \"Read extern: \");<br> &nbsp; &nbsp;  FnIR-&gt;print(errs());<br> &nbsp; &nbsp;  fprintf(stderr, \"\\n\");<br> &nbsp;  }<br>  } else {<br> &nbsp;  \/\/ Skip token for error recovery.<br> &nbsp;  getNextToken();<br>  }<br>}<br>\u200b<br>static void HandleTopLevelExpression() {<br>  \/\/ Evaluate a top-level expression into an anonymous function.<br>  if (auto FnAST = ParseTopLevelExpr()) {<br> &nbsp;  if (auto *FnIR = FnAST-&gt;codegen()) {<br> &nbsp; &nbsp;  fprintf(stderr, \"Read top-level expression:\");<br> &nbsp; &nbsp;  FnIR-&gt;print(errs());<br> &nbsp; &nbsp;  fprintf(stderr, \"\\n\");<br> &nbsp;  }<br>  } else {<br> &nbsp;  \/\/ Skip token for error recovery.<br> &nbsp;  getNextToken();<br>  }<br>}<br>\u200b<br>\/\/\/ top ::= definition | external | expression | ';'<br>static void MainLoop() {<br>  while (true) {<br> &nbsp;  fprintf(stderr, \"ready&gt; \");<br> &nbsp;  switch (CurTok) {<br> &nbsp;  case tok_eof:<br> &nbsp; &nbsp;  return;<br> &nbsp;  case ';': \/\/ ignore top-level semicolons.<br> &nbsp; &nbsp;  getNextToken();<br> &nbsp; &nbsp;  break;<br> &nbsp;  case tok_def:<br> &nbsp; &nbsp;  HandleDefinition();<br> &nbsp; &nbsp;  break;<br> &nbsp;  case tok_extern:<br> &nbsp; &nbsp;  HandleExtern();<br> &nbsp; &nbsp;  break;<br> &nbsp;  default:<br> &nbsp; &nbsp;  HandleTopLevelExpression();<br> &nbsp; &nbsp;  break;<br> &nbsp;  }<br>  }<br>}<br>\u200b<br>\/\/===----------------------------------------------------------------------===\/\/<br>\/\/ Main driver code.<br>\/\/===----------------------------------------------------------------------===\/\/<br>\u200b<br>int main() {<br>  \/\/ Install standard binary operators.<br>  \/\/ 1 is lowest precedence.<br>  BinopPrecedence['&lt;'] = 10;<br>  BinopPrecedence['+'] = 20;<br>  BinopPrecedence['-'] = 20;<br>  BinopPrecedence['*'] = 40; \/\/ highest.<br>\u200b<br>  \/\/ Prime the first token.<br>  fprintf(stderr, \"ready&gt; \");<br>  getNextToken();<br>\u200b<br>  \/\/ Make the module, which holds all the code.<br>  TheModule = std::make_unique&lt;Module&gt;(\"my cool jit\", TheContext);<br>\u200b<br>  \/\/ Run the main \"interpreter loop\" now.<br>  MainLoop();<br>\u200b<br>  \/\/ Print out all of the generated code.<br>  TheModule-&gt;print(errs(), nullptr);<br>\u200b<br>  return 0;<br>}<\/pre>\n\n\n\n<p>\u7f16\u8bd1\u547d\u4ee4<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">$LLVM_HOME\/bin\/clang++ -g -O3 toy.cpp `$LLVM_HOME\/bin\/llvm-config --cxxflags --ldflags --system-libs --libs core` -o toy -I\/usr\/local\/include<\/pre>\n\n\n\n<p>\u5148\u4ece\u7b80\u5355\u7684\u5f00\u59cb\u5206\u6790:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">ready&gt; 1;  \nready&gt;Read top-level expression:define double @__anon_expr() {\nentry:\n  ret double 1.000000e+00\n}<\/pre>\n\n\n\n<p>\u56e0\u4e3a\u65e2\u4e0d\u662fdef \u4e5f\u4e0d\u662f extern \u76f4\u63a5\u8fdb\u53bb\u5230HandleTopLevelExpression\uff0c ParseTopLevelExpr\u521b\u5efa\u4e86FunctionAST\u8bed\u6cd5\u6811\uff0c \u5982\u56fe\uff1a<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" loading=\"lazy\" width=\"521\" height=\"297\" src=\"http:\/\/47.108.144.50\/wp-content\/uploads\/2020\/08\/image-20200812173710923.png\" alt=\"image-20200812173710923\" class=\"wp-image-30\" srcset=\"http:\/\/pareto.fun\/wp-content\/uploads\/2020\/08\/image-20200812173710923.png 521w, http:\/\/pareto.fun\/wp-content\/uploads\/2020\/08\/image-20200812173710923-300x171.png 300w\" sizes=\"(max-width: 521px) 100vw, 521px\" \/><\/figure>\n\n\n\n<p>PrototypeAST \u7684\u540d\u79f0\u4e3a&#8221;__anon_expr&#8221; , \u53c2\u6570\u4e3a\u7a7a\uff0cNumberExprAST \u5b58\u4e86\u4e2a&#8221;1&#8243;\uff0c\u8bed\u6cd5\u6811\u751f\u6210\u7ed3\u675f\u540e\u3002<\/p>\n\n\n\n<p>\u8c03\u7528FnAST-&gt;codegen() \u6765\u751f\u6210\u5bf9\u5e94\u8bed\u6cd5\u6811\u7684IR\u6307\u4ee4\u3002\u5148\u751f\u6210\u51fd\u6570\u5b9a\u4e49\u518d\u751f\u6210\u51fd\u6570\u4f53\u3002\u8fc7\u7a0b\u63cf\u8ff0\u8fc7\u4e86\uff0c\u4e0d\u591a\u8d58\u8ff0\u3002<\/p>\n\n\n\n<p><a href=\"https:\/\/llvm.org\/docs\/tutorial\/MyFirstLanguageFrontend\/LangImpl03.html\">https:\/\/llvm.org\/docs\/tutorial\/MyFirstLanguageFrontend\/LangImpl03.html<\/a><\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u82f1\u6587\u770b\u591a\u4e86\u8fd8\u662f\u5934\u75db\uff0c\u8fd8\u662f\u76f4\u63a5\u4e0a\u4ee3\u7801 \u4ee3\u7801\u76f8\u6bd4\u4e8e\u4e0a\u4e00\u7bc7\u4e3a\u6bcf\u4e2a\u8bed\u6cd5\u6811\u65b0\u589e\u4e86\u751f\u6210\u6307\u4ee4\u7684\u51fd\u6570codegen\uff0c [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[1],"tags":[],"_links":{"self":[{"href":"http:\/\/pareto.fun\/index.php?rest_route=\/wp\/v2\/posts\/29"}],"collection":[{"href":"http:\/\/pareto.fun\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/pareto.fun\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/pareto.fun\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/pareto.fun\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=29"}],"version-history":[{"count":2,"href":"http:\/\/pareto.fun\/index.php?rest_route=\/wp\/v2\/posts\/29\/revisions"}],"predecessor-version":[{"id":33,"href":"http:\/\/pareto.fun\/index.php?rest_route=\/wp\/v2\/posts\/29\/revisions\/33"}],"wp:attachment":[{"href":"http:\/\/pareto.fun\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=29"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/pareto.fun\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=29"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/pareto.fun\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=29"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}