OCamlLangImpl7.rst 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723
  1. =======================================================
  2. Kaleidoscope: Extending the Language: Mutable Variables
  3. =======================================================
  4. .. contents::
  5. :local:
  6. Chapter 7 Introduction
  7. ======================
  8. Welcome to Chapter 7 of the "`Implementing a language with
  9. LLVM <index.html>`_" tutorial. In chapters 1 through 6, we've built a
  10. very respectable, albeit simple, `functional programming
  11. language <http://en.wikipedia.org/wiki/Functional_programming>`_. In our
  12. journey, we learned some parsing techniques, how to build and represent
  13. an AST, how to build LLVM IR, and how to optimize the resultant code as
  14. well as JIT compile it.
  15. While Kaleidoscope is interesting as a functional language, the fact
  16. that it is functional makes it "too easy" to generate LLVM IR for it. In
  17. particular, a functional language makes it very easy to build LLVM IR
  18. directly in `SSA
  19. form <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_.
  20. Since LLVM requires that the input code be in SSA form, this is a very
  21. nice property and it is often unclear to newcomers how to generate code
  22. for an imperative language with mutable variables.
  23. The short (and happy) summary of this chapter is that there is no need
  24. for your front-end to build SSA form: LLVM provides highly tuned and
  25. well tested support for this, though the way it works is a bit
  26. unexpected for some.
  27. Why is this a hard problem?
  28. ===========================
  29. To understand why mutable variables cause complexities in SSA
  30. construction, consider this extremely simple C example:
  31. .. code-block:: c
  32. int G, H;
  33. int test(_Bool Condition) {
  34. int X;
  35. if (Condition)
  36. X = G;
  37. else
  38. X = H;
  39. return X;
  40. }
  41. In this case, we have the variable "X", whose value depends on the path
  42. executed in the program. Because there are two different possible values
  43. for X before the return instruction, a PHI node is inserted to merge the
  44. two values. The LLVM IR that we want for this example looks like this:
  45. .. code-block:: llvm
  46. @G = weak global i32 0 ; type of @G is i32*
  47. @H = weak global i32 0 ; type of @H is i32*
  48. define i32 @test(i1 %Condition) {
  49. entry:
  50. br i1 %Condition, label %cond_true, label %cond_false
  51. cond_true:
  52. %X.0 = load i32* @G
  53. br label %cond_next
  54. cond_false:
  55. %X.1 = load i32* @H
  56. br label %cond_next
  57. cond_next:
  58. %X.2 = phi i32 [ %X.1, %cond_false ], [ %X.0, %cond_true ]
  59. ret i32 %X.2
  60. }
  61. In this example, the loads from the G and H global variables are
  62. explicit in the LLVM IR, and they live in the then/else branches of the
  63. if statement (cond\_true/cond\_false). In order to merge the incoming
  64. values, the X.2 phi node in the cond\_next block selects the right value
  65. to use based on where control flow is coming from: if control flow comes
  66. from the cond\_false block, X.2 gets the value of X.1. Alternatively, if
  67. control flow comes from cond\_true, it gets the value of X.0. The intent
  68. of this chapter is not to explain the details of SSA form. For more
  69. information, see one of the many `online
  70. references <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_.
  71. The question for this article is "who places the phi nodes when lowering
  72. assignments to mutable variables?". The issue here is that LLVM
  73. *requires* that its IR be in SSA form: there is no "non-ssa" mode for
  74. it. However, SSA construction requires non-trivial algorithms and data
  75. structures, so it is inconvenient and wasteful for every front-end to
  76. have to reproduce this logic.
  77. Memory in LLVM
  78. ==============
  79. The 'trick' here is that while LLVM does require all register values to
  80. be in SSA form, it does not require (or permit) memory objects to be in
  81. SSA form. In the example above, note that the loads from G and H are
  82. direct accesses to G and H: they are not renamed or versioned. This
  83. differs from some other compiler systems, which do try to version memory
  84. objects. In LLVM, instead of encoding dataflow analysis of memory into
  85. the LLVM IR, it is handled with `Analysis
  86. Passes <../WritingAnLLVMPass.html>`_ which are computed on demand.
  87. With this in mind, the high-level idea is that we want to make a stack
  88. variable (which lives in memory, because it is on the stack) for each
  89. mutable object in a function. To take advantage of this trick, we need
  90. to talk about how LLVM represents stack variables.
  91. In LLVM, all memory accesses are explicit with load/store instructions,
  92. and it is carefully designed not to have (or need) an "address-of"
  93. operator. Notice how the type of the @G/@H global variables is actually
  94. "i32\*" even though the variable is defined as "i32". What this means is
  95. that @G defines *space* for an i32 in the global data area, but its
  96. *name* actually refers to the address for that space. Stack variables
  97. work the same way, except that instead of being declared with global
  98. variable definitions, they are declared with the `LLVM alloca
  99. instruction <../LangRef.html#alloca-instruction>`_:
  100. .. code-block:: llvm
  101. define i32 @example() {
  102. entry:
  103. %X = alloca i32 ; type of %X is i32*.
  104. ...
  105. %tmp = load i32* %X ; load the stack value %X from the stack.
  106. %tmp2 = add i32 %tmp, 1 ; increment it
  107. store i32 %tmp2, i32* %X ; store it back
  108. ...
  109. This code shows an example of how you can declare and manipulate a stack
  110. variable in the LLVM IR. Stack memory allocated with the alloca
  111. instruction is fully general: you can pass the address of the stack slot
  112. to functions, you can store it in other variables, etc. In our example
  113. above, we could rewrite the example to use the alloca technique to avoid
  114. using a PHI node:
  115. .. code-block:: llvm
  116. @G = weak global i32 0 ; type of @G is i32*
  117. @H = weak global i32 0 ; type of @H is i32*
  118. define i32 @test(i1 %Condition) {
  119. entry:
  120. %X = alloca i32 ; type of %X is i32*.
  121. br i1 %Condition, label %cond_true, label %cond_false
  122. cond_true:
  123. %X.0 = load i32* @G
  124. store i32 %X.0, i32* %X ; Update X
  125. br label %cond_next
  126. cond_false:
  127. %X.1 = load i32* @H
  128. store i32 %X.1, i32* %X ; Update X
  129. br label %cond_next
  130. cond_next:
  131. %X.2 = load i32* %X ; Read X
  132. ret i32 %X.2
  133. }
  134. With this, we have discovered a way to handle arbitrary mutable
  135. variables without the need to create Phi nodes at all:
  136. #. Each mutable variable becomes a stack allocation.
  137. #. Each read of the variable becomes a load from the stack.
  138. #. Each update of the variable becomes a store to the stack.
  139. #. Taking the address of a variable just uses the stack address
  140. directly.
  141. While this solution has solved our immediate problem, it introduced
  142. another one: we have now apparently introduced a lot of stack traffic
  143. for very simple and common operations, a major performance problem.
  144. Fortunately for us, the LLVM optimizer has a highly-tuned optimization
  145. pass named "mem2reg" that handles this case, promoting allocas like this
  146. into SSA registers, inserting Phi nodes as appropriate. If you run this
  147. example through the pass, for example, you'll get:
  148. .. code-block:: bash
  149. $ llvm-as < example.ll | opt -mem2reg | llvm-dis
  150. @G = weak global i32 0
  151. @H = weak global i32 0
  152. define i32 @test(i1 %Condition) {
  153. entry:
  154. br i1 %Condition, label %cond_true, label %cond_false
  155. cond_true:
  156. %X.0 = load i32* @G
  157. br label %cond_next
  158. cond_false:
  159. %X.1 = load i32* @H
  160. br label %cond_next
  161. cond_next:
  162. %X.01 = phi i32 [ %X.1, %cond_false ], [ %X.0, %cond_true ]
  163. ret i32 %X.01
  164. }
  165. The mem2reg pass implements the standard "iterated dominance frontier"
  166. algorithm for constructing SSA form and has a number of optimizations
  167. that speed up (very common) degenerate cases. The mem2reg optimization
  168. pass is the answer to dealing with mutable variables, and we highly
  169. recommend that you depend on it. Note that mem2reg only works on
  170. variables in certain circumstances:
  171. #. mem2reg is alloca-driven: it looks for allocas and if it can handle
  172. them, it promotes them. It does not apply to global variables or heap
  173. allocations.
  174. #. mem2reg only looks for alloca instructions in the entry block of the
  175. function. Being in the entry block guarantees that the alloca is only
  176. executed once, which makes analysis simpler.
  177. #. mem2reg only promotes allocas whose uses are direct loads and stores.
  178. If the address of the stack object is passed to a function, or if any
  179. funny pointer arithmetic is involved, the alloca will not be
  180. promoted.
  181. #. mem2reg only works on allocas of `first
  182. class <../LangRef.html#first-class-types>`_ values (such as pointers,
  183. scalars and vectors), and only if the array size of the allocation is
  184. 1 (or missing in the .ll file). mem2reg is not capable of promoting
  185. structs or arrays to registers. Note that the "sroa" pass is
  186. more powerful and can promote structs, "unions", and arrays in many
  187. cases.
  188. All of these properties are easy to satisfy for most imperative
  189. languages, and we'll illustrate it below with Kaleidoscope. The final
  190. question you may be asking is: should I bother with this nonsense for my
  191. front-end? Wouldn't it be better if I just did SSA construction
  192. directly, avoiding use of the mem2reg optimization pass? In short, we
  193. strongly recommend that you use this technique for building SSA form,
  194. unless there is an extremely good reason not to. Using this technique
  195. is:
  196. - Proven and well tested: clang uses this technique
  197. for local mutable variables. As such, the most common clients of LLVM
  198. are using this to handle a bulk of their variables. You can be sure
  199. that bugs are found fast and fixed early.
  200. - Extremely Fast: mem2reg has a number of special cases that make it
  201. fast in common cases as well as fully general. For example, it has
  202. fast-paths for variables that are only used in a single block,
  203. variables that only have one assignment point, good heuristics to
  204. avoid insertion of unneeded phi nodes, etc.
  205. - Needed for debug info generation: `Debug information in
  206. LLVM <../SourceLevelDebugging.html>`_ relies on having the address of
  207. the variable exposed so that debug info can be attached to it. This
  208. technique dovetails very naturally with this style of debug info.
  209. If nothing else, this makes it much easier to get your front-end up and
  210. running, and is very simple to implement. Lets extend Kaleidoscope with
  211. mutable variables now!
  212. Mutable Variables in Kaleidoscope
  213. =================================
  214. Now that we know the sort of problem we want to tackle, lets see what
  215. this looks like in the context of our little Kaleidoscope language.
  216. We're going to add two features:
  217. #. The ability to mutate variables with the '=' operator.
  218. #. The ability to define new variables.
  219. While the first item is really what this is about, we only have
  220. variables for incoming arguments as well as for induction variables, and
  221. redefining those only goes so far :). Also, the ability to define new
  222. variables is a useful thing regardless of whether you will be mutating
  223. them. Here's a motivating example that shows how we could use these:
  224. ::
  225. # Define ':' for sequencing: as a low-precedence operator that ignores operands
  226. # and just returns the RHS.
  227. def binary : 1 (x y) y;
  228. # Recursive fib, we could do this before.
  229. def fib(x)
  230. if (x < 3) then
  231. 1
  232. else
  233. fib(x-1)+fib(x-2);
  234. # Iterative fib.
  235. def fibi(x)
  236. var a = 1, b = 1, c in
  237. (for i = 3, i < x in
  238. c = a + b :
  239. a = b :
  240. b = c) :
  241. b;
  242. # Call it.
  243. fibi(10);
  244. In order to mutate variables, we have to change our existing variables
  245. to use the "alloca trick". Once we have that, we'll add our new
  246. operator, then extend Kaleidoscope to support new variable definitions.
  247. Adjusting Existing Variables for Mutation
  248. =========================================
  249. The symbol table in Kaleidoscope is managed at code generation time by
  250. the '``named_values``' map. This map currently keeps track of the LLVM
  251. "Value\*" that holds the double value for the named variable. In order
  252. to support mutation, we need to change this slightly, so that it
  253. ``named_values`` holds the *memory location* of the variable in
  254. question. Note that this change is a refactoring: it changes the
  255. structure of the code, but does not (by itself) change the behavior of
  256. the compiler. All of these changes are isolated in the Kaleidoscope code
  257. 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. ``named_values`` map so that it maps to AllocaInst\* instead of Value\*.
  265. Once we do this, the C++ compiler will tell us what parts of the code we
  266. need to update:
  267. **Note:** the ocaml bindings currently model both ``Value*``'s and
  268. ``AllocInst*``'s as ``Llvm.llvalue``'s, but this may change in the future
  269. to be more type safe.
  270. .. code-block:: ocaml
  271. let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
  272. Also, since we will need to create these alloca's, we'll use a helper
  273. function that ensures that the allocas are created in the entry block of
  274. the function:
  275. .. code-block:: ocaml
  276. (* Create an alloca instruction in the entry block of the function. This
  277. * is used for mutable variables etc. *)
  278. let create_entry_block_alloca the_function var_name =
  279. let builder = builder_at (instr_begin (entry_block the_function)) in
  280. build_alloca double_type var_name builder
  281. This funny looking code creates an ``Llvm.llbuilder`` object that is
  282. pointing at the first instruction of the entry block. It then creates an
  283. alloca with the expected name and returns it. Because all values in
  284. Kaleidoscope are doubles, there is no need to pass in a type to use.
  285. With this in place, the first functionality change we want to make is to
  286. variable references. In our new scheme, variables live on the stack, so
  287. code generating a reference to them actually needs to produce a load
  288. from the stack slot:
  289. .. code-block:: ocaml
  290. let rec codegen_expr = function
  291. ...
  292. | Ast.Variable name ->
  293. let v = try Hashtbl.find named_values name with
  294. | Not_found -> raise (Error "unknown variable name")
  295. in
  296. (* Load the value. *)
  297. build_load v name builder
  298. As you can see, this is pretty straightforward. Now we need to update
  299. the things that define the variables to set up the alloca. We'll start
  300. with ``codegen_expr Ast.For ...`` (see the `full code listing <#id1>`_
  301. for the unabridged code):
  302. .. code-block:: ocaml
  303. | Ast.For (var_name, start, end_, step, body) ->
  304. let the_function = block_parent (insertion_block builder) in
  305. (* Create an alloca for the variable in the entry block. *)
  306. let alloca = create_entry_block_alloca the_function var_name in
  307. (* Emit the start code first, without 'variable' in scope. *)
  308. let start_val = codegen_expr start in
  309. (* Store the value into the alloca. *)
  310. ignore(build_store start_val alloca builder);
  311. ...
  312. (* Within the loop, the variable is defined equal to the PHI node. If it
  313. * shadows an existing variable, we have to restore it, so save it
  314. * now. *)
  315. let old_val =
  316. try Some (Hashtbl.find named_values var_name) with Not_found -> None
  317. in
  318. Hashtbl.add named_values var_name alloca;
  319. ...
  320. (* Compute the end condition. *)
  321. let end_cond = codegen_expr end_ in
  322. (* Reload, increment, and restore the alloca. This handles the case where
  323. * the body of the loop mutates the variable. *)
  324. let cur_var = build_load alloca var_name builder in
  325. let next_var = build_add cur_var step_val "nextvar" builder in
  326. ignore(build_store next_var alloca builder);
  327. ...
  328. This code is virtually identical to the code `before we allowed mutable
  329. variables <OCamlLangImpl5.html#code-generation-for-the-for-loop>`_. The big difference is that
  330. we no longer have to construct a PHI node, and we use load/store to
  331. access the variable as needed.
  332. To support mutable argument variables, we need to also make allocas for
  333. them. The code for this is also pretty simple:
  334. .. code-block:: ocaml
  335. (* Create an alloca for each argument and register the argument in the symbol
  336. * table so that references to it will succeed. *)
  337. let create_argument_allocas the_function proto =
  338. let args = match proto with
  339. | Ast.Prototype (_, args) | Ast.BinOpPrototype (_, args, _) -> args
  340. in
  341. Array.iteri (fun i ai ->
  342. let var_name = args.(i) in
  343. (* Create an alloca for this variable. *)
  344. let alloca = create_entry_block_alloca the_function var_name in
  345. (* Store the initial value into the alloca. *)
  346. ignore(build_store ai alloca builder);
  347. (* Add arguments to variable symbol table. *)
  348. Hashtbl.add named_values var_name alloca;
  349. ) (params the_function)
  350. For each argument, we make an alloca, store the input value to the
  351. function into the alloca, and register the alloca as the memory location
  352. for the argument. This method gets invoked by ``Codegen.codegen_func``
  353. right after it sets up the entry block for the function.
  354. The final missing piece is adding the mem2reg pass, which allows us to
  355. get good codegen once again:
  356. .. code-block:: ocaml
  357. let main () =
  358. ...
  359. let the_fpm = PassManager.create_function Codegen.the_module in
  360. (* Set up the optimizer pipeline. Start with registering info about how the
  361. * target lays out data structures. *)
  362. DataLayout.add (ExecutionEngine.target_data the_execution_engine) the_fpm;
  363. (* Promote allocas to registers. *)
  364. add_memory_to_register_promotion the_fpm;
  365. (* Do simple "peephole" optimizations and bit-twiddling optzn. *)
  366. add_instruction_combining the_fpm;
  367. (* reassociate expressions. *)
  368. add_reassociation the_fpm;
  369. It is interesting to see what the code looks like before and after the
  370. mem2reg optimization runs. For example, this is the before/after code
  371. for our recursive fib function. Before the optimization:
  372. .. code-block:: llvm
  373. define double @fib(double %x) {
  374. entry:
  375. %x1 = alloca double
  376. store double %x, double* %x1
  377. %x2 = load double* %x1
  378. %cmptmp = fcmp ult double %x2, 3.000000e+00
  379. %booltmp = uitofp i1 %cmptmp to double
  380. %ifcond = fcmp one double %booltmp, 0.000000e+00
  381. br i1 %ifcond, label %then, label %else
  382. then: ; preds = %entry
  383. br label %ifcont
  384. else: ; preds = %entry
  385. %x3 = load double* %x1
  386. %subtmp = fsub double %x3, 1.000000e+00
  387. %calltmp = call double @fib(double %subtmp)
  388. %x4 = load double* %x1
  389. %subtmp5 = fsub double %x4, 2.000000e+00
  390. %calltmp6 = call double @fib(double %subtmp5)
  391. %addtmp = fadd double %calltmp, %calltmp6
  392. br label %ifcont
  393. ifcont: ; preds = %else, %then
  394. %iftmp = phi double [ 1.000000e+00, %then ], [ %addtmp, %else ]
  395. ret double %iftmp
  396. }
  397. Here there is only one variable (x, the input argument) but you can
  398. still see the extremely simple-minded code generation strategy we are
  399. using. In the entry block, an alloca is created, and the initial input
  400. value is stored into it. Each reference to the variable does a reload
  401. from the stack. Also, note that we didn't modify the if/then/else
  402. expression, so it still inserts a PHI node. While we could make an
  403. alloca for it, it is actually easier to create a PHI node for it, so we
  404. still just make the PHI.
  405. Here is the code after the mem2reg pass runs:
  406. .. code-block:: llvm
  407. define double @fib(double %x) {
  408. entry:
  409. %cmptmp = fcmp ult double %x, 3.000000e+00
  410. %booltmp = uitofp i1 %cmptmp to double
  411. %ifcond = fcmp one double %booltmp, 0.000000e+00
  412. br i1 %ifcond, label %then, label %else
  413. then:
  414. br label %ifcont
  415. else:
  416. %subtmp = fsub double %x, 1.000000e+00
  417. %calltmp = call double @fib(double %subtmp)
  418. %subtmp5 = fsub double %x, 2.000000e+00
  419. %calltmp6 = call double @fib(double %subtmp5)
  420. %addtmp = fadd double %calltmp, %calltmp6
  421. br label %ifcont
  422. ifcont: ; preds = %else, %then
  423. %iftmp = phi double [ 1.000000e+00, %then ], [ %addtmp, %else ]
  424. ret double %iftmp
  425. }
  426. This is a trivial case for mem2reg, since there are no redefinitions of
  427. the variable. The point of showing this is to calm your tension about
  428. inserting such blatent inefficiencies :).
  429. After the rest of the optimizers run, we get:
  430. .. code-block:: llvm
  431. define double @fib(double %x) {
  432. entry:
  433. %cmptmp = fcmp ult double %x, 3.000000e+00
  434. %booltmp = uitofp i1 %cmptmp to double
  435. %ifcond = fcmp ueq double %booltmp, 0.000000e+00
  436. br i1 %ifcond, label %else, label %ifcont
  437. else:
  438. %subtmp = fsub double %x, 1.000000e+00
  439. %calltmp = call double @fib(double %subtmp)
  440. %subtmp5 = fsub double %x, 2.000000e+00
  441. %calltmp6 = call double @fib(double %subtmp5)
  442. %addtmp = fadd double %calltmp, %calltmp6
  443. ret double %addtmp
  444. ifcont:
  445. ret double 1.000000e+00
  446. }
  447. Here we see that the simplifycfg pass decided to clone the return
  448. instruction into the end of the 'else' block. This allowed it to
  449. eliminate some branches and the PHI node.
  450. Now that all symbol table references are updated to use stack variables,
  451. we'll add the assignment operator.
  452. New Assignment Operator
  453. =======================
  454. With our current framework, adding a new assignment operator is really
  455. simple. We will parse it just like any other binary operator, but handle
  456. it internally (instead of allowing the user to define it). The first
  457. step is to set a precedence:
  458. .. code-block:: ocaml
  459. let main () =
  460. (* Install standard binary operators.
  461. * 1 is the lowest precedence. *)
  462. Hashtbl.add Parser.binop_precedence '=' 2;
  463. Hashtbl.add Parser.binop_precedence '<' 10;
  464. Hashtbl.add Parser.binop_precedence '+' 20;
  465. Hashtbl.add Parser.binop_precedence '-' 20;
  466. ...
  467. Now that the parser knows the precedence of the binary operator, it
  468. takes care of all the parsing and AST generation. We just need to
  469. implement codegen for the assignment operator. This looks like:
  470. .. code-block:: ocaml
  471. let rec codegen_expr = function
  472. begin match op with
  473. | '=' ->
  474. (* Special case '=' because we don't want to emit the LHS as an
  475. * expression. *)
  476. let name =
  477. match lhs with
  478. | Ast.Variable name -> name
  479. | _ -> raise (Error "destination of '=' must be a variable")
  480. in
  481. Unlike the rest of the binary operators, our assignment operator doesn't
  482. follow the "emit LHS, emit RHS, do computation" model. As such, it is
  483. handled as a special case before the other binary operators are handled.
  484. The other strange thing is that it requires the LHS to be a variable. It
  485. is invalid to have "(x+1) = expr" - only things like "x = expr" are
  486. allowed.
  487. .. code-block:: ocaml
  488. (* Codegen the rhs. *)
  489. let val_ = codegen_expr rhs in
  490. (* Lookup the name. *)
  491. let variable = try Hashtbl.find named_values name with
  492. | Not_found -> raise (Error "unknown variable name")
  493. in
  494. ignore(build_store val_ variable builder);
  495. val_
  496. | _ ->
  497. ...
  498. Once we have the variable, codegen'ing the assignment is
  499. straightforward: we emit the RHS of the assignment, create a store, and
  500. return the computed value. Returning a value allows for chained
  501. assignments like "X = (Y = Z)".
  502. Now that we have an assignment operator, we can mutate loop variables
  503. and arguments. For example, we can now run code like this:
  504. ::
  505. # Function to print a double.
  506. extern printd(x);
  507. # Define ':' for sequencing: as a low-precedence operator that ignores operands
  508. # and just returns the RHS.
  509. def binary : 1 (x y) y;
  510. def test(x)
  511. printd(x) :
  512. x = 4 :
  513. printd(x);
  514. test(123);
  515. When run, this example prints "123" and then "4", showing that we did
  516. actually mutate the value! Okay, we have now officially implemented our
  517. goal: getting this to work requires SSA construction in the general
  518. case. However, to be really useful, we want the ability to define our
  519. own local variables, lets add this next!
  520. User-defined Local Variables
  521. ============================
  522. Adding var/in is just like any other other extensions we made to
  523. Kaleidoscope: we extend the lexer, the parser, the AST and the code
  524. generator. The first step for adding our new 'var/in' construct is to
  525. extend the lexer. As before, this is pretty trivial, the code looks like
  526. this:
  527. .. code-block:: ocaml
  528. type token =
  529. ...
  530. (* var definition *)
  531. | Var
  532. ...
  533. and lex_ident buffer = parser
  534. ...
  535. | "in" -> [< 'Token.In; stream >]
  536. | "binary" -> [< 'Token.Binary; stream >]
  537. | "unary" -> [< 'Token.Unary; stream >]
  538. | "var" -> [< 'Token.Var; stream >]
  539. ...
  540. The next step is to define the AST node that we will construct. For
  541. var/in, it looks like this:
  542. .. code-block:: ocaml
  543. type expr =
  544. ...
  545. (* variant for var/in. *)
  546. | Var of (string * expr option) array * expr
  547. ...
  548. var/in allows a list of names to be defined all at once, and each name
  549. can optionally have an initializer value. As such, we capture this
  550. information in the VarNames vector. Also, var/in has a body, this body
  551. is allowed to access the variables defined by the var/in.
  552. With this in place, we can define the parser pieces. The first thing we
  553. do is add it as a primary expression:
  554. .. code-block:: ocaml
  555. (* primary
  556. * ::= identifier
  557. * ::= numberexpr
  558. * ::= parenexpr
  559. * ::= ifexpr
  560. * ::= forexpr
  561. * ::= varexpr *)
  562. let rec parse_primary = parser
  563. ...
  564. (* varexpr
  565. * ::= 'var' identifier ('=' expression?
  566. * (',' identifier ('=' expression)?)* 'in' expression *)
  567. | [< 'Token.Var;
  568. (* At least one variable name is required. *)
  569. 'Token.Ident id ?? "expected identifier after var";
  570. init=parse_var_init;
  571. var_names=parse_var_names [(id, init)];
  572. (* At this point, we have to have 'in'. *)
  573. 'Token.In ?? "expected 'in' keyword after 'var'";
  574. body=parse_expr >] ->
  575. Ast.Var (Array.of_list (List.rev var_names), body)
  576. ...
  577. and parse_var_init = parser
  578. (* read in the optional initializer. *)
  579. | [< 'Token.Kwd '='; e=parse_expr >] -> Some e
  580. | [< >] -> None
  581. and parse_var_names accumulator = parser
  582. | [< 'Token.Kwd ',';
  583. 'Token.Ident id ?? "expected identifier list after var";
  584. init=parse_var_init;
  585. e=parse_var_names ((id, init) :: accumulator) >] -> e
  586. | [< >] -> accumulator
  587. Now that we can parse and represent the code, we need to support
  588. emission of LLVM IR for it. This code starts out with:
  589. .. code-block:: ocaml
  590. let rec codegen_expr = function
  591. ...
  592. | Ast.Var (var_names, body)
  593. let old_bindings = ref [] in
  594. let the_function = block_parent (insertion_block builder) in
  595. (* Register all variables and emit their initializer. *)
  596. Array.iter (fun (var_name, init) ->
  597. Basically it loops over all the variables, installing them one at a
  598. time. For each variable we put into the symbol table, we remember the
  599. previous value that we replace in OldBindings.
  600. .. code-block:: ocaml
  601. (* Emit the initializer before adding the variable to scope, this
  602. * prevents the initializer from referencing the variable itself, and
  603. * permits stuff like this:
  604. * var a = 1 in
  605. * var a = a in ... # refers to outer 'a'. *)
  606. let init_val =
  607. match init with
  608. | Some init -> codegen_expr init
  609. (* If not specified, use 0.0. *)
  610. | None -> const_float double_type 0.0
  611. in
  612. let alloca = create_entry_block_alloca the_function var_name in
  613. ignore(build_store init_val alloca builder);
  614. (* Remember the old variable binding so that we can restore the binding
  615. * when we unrecurse. *)
  616. begin
  617. try
  618. let old_value = Hashtbl.find named_values var_name in
  619. old_bindings := (var_name, old_value) :: !old_bindings;
  620. with Not_found > ()
  621. end;
  622. (* Remember this binding. *)
  623. Hashtbl.add named_values var_name alloca;
  624. ) var_names;
  625. There are more comments here than code. The basic idea is that we emit
  626. the initializer, create the alloca, then update the symbol table to
  627. point to it. Once all the variables are installed in the symbol table,
  628. we evaluate the body of the var/in expression:
  629. .. code-block:: ocaml
  630. (* Codegen the body, now that all vars are in scope. *)
  631. let body_val = codegen_expr body in
  632. Finally, before returning, we restore the previous variable bindings:
  633. .. code-block:: ocaml
  634. (* Pop all our variables from scope. *)
  635. List.iter (fun (var_name, old_value) ->
  636. Hashtbl.add named_values var_name old_value
  637. ) !old_bindings;
  638. (* Return the body computation. *)
  639. body_val
  640. The end result of all of this is that we get properly scoped variable
  641. definitions, and we even (trivially) allow mutation of them :).
  642. With this, we completed what we set out to do. Our nice iterative fib
  643. example from the intro compiles and runs just fine. The mem2reg pass
  644. optimizes all of our stack variables into SSA registers, inserting PHI
  645. nodes where needed, and our front-end remains simple: no "iterated
  646. dominance frontier" computation anywhere in sight.
  647. Full Code Listing
  648. =================
  649. Here is the complete code listing for our running example, enhanced with
  650. mutable variables and var/in support. To build this example, use:
  651. .. code-block:: bash
  652. # Compile
  653. ocamlbuild toy.byte
  654. # Run
  655. ./toy.byte
  656. Here is the code:
  657. \_tags:
  658. ::
  659. <{lexer,parser}.ml>: use_camlp4, pp(camlp4of)
  660. <*.{byte,native}>: g++, use_llvm, use_llvm_analysis
  661. <*.{byte,native}>: use_llvm_executionengine, use_llvm_target
  662. <*.{byte,native}>: use_llvm_scalar_opts, use_bindings
  663. myocamlbuild.ml:
  664. .. code-block:: ocaml
  665. open Ocamlbuild_plugin;;
  666. ocaml_lib ~extern:true "llvm";;
  667. ocaml_lib ~extern:true "llvm_analysis";;
  668. ocaml_lib ~extern:true "llvm_executionengine";;
  669. ocaml_lib ~extern:true "llvm_target";;
  670. ocaml_lib ~extern:true "llvm_scalar_opts";;
  671. flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"; A"-cclib"; A"-rdynamic"]);;
  672. dep ["link"; "ocaml"; "use_bindings"] ["bindings.o"];;
  673. token.ml:
  674. .. code-block:: ocaml
  675. (*===----------------------------------------------------------------------===
  676. * Lexer Tokens
  677. *===----------------------------------------------------------------------===*)
  678. (* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
  679. * these others for known things. *)
  680. type token =
  681. (* commands *)
  682. | Def | Extern
  683. (* primary *)
  684. | Ident of string | Number of float
  685. (* unknown *)
  686. | Kwd of char
  687. (* control *)
  688. | If | Then | Else
  689. | For | In
  690. (* operators *)
  691. | Binary | Unary
  692. (* var definition *)
  693. | Var
  694. lexer.ml:
  695. .. code-block:: ocaml
  696. (*===----------------------------------------------------------------------===
  697. * Lexer
  698. *===----------------------------------------------------------------------===*)
  699. let rec lex = parser
  700. (* Skip any whitespace. *)
  701. | [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream
  702. (* identifier: [a-zA-Z][a-zA-Z0-9] *)
  703. | [< ' ('A' .. 'Z' | 'a' .. 'z' as c); stream >] ->
  704. let buffer = Buffer.create 1 in
  705. Buffer.add_char buffer c;
  706. lex_ident buffer stream
  707. (* number: [0-9.]+ *)
  708. | [< ' ('0' .. '9' as c); stream >] ->
  709. let buffer = Buffer.create 1 in
  710. Buffer.add_char buffer c;
  711. lex_number buffer stream
  712. (* Comment until end of line. *)
  713. | [< ' ('#'); stream >] ->
  714. lex_comment stream
  715. (* Otherwise, just return the character as its ascii value. *)
  716. | [< 'c; stream >] ->
  717. [< 'Token.Kwd c; lex stream >]
  718. (* end of stream. *)
  719. | [< >] -> [< >]
  720. and lex_number buffer = parser
  721. | [< ' ('0' .. '9' | '.' as c); stream >] ->
  722. Buffer.add_char buffer c;
  723. lex_number buffer stream
  724. | [< stream=lex >] ->
  725. [< 'Token.Number (float_of_string (Buffer.contents buffer)); stream >]
  726. and lex_ident buffer = parser
  727. | [< ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream >] ->
  728. Buffer.add_char buffer c;
  729. lex_ident buffer stream
  730. | [< stream=lex >] ->
  731. match Buffer.contents buffer with
  732. | "def" -> [< 'Token.Def; stream >]
  733. | "extern" -> [< 'Token.Extern; stream >]
  734. | "if" -> [< 'Token.If; stream >]
  735. | "then" -> [< 'Token.Then; stream >]
  736. | "else" -> [< 'Token.Else; stream >]
  737. | "for" -> [< 'Token.For; stream >]
  738. | "in" -> [< 'Token.In; stream >]
  739. | "binary" -> [< 'Token.Binary; stream >]
  740. | "unary" -> [< 'Token.Unary; stream >]
  741. | "var" -> [< 'Token.Var; stream >]
  742. | id -> [< 'Token.Ident id; stream >]
  743. and lex_comment = parser
  744. | [< ' ('\n'); stream=lex >] -> stream
  745. | [< 'c; e=lex_comment >] -> e
  746. | [< >] -> [< >]
  747. ast.ml:
  748. .. code-block:: ocaml
  749. (*===----------------------------------------------------------------------===
  750. * Abstract Syntax Tree (aka Parse Tree)
  751. *===----------------------------------------------------------------------===*)
  752. (* expr - Base type for all expression nodes. *)
  753. type expr =
  754. (* variant for numeric literals like "1.0". *)
  755. | Number of float
  756. (* variant for referencing a variable, like "a". *)
  757. | Variable of string
  758. (* variant for a unary operator. *)
  759. | Unary of char * expr
  760. (* variant for a binary operator. *)
  761. | Binary of char * expr * expr
  762. (* variant for function calls. *)
  763. | Call of string * expr array
  764. (* variant for if/then/else. *)
  765. | If of expr * expr * expr
  766. (* variant for for/in. *)
  767. | For of string * expr * expr * expr option * expr
  768. (* variant for var/in. *)
  769. | Var of (string * expr option) array * expr
  770. (* proto - This type represents the "prototype" for a function, which captures
  771. * its name, and its argument names (thus implicitly the number of arguments the
  772. * function takes). *)
  773. type proto =
  774. | Prototype of string * string array
  775. | BinOpPrototype of string * string array * int
  776. (* func - This type represents a function definition itself. *)
  777. type func = Function of proto * expr
  778. parser.ml:
  779. .. code-block:: ocaml
  780. (*===---------------------------------------------------------------------===
  781. * Parser
  782. *===---------------------------------------------------------------------===*)
  783. (* binop_precedence - This holds the precedence for each binary operator that is
  784. * defined *)
  785. let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
  786. (* precedence - Get the precedence of the pending binary operator token. *)
  787. let precedence c = try Hashtbl.find binop_precedence c with Not_found -> -1
  788. (* primary
  789. * ::= identifier
  790. * ::= numberexpr
  791. * ::= parenexpr
  792. * ::= ifexpr
  793. * ::= forexpr
  794. * ::= varexpr *)
  795. let rec parse_primary = parser
  796. (* numberexpr ::= number *)
  797. | [< 'Token.Number n >] -> Ast.Number n
  798. (* parenexpr ::= '(' expression ')' *)
  799. | [< 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" >] -> e
  800. (* identifierexpr
  801. * ::= identifier
  802. * ::= identifier '(' argumentexpr ')' *)
  803. | [< 'Token.Ident id; stream >] ->
  804. let rec parse_args accumulator = parser
  805. | [< e=parse_expr; stream >] ->
  806. begin parser
  807. | [< 'Token.Kwd ','; e=parse_args (e :: accumulator) >] -> e
  808. | [< >] -> e :: accumulator
  809. end stream
  810. | [< >] -> accumulator
  811. in
  812. let rec parse_ident id = parser
  813. (* Call. *)
  814. | [< 'Token.Kwd '(';
  815. args=parse_args [];
  816. 'Token.Kwd ')' ?? "expected ')'">] ->
  817. Ast.Call (id, Array.of_list (List.rev args))
  818. (* Simple variable ref. *)
  819. | [< >] -> Ast.Variable id
  820. in
  821. parse_ident id stream
  822. (* ifexpr ::= 'if' expr 'then' expr 'else' expr *)
  823. | [< 'Token.If; c=parse_expr;
  824. 'Token.Then ?? "expected 'then'"; t=parse_expr;
  825. 'Token.Else ?? "expected 'else'"; e=parse_expr >] ->
  826. Ast.If (c, t, e)
  827. (* forexpr
  828. ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression *)
  829. | [< 'Token.For;
  830. 'Token.Ident id ?? "expected identifier after for";
  831. 'Token.Kwd '=' ?? "expected '=' after for";
  832. stream >] ->
  833. begin parser
  834. | [<
  835. start=parse_expr;
  836. 'Token.Kwd ',' ?? "expected ',' after for";
  837. end_=parse_expr;
  838. stream >] ->
  839. let step =
  840. begin parser
  841. | [< 'Token.Kwd ','; step=parse_expr >] -> Some step
  842. | [< >] -> None
  843. end stream
  844. in
  845. begin parser
  846. | [< 'Token.In; body=parse_expr >] ->
  847. Ast.For (id, start, end_, step, body)
  848. | [< >] ->
  849. raise (Stream.Error "expected 'in' after for")
  850. end stream
  851. | [< >] ->
  852. raise (Stream.Error "expected '=' after for")
  853. end stream
  854. (* varexpr
  855. * ::= 'var' identifier ('=' expression?
  856. * (',' identifier ('=' expression)?)* 'in' expression *)
  857. | [< 'Token.Var;
  858. (* At least one variable name is required. *)
  859. 'Token.Ident id ?? "expected identifier after var";
  860. init=parse_var_init;
  861. var_names=parse_var_names [(id, init)];
  862. (* At this point, we have to have 'in'. *)
  863. 'Token.In ?? "expected 'in' keyword after 'var'";
  864. body=parse_expr >] ->
  865. Ast.Var (Array.of_list (List.rev var_names), body)
  866. | [< >] -> raise (Stream.Error "unknown token when expecting an expression.")
  867. (* unary
  868. * ::= primary
  869. * ::= '!' unary *)
  870. and parse_unary = parser
  871. (* If this is a unary operator, read it. *)
  872. | [< 'Token.Kwd op when op != '(' && op != ')'; operand=parse_expr >] ->
  873. Ast.Unary (op, operand)
  874. (* If the current token is not an operator, it must be a primary expr. *)
  875. | [< stream >] -> parse_primary stream
  876. (* binoprhs
  877. * ::= ('+' primary)* *)
  878. and parse_bin_rhs expr_prec lhs stream =
  879. match Stream.peek stream with
  880. (* If this is a binop, find its precedence. *)
  881. | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c ->
  882. let token_prec = precedence c in
  883. (* If this is a binop that binds at least as tightly as the current binop,
  884. * consume it, otherwise we are done. *)
  885. if token_prec < expr_prec then lhs else begin
  886. (* Eat the binop. *)
  887. Stream.junk stream;
  888. (* Parse the primary expression after the binary operator. *)
  889. let rhs = parse_unary stream in
  890. (* Okay, we know this is a binop. *)
  891. let rhs =
  892. match Stream.peek stream with
  893. | Some (Token.Kwd c2) ->
  894. (* If BinOp binds less tightly with rhs than the operator after
  895. * rhs, let the pending operator take rhs as its lhs. *)
  896. let next_prec = precedence c2 in
  897. if token_prec < next_prec
  898. then parse_bin_rhs (token_prec + 1) rhs stream
  899. else rhs
  900. | _ -> rhs
  901. in
  902. (* Merge lhs/rhs. *)
  903. let lhs = Ast.Binary (c, lhs, rhs) in
  904. parse_bin_rhs expr_prec lhs stream
  905. end
  906. | _ -> lhs
  907. and parse_var_init = parser
  908. (* read in the optional initializer. *)
  909. | [< 'Token.Kwd '='; e=parse_expr >] -> Some e
  910. | [< >] -> None
  911. and parse_var_names accumulator = parser
  912. | [< 'Token.Kwd ',';
  913. 'Token.Ident id ?? "expected identifier list after var";
  914. init=parse_var_init;
  915. e=parse_var_names ((id, init) :: accumulator) >] -> e
  916. | [< >] -> accumulator
  917. (* expression
  918. * ::= primary binoprhs *)
  919. and parse_expr = parser
  920. | [< lhs=parse_unary; stream >] -> parse_bin_rhs 0 lhs stream
  921. (* prototype
  922. * ::= id '(' id* ')'
  923. * ::= binary LETTER number? (id, id)
  924. * ::= unary LETTER number? (id) *)
  925. let parse_prototype =
  926. let rec parse_args accumulator = parser
  927. | [< 'Token.Ident id; e=parse_args (id::accumulator) >] -> e
  928. | [< >] -> accumulator
  929. in
  930. let parse_operator = parser
  931. | [< 'Token.Unary >] -> "unary", 1
  932. | [< 'Token.Binary >] -> "binary", 2
  933. in
  934. let parse_binary_precedence = parser
  935. | [< 'Token.Number n >] -> int_of_float n
  936. | [< >] -> 30
  937. in
  938. parser
  939. | [< 'Token.Ident id;
  940. 'Token.Kwd '(' ?? "expected '(' in prototype";
  941. args=parse_args [];
  942. 'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
  943. (* success. *)
  944. Ast.Prototype (id, Array.of_list (List.rev args))
  945. | [< (prefix, kind)=parse_operator;
  946. 'Token.Kwd op ?? "expected an operator";
  947. (* Read the precedence if present. *)
  948. binary_precedence=parse_binary_precedence;
  949. 'Token.Kwd '(' ?? "expected '(' in prototype";
  950. args=parse_args [];
  951. 'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
  952. let name = prefix ^ (String.make 1 op) in
  953. let args = Array.of_list (List.rev args) in
  954. (* Verify right number of arguments for operator. *)
  955. if Array.length args != kind
  956. then raise (Stream.Error "invalid number of operands for operator")
  957. else
  958. if kind == 1 then
  959. Ast.Prototype (name, args)
  960. else
  961. Ast.BinOpPrototype (name, args, binary_precedence)
  962. | [< >] ->
  963. raise (Stream.Error "expected function name in prototype")
  964. (* definition ::= 'def' prototype expression *)
  965. let parse_definition = parser
  966. | [< 'Token.Def; p=parse_prototype; e=parse_expr >] ->
  967. Ast.Function (p, e)
  968. (* toplevelexpr ::= expression *)
  969. let parse_toplevel = parser
  970. | [< e=parse_expr >] ->
  971. (* Make an anonymous proto. *)
  972. Ast.Function (Ast.Prototype ("", [||]), e)
  973. (* external ::= 'extern' prototype *)
  974. let parse_extern = parser
  975. | [< 'Token.Extern; e=parse_prototype >] -> e
  976. codegen.ml:
  977. .. code-block:: ocaml
  978. (*===----------------------------------------------------------------------===
  979. * Code Generation
  980. *===----------------------------------------------------------------------===*)
  981. open Llvm
  982. exception Error of string
  983. let context = global_context ()
  984. let the_module = create_module context "my cool jit"
  985. let builder = builder context
  986. let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
  987. let double_type = double_type context
  988. (* Create an alloca instruction in the entry block of the function. This
  989. * is used for mutable variables etc. *)
  990. let create_entry_block_alloca the_function var_name =
  991. let builder = builder_at context (instr_begin (entry_block the_function)) in
  992. build_alloca double_type var_name builder
  993. let rec codegen_expr = function
  994. | Ast.Number n -> const_float double_type n
  995. | Ast.Variable name ->
  996. let v = try Hashtbl.find named_values name with
  997. | Not_found -> raise (Error "unknown variable name")
  998. in
  999. (* Load the value. *)
  1000. build_load v name builder
  1001. | Ast.Unary (op, operand) ->
  1002. let operand = codegen_expr operand in
  1003. let callee = "unary" ^ (String.make 1 op) in
  1004. let callee =
  1005. match lookup_function callee the_module with
  1006. | Some callee -> callee
  1007. | None -> raise (Error "unknown unary operator")
  1008. in
  1009. build_call callee [|operand|] "unop" builder
  1010. | Ast.Binary (op, lhs, rhs) ->
  1011. begin match op with
  1012. | '=' ->
  1013. (* Special case '=' because we don't want to emit the LHS as an
  1014. * expression. *)
  1015. let name =
  1016. match lhs with
  1017. | Ast.Variable name -> name
  1018. | _ -> raise (Error "destination of '=' must be a variable")
  1019. in
  1020. (* Codegen the rhs. *)
  1021. let val_ = codegen_expr rhs in
  1022. (* Lookup the name. *)
  1023. let variable = try Hashtbl.find named_values name with
  1024. | Not_found -> raise (Error "unknown variable name")
  1025. in
  1026. ignore(build_store val_ variable builder);
  1027. val_
  1028. | _ ->
  1029. let lhs_val = codegen_expr lhs in
  1030. let rhs_val = codegen_expr rhs in
  1031. begin
  1032. match op with
  1033. | '+' -> build_add lhs_val rhs_val "addtmp" builder
  1034. | '-' -> build_sub lhs_val rhs_val "subtmp" builder
  1035. | '*' -> build_mul lhs_val rhs_val "multmp" builder
  1036. | '<' ->
  1037. (* Convert bool 0/1 to double 0.0 or 1.0 *)
  1038. let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
  1039. build_uitofp i double_type "booltmp" builder
  1040. | _ ->
  1041. (* If it wasn't a builtin binary operator, it must be a user defined
  1042. * one. Emit a call to it. *)
  1043. let callee = "binary" ^ (String.make 1 op) in
  1044. let callee =
  1045. match lookup_function callee the_module with
  1046. | Some callee -> callee
  1047. | None -> raise (Error "binary operator not found!")
  1048. in
  1049. build_call callee [|lhs_val; rhs_val|] "binop" builder
  1050. end
  1051. end
  1052. | Ast.Call (callee, args) ->
  1053. (* Look up the name in the module table. *)
  1054. let callee =
  1055. match lookup_function callee the_module with
  1056. | Some callee -> callee
  1057. | None -> raise (Error "unknown function referenced")
  1058. in
  1059. let params = params callee in
  1060. (* If argument mismatch error. *)
  1061. if Array.length params == Array.length args then () else
  1062. raise (Error "incorrect # arguments passed");
  1063. let args = Array.map codegen_expr args in
  1064. build_call callee args "calltmp" builder
  1065. | Ast.If (cond, then_, else_) ->
  1066. let cond = codegen_expr cond in
  1067. (* Convert condition to a bool by comparing equal to 0.0 *)
  1068. let zero = const_float double_type 0.0 in
  1069. let cond_val = build_fcmp Fcmp.One cond zero "ifcond" builder in
  1070. (* Grab the first block so that we might later add the conditional branch
  1071. * to it at the end of the function. *)
  1072. let start_bb = insertion_block builder in
  1073. let the_function = block_parent start_bb in
  1074. let then_bb = append_block context "then" the_function in
  1075. (* Emit 'then' value. *)
  1076. position_at_end then_bb builder;
  1077. let then_val = codegen_expr then_ in
  1078. (* Codegen of 'then' can change the current block, update then_bb for the
  1079. * phi. We create a new name because one is used for the phi node, and the
  1080. * other is used for the conditional branch. *)
  1081. let new_then_bb = insertion_block builder in
  1082. (* Emit 'else' value. *)
  1083. let else_bb = append_block context "else" the_function in
  1084. position_at_end else_bb builder;
  1085. let else_val = codegen_expr else_ in
  1086. (* Codegen of 'else' can change the current block, update else_bb for the
  1087. * phi. *)
  1088. let new_else_bb = insertion_block builder in
  1089. (* Emit merge block. *)
  1090. let merge_bb = append_block context "ifcont" the_function in
  1091. position_at_end merge_bb builder;
  1092. let incoming = [(then_val, new_then_bb); (else_val, new_else_bb)] in
  1093. let phi = build_phi incoming "iftmp" builder in
  1094. (* Return to the start block to add the conditional branch. *)
  1095. position_at_end start_bb builder;
  1096. ignore (build_cond_br cond_val then_bb else_bb builder);
  1097. (* Set a unconditional branch at the end of the 'then' block and the
  1098. * 'else' block to the 'merge' block. *)
  1099. position_at_end new_then_bb builder; ignore (build_br merge_bb builder);
  1100. position_at_end new_else_bb builder; ignore (build_br merge_bb builder);
  1101. (* Finally, set the builder to the end of the merge block. *)
  1102. position_at_end merge_bb builder;
  1103. phi
  1104. | Ast.For (var_name, start, end_, step, body) ->
  1105. (* Output this as:
  1106. * var = alloca double
  1107. * ...
  1108. * start = startexpr
  1109. * store start -> var
  1110. * goto loop
  1111. * loop:
  1112. * ...
  1113. * bodyexpr
  1114. * ...
  1115. * loopend:
  1116. * step = stepexpr
  1117. * endcond = endexpr
  1118. *
  1119. * curvar = load var
  1120. * nextvar = curvar + step
  1121. * store nextvar -> var
  1122. * br endcond, loop, endloop
  1123. * outloop: *)
  1124. let the_function = block_parent (insertion_block builder) in
  1125. (* Create an alloca for the variable in the entry block. *)
  1126. let alloca = create_entry_block_alloca the_function var_name in
  1127. (* Emit the start code first, without 'variable' in scope. *)
  1128. let start_val = codegen_expr start in
  1129. (* Store the value into the alloca. *)
  1130. ignore(build_store start_val alloca builder);
  1131. (* Make the new basic block for the loop header, inserting after current
  1132. * block. *)
  1133. let loop_bb = append_block context "loop" the_function in
  1134. (* Insert an explicit fall through from the current block to the
  1135. * loop_bb. *)
  1136. ignore (build_br loop_bb builder);
  1137. (* Start insertion in loop_bb. *)
  1138. position_at_end loop_bb builder;
  1139. (* Within the loop, the variable is defined equal to the PHI node. If it
  1140. * shadows an existing variable, we have to restore it, so save it
  1141. * now. *)
  1142. let old_val =
  1143. try Some (Hashtbl.find named_values var_name) with Not_found -> None
  1144. in
  1145. Hashtbl.add named_values var_name alloca;
  1146. (* Emit the body of the loop. This, like any other expr, can change the
  1147. * current BB. Note that we ignore the value computed by the body, but
  1148. * don't allow an error *)
  1149. ignore (codegen_expr body);
  1150. (* Emit the step value. *)
  1151. let step_val =
  1152. match step with
  1153. | Some step -> codegen_expr step
  1154. (* If not specified, use 1.0. *)
  1155. | None -> const_float double_type 1.0
  1156. in
  1157. (* Compute the end condition. *)
  1158. let end_cond = codegen_expr end_ in
  1159. (* Reload, increment, and restore the alloca. This handles the case where
  1160. * the body of the loop mutates the variable. *)
  1161. let cur_var = build_load alloca var_name builder in
  1162. let next_var = build_add cur_var step_val "nextvar" builder in
  1163. ignore(build_store next_var alloca builder);
  1164. (* Convert condition to a bool by comparing equal to 0.0. *)
  1165. let zero = const_float double_type 0.0 in
  1166. let end_cond = build_fcmp Fcmp.One end_cond zero "loopcond" builder in
  1167. (* Create the "after loop" block and insert it. *)
  1168. let after_bb = append_block context "afterloop" the_function in
  1169. (* Insert the conditional branch into the end of loop_end_bb. *)
  1170. ignore (build_cond_br end_cond loop_bb after_bb builder);
  1171. (* Any new code will be inserted in after_bb. *)
  1172. position_at_end after_bb builder;
  1173. (* Restore the unshadowed variable. *)
  1174. begin match old_val with
  1175. | Some old_val -> Hashtbl.add named_values var_name old_val
  1176. | None -> ()
  1177. end;
  1178. (* for expr always returns 0.0. *)
  1179. const_null double_type
  1180. | Ast.Var (var_names, body) ->
  1181. let old_bindings = ref [] in
  1182. let the_function = block_parent (insertion_block builder) in
  1183. (* Register all variables and emit their initializer. *)
  1184. Array.iter (fun (var_name, init) ->
  1185. (* Emit the initializer before adding the variable to scope, this
  1186. * prevents the initializer from referencing the variable itself, and
  1187. * permits stuff like this:
  1188. * var a = 1 in
  1189. * var a = a in ... # refers to outer 'a'. *)
  1190. let init_val =
  1191. match init with
  1192. | Some init -> codegen_expr init
  1193. (* If not specified, use 0.0. *)
  1194. | None -> const_float double_type 0.0
  1195. in
  1196. let alloca = create_entry_block_alloca the_function var_name in
  1197. ignore(build_store init_val alloca builder);
  1198. (* Remember the old variable binding so that we can restore the binding
  1199. * when we unrecurse. *)
  1200. begin
  1201. try
  1202. let old_value = Hashtbl.find named_values var_name in
  1203. old_bindings := (var_name, old_value) :: !old_bindings;
  1204. with Not_found -> ()
  1205. end;
  1206. (* Remember this binding. *)
  1207. Hashtbl.add named_values var_name alloca;
  1208. ) var_names;
  1209. (* Codegen the body, now that all vars are in scope. *)
  1210. let body_val = codegen_expr body in
  1211. (* Pop all our variables from scope. *)
  1212. List.iter (fun (var_name, old_value) ->
  1213. Hashtbl.add named_values var_name old_value
  1214. ) !old_bindings;
  1215. (* Return the body computation. *)
  1216. body_val
  1217. let codegen_proto = function
  1218. | Ast.Prototype (name, args) | Ast.BinOpPrototype (name, args, _) ->
  1219. (* Make the function type: double(double,double) etc. *)
  1220. let doubles = Array.make (Array.length args) double_type in
  1221. let ft = function_type double_type doubles in
  1222. let f =
  1223. match lookup_function name the_module with
  1224. | None -> declare_function name ft the_module
  1225. (* If 'f' conflicted, there was already something named 'name'. If it
  1226. * has a body, don't allow redefinition or reextern. *)
  1227. | Some f ->
  1228. (* If 'f' already has a body, reject this. *)
  1229. if block_begin f <> At_end f then
  1230. raise (Error "redefinition of function");
  1231. (* If 'f' took a different number of arguments, reject. *)
  1232. if element_type (type_of f) <> ft then
  1233. raise (Error "redefinition of function with different # args");
  1234. f
  1235. in
  1236. (* Set names for all arguments. *)
  1237. Array.iteri (fun i a ->
  1238. let n = args.(i) in
  1239. set_value_name n a;
  1240. Hashtbl.add named_values n a;
  1241. ) (params f);
  1242. f
  1243. (* Create an alloca for each argument and register the argument in the symbol
  1244. * table so that references to it will succeed. *)
  1245. let create_argument_allocas the_function proto =
  1246. let args = match proto with
  1247. | Ast.Prototype (_, args) | Ast.BinOpPrototype (_, args, _) -> args
  1248. in
  1249. Array.iteri (fun i ai ->
  1250. let var_name = args.(i) in
  1251. (* Create an alloca for this variable. *)
  1252. let alloca = create_entry_block_alloca the_function var_name in
  1253. (* Store the initial value into the alloca. *)
  1254. ignore(build_store ai alloca builder);
  1255. (* Add arguments to variable symbol table. *)
  1256. Hashtbl.add named_values var_name alloca;
  1257. ) (params the_function)
  1258. let codegen_func the_fpm = function
  1259. | Ast.Function (proto, body) ->
  1260. Hashtbl.clear named_values;
  1261. let the_function = codegen_proto proto in
  1262. (* If this is an operator, install it. *)
  1263. begin match proto with
  1264. | Ast.BinOpPrototype (name, args, prec) ->
  1265. let op = name.[String.length name - 1] in
  1266. Hashtbl.add Parser.binop_precedence op prec;
  1267. | _ -> ()
  1268. end;
  1269. (* Create a new basic block to start insertion into. *)
  1270. let bb = append_block context "entry" the_function in
  1271. position_at_end bb builder;
  1272. try
  1273. (* Add all arguments to the symbol table and create their allocas. *)
  1274. create_argument_allocas the_function proto;
  1275. let ret_val = codegen_expr body in
  1276. (* Finish off the function. *)
  1277. let _ = build_ret ret_val builder in
  1278. (* Validate the generated code, checking for consistency. *)
  1279. Llvm_analysis.assert_valid_function the_function;
  1280. (* Optimize the function. *)
  1281. let _ = PassManager.run_function the_function the_fpm in
  1282. the_function
  1283. with e ->
  1284. delete_function the_function;
  1285. raise e
  1286. toplevel.ml:
  1287. .. code-block:: ocaml
  1288. (*===----------------------------------------------------------------------===
  1289. * Top-Level parsing and JIT Driver
  1290. *===----------------------------------------------------------------------===*)
  1291. open Llvm
  1292. open Llvm_executionengine
  1293. (* top ::= definition | external | expression | ';' *)
  1294. let rec main_loop the_fpm the_execution_engine stream =
  1295. match Stream.peek stream with
  1296. | None -> ()
  1297. (* ignore top-level semicolons. *)
  1298. | Some (Token.Kwd ';') ->
  1299. Stream.junk stream;
  1300. main_loop the_fpm the_execution_engine stream
  1301. | Some token ->
  1302. begin
  1303. try match token with
  1304. | Token.Def ->
  1305. let e = Parser.parse_definition stream in
  1306. print_endline "parsed a function definition.";
  1307. dump_value (Codegen.codegen_func the_fpm e);
  1308. | Token.Extern ->
  1309. let e = Parser.parse_extern stream in
  1310. print_endline "parsed an extern.";
  1311. dump_value (Codegen.codegen_proto e);
  1312. | _ ->
  1313. (* Evaluate a top-level expression into an anonymous function. *)
  1314. let e = Parser.parse_toplevel stream in
  1315. print_endline "parsed a top-level expr";
  1316. let the_function = Codegen.codegen_func the_fpm e in
  1317. dump_value the_function;
  1318. (* JIT the function, returning a function pointer. *)
  1319. let result = ExecutionEngine.run_function the_function [||]
  1320. the_execution_engine in
  1321. print_string "Evaluated to ";
  1322. print_float (GenericValue.as_float Codegen.double_type result);
  1323. print_newline ();
  1324. with Stream.Error s | Codegen.Error s ->
  1325. (* Skip token for error recovery. *)
  1326. Stream.junk stream;
  1327. print_endline s;
  1328. end;
  1329. print_string "ready> "; flush stdout;
  1330. main_loop the_fpm the_execution_engine stream
  1331. toy.ml:
  1332. .. code-block:: ocaml
  1333. (*===----------------------------------------------------------------------===
  1334. * Main driver code.
  1335. *===----------------------------------------------------------------------===*)
  1336. open Llvm
  1337. open Llvm_executionengine
  1338. open Llvm_target
  1339. open Llvm_scalar_opts
  1340. let main () =
  1341. ignore (initialize_native_target ());
  1342. (* Install standard binary operators.
  1343. * 1 is the lowest precedence. *)
  1344. Hashtbl.add Parser.binop_precedence '=' 2;
  1345. Hashtbl.add Parser.binop_precedence '<' 10;
  1346. Hashtbl.add Parser.binop_precedence '+' 20;
  1347. Hashtbl.add Parser.binop_precedence '-' 20;
  1348. Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
  1349. (* Prime the first token. *)
  1350. print_string "ready> "; flush stdout;
  1351. let stream = Lexer.lex (Stream.of_channel stdin) in
  1352. (* Create the JIT. *)
  1353. let the_execution_engine = ExecutionEngine.create Codegen.the_module in
  1354. let the_fpm = PassManager.create_function Codegen.the_module in
  1355. (* Set up the optimizer pipeline. Start with registering info about how the
  1356. * target lays out data structures. *)
  1357. DataLayout.add (ExecutionEngine.target_data the_execution_engine) the_fpm;
  1358. (* Promote allocas to registers. *)
  1359. add_memory_to_register_promotion the_fpm;
  1360. (* Do simple "peephole" optimizations and bit-twiddling optzn. *)
  1361. add_instruction_combination the_fpm;
  1362. (* reassociate expressions. *)
  1363. add_reassociation the_fpm;
  1364. (* Eliminate Common SubExpressions. *)
  1365. add_gvn the_fpm;
  1366. (* Simplify the control flow graph (deleting unreachable blocks, etc). *)
  1367. add_cfg_simplification the_fpm;
  1368. ignore (PassManager.initialize the_fpm);
  1369. (* Run the main "interpreter loop" now. *)
  1370. Toplevel.main_loop the_fpm the_execution_engine stream;
  1371. (* Print out all the generated code. *)
  1372. dump_module Codegen.the_module
  1373. ;;
  1374. main ()
  1375. bindings.c
  1376. .. code-block:: c
  1377. #include <stdio.h>
  1378. /* putchard - putchar that takes a double and returns 0. */
  1379. extern double putchard(double X) {
  1380. putchar((char)X);
  1381. return 0;
  1382. }
  1383. /* printd - printf that takes a double prints it as "%f\n", returning 0. */
  1384. extern double printd(double X) {
  1385. printf("%f\n", X);
  1386. return 0;
  1387. }
  1388. `Next: Conclusion and other useful LLVM tidbits <OCamlLangImpl8.html>`_