LangImpl07.rst 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. :orphan:
  2. =======================================================
  3. Kaleidoscope: Extending the Language: Mutable Variables
  4. =======================================================
  5. .. contents::
  6. :local:
  7. Chapter 7 Introduction
  8. ======================
  9. Welcome to Chapter 7 of the "`Implementing a language with
  10. LLVM <index.html>`_" tutorial. In chapters 1 through 6, we've built a
  11. very respectable, albeit simple, `functional programming
  12. language <http://en.wikipedia.org/wiki/Functional_programming>`_. In our
  13. journey, we learned some parsing techniques, how to build and represent
  14. an AST, how to build LLVM IR, and how to optimize the resultant code as
  15. well as JIT compile it.
  16. While Kaleidoscope is interesting as a functional language, the fact
  17. that it is functional makes it "too easy" to generate LLVM IR for it. In
  18. particular, a functional language makes it very easy to build LLVM IR
  19. directly in `SSA
  20. form <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_.
  21. Since LLVM requires that the input code be in SSA form, this is a very
  22. nice property and it is often unclear to newcomers how to generate code
  23. for an imperative language with mutable variables.
  24. The short (and happy) summary of this chapter is that there is no need
  25. for your front-end to build SSA form: LLVM provides highly tuned and
  26. well tested support for this, though the way it works is a bit
  27. unexpected for some.
  28. Why is this a hard problem?
  29. ===========================
  30. To understand why mutable variables cause complexities in SSA
  31. construction, consider this extremely simple C example:
  32. .. code-block:: c
  33. int G, H;
  34. int test(_Bool Condition) {
  35. int X;
  36. if (Condition)
  37. X = G;
  38. else
  39. X = H;
  40. return X;
  41. }
  42. In this case, we have the variable "X", whose value depends on the path
  43. executed in the program. Because there are two different possible values
  44. for X before the return instruction, a PHI node is inserted to merge the
  45. two values. The LLVM IR that we want for this example looks like this:
  46. .. code-block:: llvm
  47. @G = weak global i32 0 ; type of @G is i32*
  48. @H = weak global i32 0 ; type of @H is i32*
  49. define i32 @test(i1 %Condition) {
  50. entry:
  51. br i1 %Condition, label %cond_true, label %cond_false
  52. cond_true:
  53. %X.0 = load i32* @G
  54. br label %cond_next
  55. cond_false:
  56. %X.1 = load i32* @H
  57. br label %cond_next
  58. cond_next:
  59. %X.2 = phi i32 [ %X.1, %cond_false ], [ %X.0, %cond_true ]
  60. ret i32 %X.2
  61. }
  62. In this example, the loads from the G and H global variables are
  63. explicit in the LLVM IR, and they live in the then/else branches of the
  64. if statement (cond\_true/cond\_false). In order to merge the incoming
  65. values, the X.2 phi node in the cond\_next block selects the right value
  66. to use based on where control flow is coming from: if control flow comes
  67. from the cond\_false block, X.2 gets the value of X.1. Alternatively, if
  68. control flow comes from cond\_true, it gets the value of X.0. The intent
  69. of this chapter is not to explain the details of SSA form. For more
  70. information, see one of the many `online
  71. references <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_.
  72. The question for this article is "who places the phi nodes when lowering
  73. assignments to mutable variables?". The issue here is that LLVM
  74. *requires* that its IR be in SSA form: there is no "non-ssa" mode for
  75. it. However, SSA construction requires non-trivial algorithms and data
  76. structures, so it is inconvenient and wasteful for every front-end to
  77. have to reproduce this logic.
  78. Memory in LLVM
  79. ==============
  80. The 'trick' here is that while LLVM does require all register values to
  81. be in SSA form, it does not require (or permit) memory objects to be in
  82. SSA form. In the example above, note that the loads from G and H are
  83. direct accesses to G and H: they are not renamed or versioned. This
  84. differs from some other compiler systems, which do try to version memory
  85. objects. In LLVM, instead of encoding dataflow analysis of memory into
  86. the LLVM IR, it is handled with `Analysis
  87. Passes <../WritingAnLLVMPass.html>`_ which are computed on demand.
  88. With this in mind, the high-level idea is that we want to make a stack
  89. variable (which lives in memory, because it is on the stack) for each
  90. mutable object in a function. To take advantage of this trick, we need
  91. to talk about how LLVM represents stack variables.
  92. In LLVM, all memory accesses are explicit with load/store instructions,
  93. and it is carefully designed not to have (or need) an "address-of"
  94. operator. Notice how the type of the @G/@H global variables is actually
  95. "i32\*" even though the variable is defined as "i32". What this means is
  96. that @G defines *space* for an i32 in the global data area, but its
  97. *name* actually refers to the address for that space. Stack variables
  98. work the same way, except that instead of being declared with global
  99. variable definitions, they are declared with the `LLVM alloca
  100. instruction <../LangRef.html#alloca-instruction>`_:
  101. .. code-block:: llvm
  102. define i32 @example() {
  103. entry:
  104. %X = alloca i32 ; type of %X is i32*.
  105. ...
  106. %tmp = load i32* %X ; load the stack value %X from the stack.
  107. %tmp2 = add i32 %tmp, 1 ; increment it
  108. store i32 %tmp2, i32* %X ; store it back
  109. ...
  110. This code shows an example of how you can declare and manipulate a stack
  111. variable in the LLVM IR. Stack memory allocated with the alloca
  112. instruction is fully general: you can pass the address of the stack slot
  113. to functions, you can store it in other variables, etc. In our example
  114. above, we could rewrite the example to use the alloca technique to avoid
  115. using a PHI node:
  116. .. code-block:: llvm
  117. @G = weak global i32 0 ; type of @G is i32*
  118. @H = weak global i32 0 ; type of @H is i32*
  119. define i32 @test(i1 %Condition) {
  120. entry:
  121. %X = alloca i32 ; type of %X is i32*.
  122. br i1 %Condition, label %cond_true, label %cond_false
  123. cond_true:
  124. %X.0 = load i32* @G
  125. store i32 %X.0, i32* %X ; Update X
  126. br label %cond_next
  127. cond_false:
  128. %X.1 = load i32* @H
  129. store i32 %X.1, i32* %X ; Update X
  130. br label %cond_next
  131. cond_next:
  132. %X.2 = load i32* %X ; Read X
  133. ret i32 %X.2
  134. }
  135. With this, we have discovered a way to handle arbitrary mutable
  136. variables without the need to create Phi nodes at all:
  137. #. Each mutable variable becomes a stack allocation.
  138. #. Each read of the variable becomes a load from the stack.
  139. #. Each update of the variable becomes a store to the stack.
  140. #. Taking the address of a variable just uses the stack address
  141. directly.
  142. While this solution has solved our immediate problem, it introduced
  143. another one: we have now apparently introduced a lot of stack traffic
  144. for very simple and common operations, a major performance problem.
  145. Fortunately for us, the LLVM optimizer has a highly-tuned optimization
  146. pass named "mem2reg" that handles this case, promoting allocas like this
  147. into SSA registers, inserting Phi nodes as appropriate. If you run this
  148. example through the pass, for example, you'll get:
  149. .. code-block:: bash
  150. $ llvm-as < example.ll | opt -mem2reg | llvm-dis
  151. @G = weak global i32 0
  152. @H = weak global i32 0
  153. define i32 @test(i1 %Condition) {
  154. entry:
  155. br i1 %Condition, label %cond_true, label %cond_false
  156. cond_true:
  157. %X.0 = load i32* @G
  158. br label %cond_next
  159. cond_false:
  160. %X.1 = load i32* @H
  161. br label %cond_next
  162. cond_next:
  163. %X.01 = phi i32 [ %X.1, %cond_false ], [ %X.0, %cond_true ]
  164. ret i32 %X.01
  165. }
  166. The mem2reg pass implements the standard "iterated dominance frontier"
  167. algorithm for constructing SSA form and has a number of optimizations
  168. that speed up (very common) degenerate cases. The mem2reg optimization
  169. pass is the answer to dealing with mutable variables, and we highly
  170. recommend that you depend on it. Note that mem2reg only works on
  171. variables in certain circumstances:
  172. #. mem2reg is alloca-driven: it looks for allocas and if it can handle
  173. them, it promotes them. It does not apply to global variables or heap
  174. allocations.
  175. #. mem2reg only looks for alloca instructions in the entry block of the
  176. function. Being in the entry block guarantees that the alloca is only
  177. executed once, which makes analysis simpler.
  178. #. mem2reg only promotes allocas whose uses are direct loads and stores.
  179. If the address of the stack object is passed to a function, or if any
  180. funny pointer arithmetic is involved, the alloca will not be
  181. promoted.
  182. #. mem2reg only works on allocas of `first
  183. class <../LangRef.html#first-class-types>`_ values (such as pointers,
  184. scalars and vectors), and only if the array size of the allocation is
  185. 1 (or missing in the .ll file). mem2reg is not capable of promoting
  186. structs or arrays to registers. Note that the "sroa" pass is
  187. more powerful and can promote structs, "unions", and arrays in many
  188. cases.
  189. All of these properties are easy to satisfy for most imperative
  190. languages, and we'll illustrate it below with Kaleidoscope. The final
  191. question you may be asking is: should I bother with this nonsense for my
  192. front-end? Wouldn't it be better if I just did SSA construction
  193. directly, avoiding use of the mem2reg optimization pass? In short, we
  194. strongly recommend that you use this technique for building SSA form,
  195. unless there is an extremely good reason not to. Using this technique
  196. is:
  197. - Proven and well tested: clang uses this technique
  198. for local mutable variables. As such, the most common clients of LLVM
  199. are using this to handle a bulk of their variables. You can be sure
  200. that bugs are found fast and fixed early.
  201. - Extremely Fast: mem2reg has a number of special cases that make it
  202. fast in common cases as well as fully general. For example, it has
  203. fast-paths for variables that are only used in a single block,
  204. variables that only have one assignment point, good heuristics to
  205. avoid insertion of unneeded phi nodes, etc.
  206. - Needed for debug info generation: `Debug information in
  207. LLVM <../SourceLevelDebugging.html>`_ relies on having the address of
  208. the variable exposed so that debug info can be attached to it. This
  209. technique dovetails very naturally with this style of debug info.
  210. If nothing else, this makes it much easier to get your front-end up and
  211. running, and is very simple to implement. Let's extend Kaleidoscope with
  212. mutable variables now!
  213. Mutable Variables in Kaleidoscope
  214. =================================
  215. Now that we know the sort of problem we want to tackle, let's see what
  216. this looks like in the context of our little Kaleidoscope language.
  217. We're going to add two features:
  218. #. The ability to mutate variables with the '=' operator.
  219. #. The ability to define new variables.
  220. While the first item is really what this is about, we only have
  221. variables for incoming arguments as well as for induction variables, and
  222. redefining those only goes so far :). Also, the ability to define new
  223. variables is a useful thing regardless of whether you will be mutating
  224. them. Here's a motivating example that shows how we could use these:
  225. ::
  226. # Define ':' for sequencing: as a low-precedence operator that ignores operands
  227. # and just returns the RHS.
  228. def binary : 1 (x y) y;
  229. # Recursive fib, we could do this before.
  230. def fib(x)
  231. if (x < 3) then
  232. 1
  233. else
  234. fib(x-1)+fib(x-2);
  235. # Iterative fib.
  236. def fibi(x)
  237. var a = 1, b = 1, c in
  238. (for i = 3, i < x in
  239. c = a + b :
  240. a = b :
  241. b = c) :
  242. b;
  243. # Call it.
  244. fibi(10);
  245. In order to mutate variables, we have to change our existing variables
  246. to use the "alloca trick". Once we have that, we'll add our new
  247. operator, then extend Kaleidoscope to support new variable definitions.
  248. Adjusting Existing Variables for Mutation
  249. =========================================
  250. The symbol table in Kaleidoscope is managed at code generation time by
  251. the '``NamedValues``' map. This map currently keeps track of the LLVM
  252. "Value\*" that holds the double value for the named variable. In order
  253. to support mutation, we need to change this slightly, so that
  254. ``NamedValues`` holds the *memory location* of the variable in question.
  255. Note that this change is a refactoring: it changes the structure of the
  256. code, but does not (by itself) change the behavior of the compiler. All
  257. of these changes are isolated in the Kaleidoscope code generator.
  258. At this point in Kaleidoscope's development, it only supports variables
  259. for two things: incoming arguments to functions and the induction
  260. variable of 'for' loops. For consistency, we'll allow mutation of these
  261. variables in addition to other user-defined variables. This means that
  262. these will both need memory locations.
  263. To start our transformation of Kaleidoscope, we'll change the
  264. NamedValues map so that it maps to AllocaInst\* instead of Value\*. Once
  265. we do this, the C++ compiler will tell us what parts of the code we need
  266. to update:
  267. .. code-block:: c++
  268. static std::map<std::string, AllocaInst*> NamedValues;
  269. Also, since we will need to create these allocas, we'll use a helper
  270. function that ensures that the allocas are created in the entry block of
  271. the function:
  272. .. code-block:: c++
  273. /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
  274. /// the function. This is used for mutable variables etc.
  275. static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
  276. const std::string &VarName) {
  277. IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
  278. TheFunction->getEntryBlock().begin());
  279. return TmpB.CreateAlloca(Type::getDoubleTy(TheContext), 0,
  280. VarName.c_str());
  281. }
  282. This funny looking code creates an IRBuilder object that is pointing at
  283. the first instruction (.begin()) of the entry block. It then creates an
  284. alloca with the expected name and returns it. Because all values in
  285. Kaleidoscope are doubles, there is no need to pass in a type to use.
  286. With this in place, the first functionality change we want to make belongs to
  287. variable references. In our new scheme, variables live on the stack, so
  288. code generating a reference to them actually needs to produce a load
  289. from the stack slot:
  290. .. code-block:: c++
  291. Value *VariableExprAST::codegen() {
  292. // Look this variable up in the function.
  293. Value *V = NamedValues[Name];
  294. if (!V)
  295. return LogErrorV("Unknown variable name");
  296. // Load the value.
  297. return Builder.CreateLoad(V, Name.c_str());
  298. }
  299. As you can see, this is pretty straightforward. Now we need to update
  300. the things that define the variables to set up the alloca. We'll start
  301. with ``ForExprAST::codegen()`` (see the `full code listing <#id1>`_ for
  302. the unabridged code):
  303. .. code-block:: c++
  304. Function *TheFunction = Builder.GetInsertBlock()->getParent();
  305. // Create an alloca for the variable in the entry block.
  306. AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
  307. // Emit the start code first, without 'variable' in scope.
  308. Value *StartVal = Start->codegen();
  309. if (!StartVal)
  310. return nullptr;
  311. // Store the value into the alloca.
  312. Builder.CreateStore(StartVal, Alloca);
  313. ...
  314. // Compute the end condition.
  315. Value *EndCond = End->codegen();
  316. if (!EndCond)
  317. return nullptr;
  318. // Reload, increment, and restore the alloca. This handles the case where
  319. // the body of the loop mutates the variable.
  320. Value *CurVar = Builder.CreateLoad(Alloca);
  321. Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
  322. Builder.CreateStore(NextVar, Alloca);
  323. ...
  324. This code is virtually identical to the code `before we allowed mutable
  325. variables <LangImpl5.html#code-generation-for-the-for-loop>`_. The big difference is that we
  326. no longer have to construct a PHI node, and we use load/store to access
  327. the variable as needed.
  328. To support mutable argument variables, we need to also make allocas for
  329. them. The code for this is also pretty simple:
  330. .. code-block:: c++
  331. Function *FunctionAST::codegen() {
  332. ...
  333. Builder.SetInsertPoint(BB);
  334. // Record the function arguments in the NamedValues map.
  335. NamedValues.clear();
  336. for (auto &Arg : TheFunction->args()) {
  337. // Create an alloca for this variable.
  338. AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
  339. // Store the initial value into the alloca.
  340. Builder.CreateStore(&Arg, Alloca);
  341. // Add arguments to variable symbol table.
  342. NamedValues[Arg.getName()] = Alloca;
  343. }
  344. if (Value *RetVal = Body->codegen()) {
  345. ...
  346. For each argument, we make an alloca, store the input value to the
  347. function into the alloca, and register the alloca as the memory location
  348. for the argument. This method gets invoked by ``FunctionAST::codegen()``
  349. right after it sets up the entry block for the function.
  350. The final missing piece is adding the mem2reg pass, which allows us to
  351. get good codegen once again:
  352. .. code-block:: c++
  353. // Promote allocas to registers.
  354. TheFPM->add(createPromoteMemoryToRegisterPass());
  355. // Do simple "peephole" optimizations and bit-twiddling optzns.
  356. TheFPM->add(createInstructionCombiningPass());
  357. // Reassociate expressions.
  358. TheFPM->add(createReassociatePass());
  359. ...
  360. It is interesting to see what the code looks like before and after the
  361. mem2reg optimization runs. For example, this is the before/after code
  362. for our recursive fib function. Before the optimization:
  363. .. code-block:: llvm
  364. define double @fib(double %x) {
  365. entry:
  366. %x1 = alloca double
  367. store double %x, double* %x1
  368. %x2 = load double, double* %x1
  369. %cmptmp = fcmp ult double %x2, 3.000000e+00
  370. %booltmp = uitofp i1 %cmptmp to double
  371. %ifcond = fcmp one double %booltmp, 0.000000e+00
  372. br i1 %ifcond, label %then, label %else
  373. then: ; preds = %entry
  374. br label %ifcont
  375. else: ; preds = %entry
  376. %x3 = load double, double* %x1
  377. %subtmp = fsub double %x3, 1.000000e+00
  378. %calltmp = call double @fib(double %subtmp)
  379. %x4 = load double, double* %x1
  380. %subtmp5 = fsub double %x4, 2.000000e+00
  381. %calltmp6 = call double @fib(double %subtmp5)
  382. %addtmp = fadd double %calltmp, %calltmp6
  383. br label %ifcont
  384. ifcont: ; preds = %else, %then
  385. %iftmp = phi double [ 1.000000e+00, %then ], [ %addtmp, %else ]
  386. ret double %iftmp
  387. }
  388. Here there is only one variable (x, the input argument) but you can
  389. still see the extremely simple-minded code generation strategy we are
  390. using. In the entry block, an alloca is created, and the initial input
  391. value is stored into it. Each reference to the variable does a reload
  392. from the stack. Also, note that we didn't modify the if/then/else
  393. expression, so it still inserts a PHI node. While we could make an
  394. alloca for it, it is actually easier to create a PHI node for it, so we
  395. still just make the PHI.
  396. Here is the code after the mem2reg pass runs:
  397. .. code-block:: llvm
  398. define double @fib(double %x) {
  399. entry:
  400. %cmptmp = fcmp ult double %x, 3.000000e+00
  401. %booltmp = uitofp i1 %cmptmp to double
  402. %ifcond = fcmp one double %booltmp, 0.000000e+00
  403. br i1 %ifcond, label %then, label %else
  404. then:
  405. br label %ifcont
  406. else:
  407. %subtmp = fsub double %x, 1.000000e+00
  408. %calltmp = call double @fib(double %subtmp)
  409. %subtmp5 = fsub double %x, 2.000000e+00
  410. %calltmp6 = call double @fib(double %subtmp5)
  411. %addtmp = fadd double %calltmp, %calltmp6
  412. br label %ifcont
  413. ifcont: ; preds = %else, %then
  414. %iftmp = phi double [ 1.000000e+00, %then ], [ %addtmp, %else ]
  415. ret double %iftmp
  416. }
  417. This is a trivial case for mem2reg, since there are no redefinitions of
  418. the variable. The point of showing this is to calm your tension about
  419. inserting such blatant inefficiencies :).
  420. After the rest of the optimizers run, we get:
  421. .. code-block:: llvm
  422. define double @fib(double %x) {
  423. entry:
  424. %cmptmp = fcmp ult double %x, 3.000000e+00
  425. %booltmp = uitofp i1 %cmptmp to double
  426. %ifcond = fcmp ueq double %booltmp, 0.000000e+00
  427. br i1 %ifcond, label %else, label %ifcont
  428. else:
  429. %subtmp = fsub double %x, 1.000000e+00
  430. %calltmp = call double @fib(double %subtmp)
  431. %subtmp5 = fsub double %x, 2.000000e+00
  432. %calltmp6 = call double @fib(double %subtmp5)
  433. %addtmp = fadd double %calltmp, %calltmp6
  434. ret double %addtmp
  435. ifcont:
  436. ret double 1.000000e+00
  437. }
  438. Here we see that the simplifycfg pass decided to clone the return
  439. instruction into the end of the 'else' block. This allowed it to
  440. eliminate some branches and the PHI node.
  441. Now that all symbol table references are updated to use stack variables,
  442. we'll add the assignment operator.
  443. New Assignment Operator
  444. =======================
  445. With our current framework, adding a new assignment operator is really
  446. simple. We will parse it just like any other binary operator, but handle
  447. it internally (instead of allowing the user to define it). The first
  448. step is to set a precedence:
  449. .. code-block:: c++
  450. int main() {
  451. // Install standard binary operators.
  452. // 1 is lowest precedence.
  453. BinopPrecedence['='] = 2;
  454. BinopPrecedence['<'] = 10;
  455. BinopPrecedence['+'] = 20;
  456. BinopPrecedence['-'] = 20;
  457. Now that the parser knows the precedence of the binary operator, it
  458. takes care of all the parsing and AST generation. We just need to
  459. implement codegen for the assignment operator. This looks like:
  460. .. code-block:: c++
  461. Value *BinaryExprAST::codegen() {
  462. // Special case '=' because we don't want to emit the LHS as an expression.
  463. if (Op == '=') {
  464. // Assignment requires the LHS to be an identifier.
  465. VariableExprAST *LHSE = dynamic_cast<VariableExprAST*>(LHS.get());
  466. if (!LHSE)
  467. return LogErrorV("destination of '=' must be a variable");
  468. Unlike the rest of the binary operators, our assignment operator doesn't
  469. follow the "emit LHS, emit RHS, do computation" model. As such, it is
  470. handled as a special case before the other binary operators are handled.
  471. The other strange thing is that it requires the LHS to be a variable. It
  472. is invalid to have "(x+1) = expr" - only things like "x = expr" are
  473. allowed.
  474. .. code-block:: c++
  475. // Codegen the RHS.
  476. Value *Val = RHS->codegen();
  477. if (!Val)
  478. return nullptr;
  479. // Look up the name.
  480. Value *Variable = NamedValues[LHSE->getName()];
  481. if (!Variable)
  482. return LogErrorV("Unknown variable name");
  483. Builder.CreateStore(Val, Variable);
  484. return Val;
  485. }
  486. ...
  487. Once we have the variable, codegen'ing the assignment is
  488. straightforward: we emit the RHS of the assignment, create a store, and
  489. return the computed value. Returning a value allows for chained
  490. assignments like "X = (Y = Z)".
  491. Now that we have an assignment operator, we can mutate loop variables
  492. and arguments. For example, we can now run code like this:
  493. ::
  494. # Function to print a double.
  495. extern printd(x);
  496. # Define ':' for sequencing: as a low-precedence operator that ignores operands
  497. # and just returns the RHS.
  498. def binary : 1 (x y) y;
  499. def test(x)
  500. printd(x) :
  501. x = 4 :
  502. printd(x);
  503. test(123);
  504. When run, this example prints "123" and then "4", showing that we did
  505. actually mutate the value! Okay, we have now officially implemented our
  506. goal: getting this to work requires SSA construction in the general
  507. case. However, to be really useful, we want the ability to define our
  508. own local variables, let's add this next!
  509. User-defined Local Variables
  510. ============================
  511. Adding var/in is just like any other extension we made to
  512. Kaleidoscope: we extend the lexer, the parser, the AST and the code
  513. generator. The first step for adding our new 'var/in' construct is to
  514. extend the lexer. As before, this is pretty trivial, the code looks like
  515. this:
  516. .. code-block:: c++
  517. enum Token {
  518. ...
  519. // var definition
  520. tok_var = -13
  521. ...
  522. }
  523. ...
  524. static int gettok() {
  525. ...
  526. if (IdentifierStr == "in")
  527. return tok_in;
  528. if (IdentifierStr == "binary")
  529. return tok_binary;
  530. if (IdentifierStr == "unary")
  531. return tok_unary;
  532. if (IdentifierStr == "var")
  533. return tok_var;
  534. return tok_identifier;
  535. ...
  536. The next step is to define the AST node that we will construct. For
  537. var/in, it looks like this:
  538. .. code-block:: c++
  539. /// VarExprAST - Expression class for var/in
  540. class VarExprAST : public ExprAST {
  541. std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
  542. std::unique_ptr<ExprAST> Body;
  543. public:
  544. VarExprAST(std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
  545. std::unique_ptr<ExprAST> Body)
  546. : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
  547. Value *codegen() override;
  548. };
  549. var/in allows a list of names to be defined all at once, and each name
  550. can optionally have an initializer value. As such, we capture this
  551. information in the VarNames vector. Also, var/in has a body, this body
  552. is allowed to access the variables defined by the var/in.
  553. With this in place, we can define the parser pieces. The first thing we
  554. do is add it as a primary expression:
  555. .. code-block:: c++
  556. /// primary
  557. /// ::= identifierexpr
  558. /// ::= numberexpr
  559. /// ::= parenexpr
  560. /// ::= ifexpr
  561. /// ::= forexpr
  562. /// ::= varexpr
  563. static std::unique_ptr<ExprAST> ParsePrimary() {
  564. switch (CurTok) {
  565. default:
  566. return LogError("unknown token when expecting an expression");
  567. case tok_identifier:
  568. return ParseIdentifierExpr();
  569. case tok_number:
  570. return ParseNumberExpr();
  571. case '(':
  572. return ParseParenExpr();
  573. case tok_if:
  574. return ParseIfExpr();
  575. case tok_for:
  576. return ParseForExpr();
  577. case tok_var:
  578. return ParseVarExpr();
  579. }
  580. }
  581. Next we define ParseVarExpr:
  582. .. code-block:: c++
  583. /// varexpr ::= 'var' identifier ('=' expression)?
  584. // (',' identifier ('=' expression)?)* 'in' expression
  585. static std::unique_ptr<ExprAST> ParseVarExpr() {
  586. getNextToken(); // eat the var.
  587. std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
  588. // At least one variable name is required.
  589. if (CurTok != tok_identifier)
  590. return LogError("expected identifier after var");
  591. The first part of this code parses the list of identifier/expr pairs
  592. into the local ``VarNames`` vector.
  593. .. code-block:: c++
  594. while (1) {
  595. std::string Name = IdentifierStr;
  596. getNextToken(); // eat identifier.
  597. // Read the optional initializer.
  598. std::unique_ptr<ExprAST> Init;
  599. if (CurTok == '=') {
  600. getNextToken(); // eat the '='.
  601. Init = ParseExpression();
  602. if (!Init) return nullptr;
  603. }
  604. VarNames.push_back(std::make_pair(Name, std::move(Init)));
  605. // End of var list, exit loop.
  606. if (CurTok != ',') break;
  607. getNextToken(); // eat the ','.
  608. if (CurTok != tok_identifier)
  609. return LogError("expected identifier list after var");
  610. }
  611. Once all the variables are parsed, we then parse the body and create the
  612. AST node:
  613. .. code-block:: c++
  614. // At this point, we have to have 'in'.
  615. if (CurTok != tok_in)
  616. return LogError("expected 'in' keyword after 'var'");
  617. getNextToken(); // eat 'in'.
  618. auto Body = ParseExpression();
  619. if (!Body)
  620. return nullptr;
  621. return std::make_unique<VarExprAST>(std::move(VarNames),
  622. std::move(Body));
  623. }
  624. Now that we can parse and represent the code, we need to support
  625. emission of LLVM IR for it. This code starts out with:
  626. .. code-block:: c++
  627. Value *VarExprAST::codegen() {
  628. std::vector<AllocaInst *> OldBindings;
  629. Function *TheFunction = Builder.GetInsertBlock()->getParent();
  630. // Register all variables and emit their initializer.
  631. for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
  632. const std::string &VarName = VarNames[i].first;
  633. ExprAST *Init = VarNames[i].second.get();
  634. Basically it loops over all the variables, installing them one at a
  635. time. For each variable we put into the symbol table, we remember the
  636. previous value that we replace in OldBindings.
  637. .. code-block:: c++
  638. // Emit the initializer before adding the variable to scope, this prevents
  639. // the initializer from referencing the variable itself, and permits stuff
  640. // like this:
  641. // var a = 1 in
  642. // var a = a in ... # refers to outer 'a'.
  643. Value *InitVal;
  644. if (Init) {
  645. InitVal = Init->codegen();
  646. if (!InitVal)
  647. return nullptr;
  648. } else { // If not specified, use 0.0.
  649. InitVal = ConstantFP::get(TheContext, APFloat(0.0));
  650. }
  651. AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
  652. Builder.CreateStore(InitVal, Alloca);
  653. // Remember the old variable binding so that we can restore the binding when
  654. // we unrecurse.
  655. OldBindings.push_back(NamedValues[VarName]);
  656. // Remember this binding.
  657. NamedValues[VarName] = Alloca;
  658. }
  659. There are more comments here than code. The basic idea is that we emit
  660. the initializer, create the alloca, then update the symbol table to
  661. point to it. Once all the variables are installed in the symbol table,
  662. we evaluate the body of the var/in expression:
  663. .. code-block:: c++
  664. // Codegen the body, now that all vars are in scope.
  665. Value *BodyVal = Body->codegen();
  666. if (!BodyVal)
  667. return nullptr;
  668. Finally, before returning, we restore the previous variable bindings:
  669. .. code-block:: c++
  670. // Pop all our variables from scope.
  671. for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
  672. NamedValues[VarNames[i].first] = OldBindings[i];
  673. // Return the body computation.
  674. return BodyVal;
  675. }
  676. The end result of all of this is that we get properly scoped variable
  677. definitions, and we even (trivially) allow mutation of them :).
  678. With this, we completed what we set out to do. Our nice iterative fib
  679. example from the intro compiles and runs just fine. The mem2reg pass
  680. optimizes all of our stack variables into SSA registers, inserting PHI
  681. nodes where needed, and our front-end remains simple: no "iterated
  682. dominance frontier" computation anywhere in sight.
  683. Full Code Listing
  684. =================
  685. Here is the complete code listing for our running example, enhanced with
  686. mutable variables and var/in support. To build this example, use:
  687. .. code-block:: bash
  688. # Compile
  689. clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core mcjit native` -O3 -o toy
  690. # Run
  691. ./toy
  692. Here is the code:
  693. .. literalinclude:: ../../../examples/Kaleidoscope/Chapter7/toy.cpp
  694. :language: c++
  695. `Next: Compiling to Object Code <LangImpl08.html>`_