compiler.texi 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389
  1. @c -*-texinfo-*-
  2. @c This is part of the GNU Guile Reference Manual.
  3. @c Copyright (C) 2008-2016, 2018
  4. @c Free Software Foundation, Inc.
  5. @c See the file guile.texi for copying conditions.
  6. @node Compiling to the Virtual Machine
  7. @section Compiling to the Virtual Machine
  8. Compilers! The word itself inspires excitement and awe, even among
  9. experienced practitioners. But a compiler is just a program: an
  10. eminently hackable thing. This section aims to describe Guile's
  11. compiler in such a way that interested Scheme hackers can feel
  12. comfortable reading and extending it.
  13. @xref{Read/Load/Eval/Compile}, if you're lost and you just wanted to
  14. know how to compile your @code{.scm} file.
  15. @menu
  16. * Compiler Tower::
  17. * The Scheme Compiler::
  18. * Tree-IL::
  19. * Continuation-Passing Style::
  20. * Bytecode::
  21. * Writing New High-Level Languages::
  22. * Extending the Compiler::
  23. @end menu
  24. @node Compiler Tower
  25. @subsection Compiler Tower
  26. Guile's compiler is quite simple -- its @emph{compilers}, to put it more
  27. accurately. Guile defines a tower of languages, starting at Scheme and
  28. progressively simplifying down to languages that resemble the VM
  29. instruction set (@pxref{Instruction Set}).
  30. Each language knows how to compile to the next, so each step is simple
  31. and understandable. Furthermore, this set of languages is not hardcoded
  32. into Guile, so it is possible for the user to add new high-level
  33. languages, new passes, or even different compilation targets.
  34. Languages are registered in the module, @code{(system base language)}:
  35. @example
  36. (use-modules (system base language))
  37. @end example
  38. They are registered with the @code{define-language} form.
  39. @deffn {Scheme Syntax} define-language @
  40. [#:name] [#:title] [#:reader] [#:printer] @
  41. [#:parser=#f] [#:compilers='()] @
  42. [#:decompilers='()] [#:evaluator=#f] @
  43. [#:joiner=#f] [#:for-humans?=#t] @
  44. [#:make-default-environment=make-fresh-user-module]
  45. Define a language.
  46. This syntax defines a @code{<language>} object, bound to @var{name} in
  47. the current environment. In addition, the language will be added to the
  48. global language set. For example, this is the language definition for
  49. Scheme:
  50. @example
  51. (define-language scheme
  52. #:title "Scheme"
  53. #:reader (lambda (port env) ...)
  54. #:compilers `((tree-il . ,compile-tree-il))
  55. #:decompilers `((tree-il . ,decompile-tree-il))
  56. #:evaluator (lambda (x module) (primitive-eval x))
  57. #:printer write
  58. #:make-default-environment (lambda () ...))
  59. @end example
  60. @end deffn
  61. The interesting thing about having languages defined this way is that
  62. they present a uniform interface to the read-eval-print loop. This
  63. allows the user to change the current language of the REPL:
  64. @example
  65. scheme@@(guile-user)> ,language tree-il
  66. Happy hacking with Tree Intermediate Language! To switch back, type `,L scheme'.
  67. tree-il@@(guile-user)> ,L scheme
  68. Happy hacking with Scheme! To switch back, type `,L tree-il'.
  69. scheme@@(guile-user)>
  70. @end example
  71. Languages can be looked up by name, as they were above.
  72. @deffn {Scheme Procedure} lookup-language name
  73. Looks up a language named @var{name}, autoloading it if necessary.
  74. Languages are autoloaded by looking for a variable named @var{name} in
  75. a module named @code{(language @var{name} spec)}.
  76. The language object will be returned, or @code{#f} if there does not
  77. exist a language with that name.
  78. @end deffn
  79. Defining languages this way allows us to programmatically determine
  80. the necessary steps for compiling code from one language to another.
  81. @deffn {Scheme Procedure} lookup-compilation-order from to
  82. Recursively traverses the set of languages to which @var{from} can
  83. compile, depth-first, and return the first path that can transform
  84. @var{from} to @var{to}. Returns @code{#f} if no path is found.
  85. This function memoizes its results in a cache that is invalidated by
  86. subsequent calls to @code{define-language}, so it should be quite
  87. fast.
  88. @end deffn
  89. There is a notion of a ``current language'', which is maintained in the
  90. @code{current-language} parameter, defined in the core @code{(guile)}
  91. module. This language is normally Scheme, and may be rebound by the
  92. user. The run-time compilation interfaces
  93. (@pxref{Read/Load/Eval/Compile}) also allow you to choose other source
  94. and target languages.
  95. The normal tower of languages when compiling Scheme goes like this:
  96. @itemize
  97. @item Scheme
  98. @item Tree Intermediate Language (Tree-IL)
  99. @item Continuation-Passing Style (CPS)
  100. @item Bytecode
  101. @end itemize
  102. As discussed before (@pxref{Object File Format}), bytecode is in ELF
  103. format, ready to be serialized to disk. But when compiling Scheme at
  104. run time, you want a Scheme value: for example, a compiled procedure.
  105. For this reason, so as not to break the abstraction, Guile defines a
  106. fake language at the bottom of the tower:
  107. @itemize
  108. @item Value
  109. @end itemize
  110. Compiling to @code{value} loads the bytecode into a procedure, turning
  111. cold bytes into warm code.
  112. Perhaps this strangeness can be explained by example:
  113. @code{compile-file} defaults to compiling to bytecode, because it
  114. produces object code that has to live in the barren world outside the
  115. Guile runtime; but @code{compile} defaults to compiling to @code{value},
  116. as its product re-enters the Guile world.
  117. @c FIXME: This doesn't work anymore :( Should we add some kind of
  118. @c special GC pass, or disclaim this kind of code, or what?
  119. Indeed, the process of compilation can circulate through these
  120. different worlds indefinitely, as shown by the following quine:
  121. @example
  122. ((lambda (x) ((compile x) x)) '(lambda (x) ((compile x) x)))
  123. @end example
  124. @node The Scheme Compiler
  125. @subsection The Scheme Compiler
  126. The job of the Scheme compiler is to expand all macros and all of Scheme
  127. to its most primitive expressions. The definition of ``primitive
  128. expression'' is given by the inventory of constructs provided by
  129. Tree-IL, the target language of the Scheme compiler: procedure calls,
  130. conditionals, lexical references, and so on. This is described more
  131. fully in the next section.
  132. The tricky and amusing thing about the Scheme-to-Tree-IL compiler is
  133. that it is completely implemented by the macro expander. Since the
  134. macro expander has to run over all of the source code already in order
  135. to expand macros, it might as well do the analysis at the same time,
  136. producing Tree-IL expressions directly.
  137. Because this compiler is actually the macro expander, it is extensible.
  138. Any macro which the user writes becomes part of the compiler.
  139. The Scheme-to-Tree-IL expander may be invoked using the generic
  140. @code{compile} procedure:
  141. @lisp
  142. (compile '(+ 1 2) #:from 'scheme #:to 'tree-il)
  143. @result{}
  144. #<tree-il (call (toplevel +) (const 1) (const 2))>
  145. @end lisp
  146. @code{(compile @var{foo} #:from 'scheme #:to 'tree-il)} is entirely
  147. equivalent to calling the macro expander as @code{(macroexpand @var{foo}
  148. 'c '(compile load eval))}. @xref{Macro Expansion}.
  149. @code{compile-tree-il}, the procedure dispatched by @code{compile} to
  150. @code{'tree-il}, is a small wrapper around @code{macroexpand}, to make
  151. it conform to the general form of compiler procedures in Guile's
  152. language tower.
  153. Compiler procedures take three arguments: an expression, an
  154. environment, and a keyword list of options. They return three values:
  155. the compiled expression, the corresponding environment for the target
  156. language, and a ``continuation environment''. The compiled expression
  157. and environment will serve as input to the next language's compiler.
  158. The ``continuation environment'' can be used to compile another
  159. expression from the same source language within the same module.
  160. For example, you might compile the expression, @code{(define-module
  161. (foo))}. This will result in a Tree-IL expression and environment. But
  162. if you compiled a second expression, you would want to take into account
  163. the compile-time effect of compiling the previous expression, which puts
  164. the user in the @code{(foo)} module. That is the purpose of the
  165. ``continuation environment''; you would pass it as the environment when
  166. compiling the subsequent expression.
  167. For Scheme, an environment is a module. By default, the @code{compile}
  168. and @code{compile-file} procedures compile in a fresh module, such
  169. that bindings and macros introduced by the expression being compiled
  170. are isolated:
  171. @example
  172. (eq? (current-module) (compile '(current-module)))
  173. @result{} #f
  174. (compile '(define hello 'world))
  175. (defined? 'hello)
  176. @result{} #f
  177. (define / *)
  178. (eq? (compile '/) /)
  179. @result{} #f
  180. @end example
  181. Similarly, changes to the @code{current-reader} fluid (@pxref{Loading,
  182. @code{current-reader}}) are isolated:
  183. @example
  184. (compile '(fluid-set! current-reader (lambda args 'fail)))
  185. (fluid-ref current-reader)
  186. @result{} #f
  187. @end example
  188. Nevertheless, having the compiler and @dfn{compilee} share the same name
  189. space can be achieved by explicitly passing @code{(current-module)} as
  190. the compilation environment:
  191. @example
  192. (define hello 'world)
  193. (compile 'hello #:env (current-module))
  194. @result{} world
  195. @end example
  196. @node Tree-IL
  197. @subsection Tree-IL
  198. Tree Intermediate Language (Tree-IL) is a structured intermediate
  199. language that is close in expressive power to Scheme. It is an
  200. expanded, pre-analyzed Scheme.
  201. Tree-IL is ``structured'' in the sense that its representation is
  202. based on records, not S-expressions. This gives a rigidity to the
  203. language that ensures that compiling to a lower-level language only
  204. requires a limited set of transformations. For example, the Tree-IL
  205. type @code{<const>} is a record type with two fields, @code{src} and
  206. @code{exp}. Instances of this type are created via @code{make-const}.
  207. Fields of this type are accessed via the @code{const-src} and
  208. @code{const-exp} procedures. There is also a predicate, @code{const?}.
  209. @xref{Records}, for more information on records.
  210. @c alpha renaming
  211. All Tree-IL types have a @code{src} slot, which holds source location
  212. information for the expression. This information, if present, will be
  213. residualized into the compiled object code, allowing backtraces to
  214. show source information. The format of @code{src} is the same as that
  215. returned by Guile's @code{source-properties} function. @xref{Source
  216. Properties}, for more information.
  217. Although Tree-IL objects are represented internally using records,
  218. there is also an equivalent S-expression external representation for
  219. each kind of Tree-IL. For example, the S-expression representation
  220. of @code{#<const src: #f exp: 3>} expression would be:
  221. @example
  222. (const 3)
  223. @end example
  224. Users may program with this format directly at the REPL:
  225. @example
  226. scheme@@(guile-user)> ,language tree-il
  227. Happy hacking with Tree Intermediate Language! To switch back, type `,L scheme'.
  228. tree-il@@(guile-user)> (call (primitive +) (const 32) (const 10))
  229. @result{} 42
  230. @end example
  231. The @code{src} fields are left out of the external representation.
  232. One may create Tree-IL objects from their external representations via
  233. calling @code{parse-tree-il}, the reader for Tree-IL. If any source
  234. information is attached to the input S-expression, it will be
  235. propagated to the resulting Tree-IL expressions. This is probably the
  236. easiest way to compile to Tree-IL: just make the appropriate external
  237. representations in S-expression format, and let @code{parse-tree-il}
  238. take care of the rest.
  239. @deftp {Scheme Variable} <void> src
  240. @deftpx {External Representation} (void)
  241. An empty expression. In practice, equivalent to Scheme's @code{(if #f
  242. #f)}.
  243. @end deftp
  244. @deftp {Scheme Variable} <const> src exp
  245. @deftpx {External Representation} (const @var{exp})
  246. A constant.
  247. @end deftp
  248. @deftp {Scheme Variable} <primitive-ref> src name
  249. @deftpx {External Representation} (primitive @var{name})
  250. A reference to a ``primitive''. A primitive is a procedure that, when
  251. compiled, may be open-coded. For example, @code{cons} is usually
  252. recognized as a primitive, so that it compiles down to a single
  253. instruction.
  254. Compilation of Tree-IL usually begins with a pass that resolves some
  255. @code{<module-ref>} and @code{<toplevel-ref>} expressions to
  256. @code{<primitive-ref>} expressions. The actual compilation pass has
  257. special cases for calls to certain primitives, like @code{apply} or
  258. @code{cons}.
  259. @end deftp
  260. @deftp {Scheme Variable} <lexical-ref> src name gensym
  261. @deftpx {External Representation} (lexical @var{name} @var{gensym})
  262. A reference to a lexically-bound variable. The @var{name} is the
  263. original name of the variable in the source program. @var{gensym} is a
  264. unique identifier for this variable.
  265. @end deftp
  266. @deftp {Scheme Variable} <lexical-set> src name gensym exp
  267. @deftpx {External Representation} (set! (lexical @var{name} @var{gensym}) @var{exp})
  268. Sets a lexically-bound variable.
  269. @end deftp
  270. @deftp {Scheme Variable} <module-ref> src mod name public?
  271. @deftpx {External Representation} (@@ @var{mod} @var{name})
  272. @deftpx {External Representation} (@@@@ @var{mod} @var{name})
  273. A reference to a variable in a specific module. @var{mod} should be
  274. the name of the module, e.g.@: @code{(guile-user)}.
  275. If @var{public?} is true, the variable named @var{name} will be looked
  276. up in @var{mod}'s public interface, and serialized with @code{@@};
  277. otherwise it will be looked up among the module's private bindings,
  278. and is serialized with @code{@@@@}.
  279. @end deftp
  280. @deftp {Scheme Variable} <module-set> src mod name public? exp
  281. @deftpx {External Representation} (set! (@@ @var{mod} @var{name}) @var{exp})
  282. @deftpx {External Representation} (set! (@@@@ @var{mod} @var{name}) @var{exp})
  283. Sets a variable in a specific module.
  284. @end deftp
  285. @deftp {Scheme Variable} <toplevel-ref> src name
  286. @deftpx {External Representation} (toplevel @var{name})
  287. References a variable from the current procedure's module.
  288. @end deftp
  289. @deftp {Scheme Variable} <toplevel-set> src name exp
  290. @deftpx {External Representation} (set! (toplevel @var{name}) @var{exp})
  291. Sets a variable in the current procedure's module.
  292. @end deftp
  293. @deftp {Scheme Variable} <toplevel-define> src name exp
  294. @deftpx {External Representation} (define @var{name} @var{exp})
  295. Defines a new top-level variable in the current procedure's module.
  296. @end deftp
  297. @deftp {Scheme Variable} <conditional> src test then else
  298. @deftpx {External Representation} (if @var{test} @var{then} @var{else})
  299. A conditional. Note that @var{else} is not optional.
  300. @end deftp
  301. @deftp {Scheme Variable} <call> src proc args
  302. @deftpx {External Representation} (call @var{proc} . @var{args})
  303. A procedure call.
  304. @end deftp
  305. @deftp {Scheme Variable} <primcall> src name args
  306. @deftpx {External Representation} (primcall @var{name} . @var{args})
  307. A call to a primitive. Equivalent to @code{(call (primitive @var{name})
  308. . @var{args})}. This construct is often more convenient to generate and
  309. analyze than @code{<call>}.
  310. As part of the compilation process, instances of @code{(call (primitive
  311. @var{name}) . @var{args})} are transformed into primcalls.
  312. @end deftp
  313. @deftp {Scheme Variable} <seq> src head tail
  314. @deftpx {External Representation} (seq @var{head} @var{tail})
  315. A sequence. The semantics is that @var{head} is evaluated first, and
  316. any resulting values are ignored. Then @var{tail} is evaluated, in tail
  317. position.
  318. @end deftp
  319. @deftp {Scheme Variable} <lambda> src meta body
  320. @deftpx {External Representation} (lambda @var{meta} @var{body})
  321. A closure. @var{meta} is an association list of properties for the
  322. procedure. @var{body} is a single Tree-IL expression of type
  323. @code{<lambda-case>}. As the @code{<lambda-case>} clause can chain to
  324. an alternate clause, this makes Tree-IL's @code{<lambda>} have the
  325. expressiveness of Scheme's @code{case-lambda}.
  326. @end deftp
  327. @deftp {Scheme Variable} <lambda-case> req opt rest kw inits gensyms body alternate
  328. @deftpx {External Representation} @
  329. (lambda-case ((@var{req} @var{opt} @var{rest} @var{kw} @var{inits} @var{gensyms})@
  330. @var{body})@
  331. [@var{alternate}])
  332. One clause of a @code{case-lambda}. A @code{lambda} expression in
  333. Scheme is treated as a @code{case-lambda} with one clause.
  334. @var{req} is a list of the procedure's required arguments, as symbols.
  335. @var{opt} is a list of the optional arguments, or @code{#f} if there
  336. are no optional arguments. @var{rest} is the name of the rest
  337. argument, or @code{#f}.
  338. @var{kw} is a list of the form, @code{(@var{allow-other-keys?}
  339. (@var{keyword} @var{name} @var{var}) ...)}, where @var{keyword} is the
  340. keyword corresponding to the argument named @var{name}, and whose
  341. corresponding gensym is @var{var}. @var{inits} are tree-il expressions
  342. corresponding to all of the optional and keyword arguments, evaluated to
  343. bind variables whose value is not supplied by the procedure caller.
  344. Each @var{init} expression is evaluated in the lexical context of
  345. previously bound variables, from left to right.
  346. @var{gensyms} is a list of gensyms corresponding to all arguments:
  347. first all of the required arguments, then the optional arguments if
  348. any, then the rest argument if any, then all of the keyword arguments.
  349. @var{body} is the body of the clause. If the procedure is called with
  350. an appropriate number of arguments, @var{body} is evaluated in tail
  351. position. Otherwise, if there is an @var{alternate}, it should be a
  352. @code{<lambda-case>} expression, representing the next clause to try.
  353. If there is no @var{alternate}, a wrong-number-of-arguments error is
  354. signaled.
  355. @end deftp
  356. @deftp {Scheme Variable} <let> src names gensyms vals exp
  357. @deftpx {External Representation} (let @var{names} @var{gensyms} @var{vals} @var{exp})
  358. Lexical binding, like Scheme's @code{let}. @var{names} are the original
  359. binding names, @var{gensyms} are gensyms corresponding to the
  360. @var{names}, and @var{vals} are Tree-IL expressions for the values.
  361. @var{exp} is a single Tree-IL expression.
  362. @end deftp
  363. @deftp {Scheme Variable} <letrec> in-order? src names gensyms vals exp
  364. @deftpx {External Representation} (letrec @var{names} @var{gensyms} @var{vals} @var{exp})
  365. @deftpx {External Representation} (letrec* @var{names} @var{gensyms} @var{vals} @var{exp})
  366. A version of @code{<let>} that creates recursive bindings, like
  367. Scheme's @code{letrec}, or @code{letrec*} if @var{in-order?} is true.
  368. @end deftp
  369. @deftp {Scheme Variable} <prompt> escape-only? tag body handler
  370. @deftpx {External Representation} (prompt @var{escape-only?} @var{tag} @var{body} @var{handler})
  371. A dynamic prompt. Instates a prompt named @var{tag}, an expression,
  372. during the dynamic extent of the execution of @var{body}, also an
  373. expression. If an abort occurs to this prompt, control will be passed
  374. to @var{handler}, also an expression, which should be a procedure. The
  375. first argument to the handler procedure will be the captured
  376. continuation, followed by all of the values passed to the abort. If
  377. @var{escape-only?} is true, the handler should be a @code{<lambda>} with
  378. a single @code{<lambda-case>} body expression with no optional or
  379. keyword arguments, and no alternate, and whose first argument is
  380. unreferenced. @xref{Prompts}, for more information.
  381. @end deftp
  382. @deftp {Scheme Variable} <abort> tag args tail
  383. @deftpx {External Representation} (abort @var{tag} @var{args} @var{tail})
  384. An abort to the nearest prompt with the name @var{tag}, an expression.
  385. @var{args} should be a list of expressions to pass to the prompt's
  386. handler, and @var{tail} should be an expression that will evaluate to
  387. a list of additional arguments. An abort will save the partial
  388. continuation, which may later be reinstated, resulting in the
  389. @code{<abort>} expression evaluating to some number of values.
  390. @end deftp
  391. There are two Tree-IL constructs that are not normally produced by
  392. higher-level compilers, but instead are generated during the
  393. source-to-source optimization and analysis passes that the Tree-IL
  394. compiler does. Users should not generate these expressions directly,
  395. unless they feel very clever, as the default analysis pass will generate
  396. them as necessary.
  397. @deftp {Scheme Variable} <let-values> src names gensyms exp body
  398. @deftpx {External Representation} (let-values @var{names} @var{gensyms} @var{exp} @var{body})
  399. Like Scheme's @code{receive} -- binds the values returned by
  400. evaluating @code{exp} to the @code{lambda}-like bindings described by
  401. @var{gensyms}. That is to say, @var{gensyms} may be an improper list.
  402. @code{<let-values>} is an optimization of a @code{<call>} to the
  403. primitive, @code{call-with-values}.
  404. @end deftp
  405. @deftp {Scheme Variable} <fix> src names gensyms vals body
  406. @deftpx {External Representation} (fix @var{names} @var{gensyms} @var{vals} @var{body})
  407. Like @code{<letrec>}, but only for @var{vals} that are unset
  408. @code{lambda} expressions.
  409. @code{fix} is an optimization of @code{letrec} (and @code{let}).
  410. @end deftp
  411. Tree-IL is a convenient compilation target from source languages. It
  412. can be convenient as a medium for optimization, though CPS is usually
  413. better. The strength of Tree-IL is that it does not fix order of
  414. evaluation, so it makes some code motion a bit easier.
  415. Optimization passes performed on Tree-IL currently include:
  416. @itemize
  417. @item Open-coding (turning toplevel-refs into primitive-refs,
  418. and calls to primitives to primcalls)
  419. @item Partial evaluation (comprising inlining, copy propagation, and
  420. constant folding)
  421. @end itemize
  422. @node Continuation-Passing Style
  423. @subsection Continuation-Passing Style
  424. @cindex CPS
  425. Continuation-passing style (CPS) is Guile's principal intermediate
  426. language, bridging the gap between languages for people and languages
  427. for machines. CPS gives a name to every part of a program: every
  428. control point, and every intermediate value. This makes it an excellent
  429. medium for reasoning about programs, which is the principal job of a
  430. compiler.
  431. @menu
  432. * An Introduction to CPS::
  433. * CPS in Guile::
  434. * Building CPS::
  435. * CPS Soup::
  436. * Compiling CPS::
  437. @end menu
  438. @node An Introduction to CPS
  439. @subsubsection An Introduction to CPS
  440. Consider the following Scheme expression:
  441. @lisp
  442. (begin
  443. (display "The sum of 32 and 10 is: ")
  444. (display 42)
  445. (newline))
  446. @end lisp
  447. Let us identify all of the sub-expressions in this expression,
  448. annotating them with unique labels:
  449. @lisp
  450. (begin
  451. (display "The sum of 32 and 10 is: ")
  452. |k1 k2
  453. k0
  454. (display 42)
  455. |k4 k5
  456. k3
  457. (newline))
  458. |k7
  459. k6
  460. @end lisp
  461. Each of these labels identifies a point in a program. One label may be
  462. the continuation of another label. For example, the continuation of
  463. @code{k7} is @code{k6}. This is because after evaluating the value of
  464. @code{newline}, performed by the expression labelled @code{k7}, we
  465. continue to apply it in @code{k6}.
  466. Which expression has @code{k0} as its continuation? It is either the
  467. expression labelled @code{k1} or the expression labelled @code{k2}.
  468. Scheme does not have a fixed order of evaluation of arguments, though it
  469. does guarantee that they are evaluated in some order. Unlike general
  470. Scheme, continuation-passing style makes evaluation order explicit. In
  471. Guile, this choice is made by the higher-level language compilers.
  472. Let us assume a left-to-right evaluation order. In that case the
  473. continuation of @code{k1} is @code{k2}, and the continuation of
  474. @code{k2} is @code{k0}.
  475. With this example established, we are ready to give an example of CPS in
  476. Scheme:
  477. @smalllisp
  478. (lambda (ktail)
  479. (let ((k1 (lambda ()
  480. (let ((k2 (lambda (proc)
  481. (let ((k0 (lambda (arg0)
  482. (proc k4 arg0))))
  483. (k0 "The sum of 32 and 10 is: ")))))
  484. (k2 display))))
  485. (k4 (lambda _
  486. (let ((k5 (lambda (proc)
  487. (let ((k3 (lambda (arg0)
  488. (proc k7 arg0))))
  489. (k3 42)))))
  490. (k5 display))))
  491. (k7 (lambda _
  492. (let ((k6 (lambda (proc)
  493. (proc ktail))))
  494. (k6 newline)))))
  495. (k1))
  496. @end smalllisp
  497. Holy code explosion, Batman! What's with all the lambdas? Indeed, CPS
  498. is by nature much more verbose than ``direct-style'' intermediate
  499. languages like Tree-IL. At the same time, CPS is simpler than full
  500. Scheme, because it makes things more explicit.
  501. In the original program, the expression labelled @code{k0} is in effect
  502. context. Any values it returns are ignored. In Scheme, this fact is
  503. implicit. In CPS, we can see it explicitly by noting that its
  504. continuation, @code{k4}, takes any number of values and ignores them.
  505. Compare this to @code{k2}, which takes a single value; in this way we
  506. can say that @code{k1} is in a ``value'' context. Likewise @code{k6} is
  507. in tail context with respect to the expression as a whole, because its
  508. continuation is the tail continuation, @code{ktail}. CPS makes these
  509. details manifest, and gives them names.
  510. @node CPS in Guile
  511. @subsubsection CPS in Guile
  512. @cindex continuation, CPS
  513. Guile's CPS language is composed of @dfn{continuations}. A continuation
  514. is a labelled program point. If you are used to traditional compilers,
  515. think of a continuation as a trivial basic block. A program is a
  516. ``soup'' of continuations, represented as a map from labels to
  517. continuations.
  518. @cindex term, CPS
  519. @cindex expression, CPS
  520. Like basic blocks, each continuation belongs to only one function. Some
  521. continuations are special, like the continuation corresponding to a
  522. function's entry point, or the continuation that represents the tail of
  523. a function. Others contain a @dfn{term}. A term contains an
  524. @dfn{expression}, which evaluates to zero or more values. The term also
  525. records the continuation to which it will pass its values. Some terms,
  526. like conditional branches, may continue to one of a number of
  527. continuations.
  528. Continuation labels are small integers. This makes it easy to sort them
  529. and to group them into sets. Whenever a term refers to a continuation,
  530. it does so by name, simply recording the label of the continuation.
  531. Continuation labels are unique among the set of labels in a program.
  532. Variables are also named by small integers. Variable names are unique
  533. among the set of variables in a program.
  534. For example, a simple continuation that receives two values and adds
  535. them together can be matched like this, using the @code{match} form from
  536. @code{(ice-9 match)}:
  537. @smallexample
  538. (match cont
  539. (($ $kargs (x-name y-name) (x-var y-var)
  540. ($ $continue k src ($ $primcall '+ #f (x-var y-var))))
  541. (format #t "Add ~a and ~a and pass the result to label ~a"
  542. x-var y-var k)))
  543. @end smallexample
  544. Here we see the most common kind of continuation, @code{$kargs}, which
  545. binds some number of values to variables and then evaluates a term.
  546. @deftp {CPS Continuation} $kargs names vars term
  547. Bind the incoming values to the variables @var{vars}, with original
  548. names @var{names}, and then evaluate @var{term}.
  549. @end deftp
  550. The @var{names} of a @code{$kargs} are just for debugging, and will end
  551. up residualized in the object file for use by the debugger.
  552. The @var{term} in a @code{$kargs} is always a @code{$continue}, which
  553. evaluates an expression and continues to a continuation.
  554. @deftp {CPS Term} $continue k src exp
  555. Evaluate the expression @var{exp} and pass the resulting values (if any)
  556. to the continuation labelled @var{k}. The source information associated
  557. with the expression may be found in @var{src}, which is either an alist
  558. as in @code{source-properties} or is @code{#f} if there is no associated
  559. source.
  560. @end deftp
  561. There are a number of expression kinds. Above you see an example of
  562. @code{$primcall}.
  563. @deftp {CPS Expression} $primcall name param args
  564. Perform the primitive operation identified by @code{name}, a well-known
  565. symbol, passing it the arguments @var{args}, and pass all resulting
  566. values to the continuation.
  567. @var{param} is a constant parameter whose interpretation is up to the
  568. primcall in question. Usually it's @code{#f} but for a primcall that
  569. might need some compile-time constant information -- such as
  570. @code{add/immediate}, which adds a constant number to a value -- the
  571. parameter holds this information.
  572. The set of available primitives includes many primitives known to
  573. Tree-IL and then some more; see the source code for details. Note that
  574. some Tree-IL primcalls need to be converted to a sequence of lower-level
  575. CPS primcalls. Again, see @code{(language tree-il compile-cps)} for
  576. full details.
  577. @end deftp
  578. @cindex dominate, CPS
  579. The variables that are used by @code{$primcall}, or indeed by any
  580. expression, must be defined before the expression is evaluated. An
  581. equivalent way of saying this is that predecessor @code{$kargs}
  582. continuation(s) that bind the variables(s) used by the expression must
  583. @dfn{dominate} the continuation that uses the expression: definitions
  584. dominate uses. This condition is trivially satisfied in our example
  585. above, but in general to determine the set of variables that are in
  586. ``scope'' for a given term, you need to do a flow analysis to see what
  587. continuations dominate a term. The variables that are in scope are
  588. those variables defined by the continuations that dominate a term.
  589. Here is an inventory of the kinds of expressions in Guile's CPS
  590. language, besides @code{$primcall} which has already been described.
  591. Recall that all expressions are wrapped in a @code{$continue} term which
  592. specifies their continuation.
  593. @deftp {CPS Expression} $const val
  594. Continue with the constant value @var{val}.
  595. @end deftp
  596. @deftp {CPS Expression} $prim name
  597. Continue with the procedure that implements the primitive operation
  598. named by @var{name}.
  599. @end deftp
  600. @deftp {CPS Expression} $call proc args
  601. Call @var{proc} with the arguments @var{args}, and pass all values to
  602. the continuation. @var{proc} and the elements of the @var{args} list
  603. should all be variable names. The continuation identified by the term's
  604. @var{k} should be a @code{$kreceive} or a @code{$ktail} instance.
  605. @end deftp
  606. @deftp {CPS Expression} $values args
  607. Pass the values named by the list @var{args} to the continuation.
  608. @end deftp
  609. @deftp {CPS Expression} $prompt escape? tag handler
  610. @end deftp
  611. @cindex higher-order CPS
  612. @cindex CPS, higher-order
  613. @cindex first-order CPS
  614. @cindex CPS, first-order
  615. There are two sub-languages of CPS, @dfn{higher-order CPS} and
  616. @dfn{first-order CPS}. The difference is that in higher-order CPS,
  617. there are @code{$fun} and @code{$rec} expressions that bind functions or
  618. mutually-recursive functions in the implicit scope of their use sites.
  619. Guile transforms higher-order CPS into first-order CPS by @dfn{closure
  620. conversion}, which chooses representations for all closures and which
  621. arranges to access free variables through the implicit closure parameter
  622. that is passed to every function call.
  623. @deftp {CPS Expression} $fun body
  624. Continue with a procedure. @var{body} names the entry point of the
  625. function, which should be a @code{$kfun}. This expression kind is only
  626. valid in higher-order CPS, which is the CPS language before closure
  627. conversion.
  628. @end deftp
  629. @deftp {CPS Expression} $rec names vars funs
  630. Continue with a set of mutually recursive procedures denoted by
  631. @var{names}, @var{vars}, and @var{funs}. @var{names} is a list of
  632. symbols, @var{vars} is a list of variable names (unique integers), and
  633. @var{funs} is a list of @code{$fun} values. Note that the @code{$kargs}
  634. continuation should also define @var{names}/@var{vars} bindings.
  635. @end deftp
  636. The contification pass will attempt to transform the functions declared
  637. in a @code{$rec} into local continuations. Any remaining @code{$fun}
  638. instances are later removed by the closure conversion pass. If the
  639. function has no free variables, it gets allocated as a constant.
  640. @deftp {CPS Expression} $const-fun label
  641. A constant which is a function whose entry point is @var{label}. As a
  642. constant, instances of @code{$const-fun} with the same @var{label} will
  643. not allocate; the space for the function is allocated as part of the
  644. compilation unit.
  645. In practice, @code{$const-fun} expressions are reified by CPS-conversion
  646. for functions whose call sites are not all visible within the
  647. compilation unit and which have no free variables. This expression kind
  648. is part of first-order CPS.
  649. @end deftp
  650. Otherwise, if the closure has free variables, it will be allocated at
  651. its definition site via an @code{allocate-words} primcall and its free
  652. variables initialized there. The code pointer in the closure is
  653. initialized from a @code{$code} expression.
  654. @deftp {CPS Expression} $code label
  655. Continue with the value of @var{label}, which should denote some
  656. @code{$kfun} continuation in the program. Used when initializing the
  657. code pointer of closure objects.
  658. @end deftp
  659. However, If the closure can be proven to never escape its scope then
  660. other lighter-weight representations can be chosen. Additionally, if
  661. all call sites are known, closure conversion will hard-wire the calls by
  662. lowering @code{$call} to @code{$callk}.
  663. @deftp {CPS Expression} $callk label proc args
  664. Like @code{$call}, but for the case where the call target is known to be
  665. in the same compilation unit. @var{label} should denote some
  666. @code{$kfun} continuation in the program. In this case the @var{proc}
  667. is simply an additional argument, since it is not used to determine the
  668. call target at run-time.
  669. @end deftp
  670. To summarize: a @code{$continue} is a CPS term that continues to a
  671. single label. But there are other kinds of CPS terms that can continue
  672. to a different number of labels: @code{$branch}, @code{$throw}, and
  673. @code{$prompt}.
  674. @deftp {CPS Term} $branch kf kt src op param args
  675. Evaluate the branching primcall @var{op}, with arguments @var{args} and
  676. constant parameter @var{param}, and continue to @var{kt} with zero
  677. values if the test is true. Otherwise continue to @var{kf}.
  678. The @code{$branch} term is like a @code{$continue} term with a
  679. @code{$primcall} expression, except that instead of binding a value and
  680. continuing to a single label, the result of the test is not bound but
  681. instead used to choose the continuation label.
  682. The set of operations (corresponding to @var{op} values) that are valid
  683. in a @var{$branch} is limited. In the general case, bind the result of
  684. a test expression to a variable, and then make a @code{$branch} on a
  685. @code{true?} op referencing that variable. The optimizer should inline
  686. the branch if possible.
  687. @end deftp
  688. @deftp {CPS Term} $throw src op param args
  689. Throw a non-resumable exception. Throw terms do not continue at all.
  690. The usual value of @var{op} is @code{throw}, with two arguments
  691. @var{key} and @var{args}. There are also some specific primcalls that
  692. compile to the VM @code{throw/value} and @code{throw/value+data}
  693. instructions; see the code for full details.
  694. The advantage of having @code{$throw} as a term is that, because it does
  695. not continue, this allows the optimizer to gather more information from
  696. type predicates. For example, if the predicate is @code{char?} and the
  697. @var{kf} continues to a throw, the set of labels dominated by @var{kt}
  698. is larger than if the throw notationally continued to some label that
  699. would never be reached by the throw.
  700. @end deftp
  701. @deftp {CPS Term} $prompt k kh src escape? tag
  702. Push a prompt on the stack identified by the variable name @var{tag},
  703. which may be escape-only if @var{escape?} is true, and continue to
  704. @var{kh} with zero values. If the body aborts to this prompt, control
  705. will proceed at the continuation labelled @var{kh}, which should be a
  706. @code{$kreceive} continuation. Prompts are later popped by
  707. @code{pop-prompt} primcalls.
  708. @end deftp
  709. At this point we have described terms, expressions, and the most common
  710. kind of continuation, @code{$kargs}. @code{$kargs} is used when the
  711. predecessors of the continuation can be instructed to pass the values
  712. where the continuation wants them. For example, if a @code{$kargs}
  713. continuation @var{k} binds a variable @var{v}, and the compiler decides
  714. to allocate @var{v} to slot 6, all predecessors of @var{k} should put
  715. the value for @var{v} in slot 6 before jumping to @var{k}. One
  716. situation in which this isn't possible is receiving values from function
  717. calls. Guile has a calling convention for functions which currently
  718. places return values on the stack. A continuation of a call must check
  719. that the number of values returned from a function matches the expected
  720. number of values, and then must shuffle or collect those values to named
  721. variables. @code{$kreceive} denotes this kind of continuation.
  722. @deftp {CPS Continuation} $kreceive arity k
  723. Receive values on the stack. Parse them according to @var{arity}, and
  724. then proceed with the parsed values to the @code{$kargs} continuation
  725. labelled @var{k}. As a limitation specific to @code{$kreceive},
  726. @var{arity} may only contain required and rest arguments.
  727. @end deftp
  728. @code{$arity} is a helper data structure used by @code{$kreceive} and
  729. also by @code{$kclause}, described below.
  730. @deftp {CPS Data} $arity req opt rest kw allow-other-keys?
  731. A data type declaring an arity. @var{req} and @var{opt} are lists of
  732. source names of required and optional arguments, respectively.
  733. @var{rest} is either the source name of the rest variable, or @code{#f}
  734. if this arity does not accept additional values. @var{kw} is a list of
  735. the form @code{((@var{keyword} @var{name} @var{var}) ...)}, describing
  736. the keyword arguments. @var{allow-other-keys?} is true if other keyword
  737. arguments are allowed and false otherwise.
  738. Note that all of these names with the exception of the @var{var}s in the
  739. @var{kw} list are source names, not unique variable names.
  740. @end deftp
  741. Additionally, there are three specific kinds of continuations that are
  742. only used in function entries.
  743. @deftp {CPS Continuation} $kfun src meta self tail clause
  744. Declare a function entry. @var{src} is the source information for the
  745. procedure declaration, and @var{meta} is the metadata alist as described
  746. above in Tree-IL's @code{<lambda>}. @var{self} is a variable bound to
  747. the procedure being called, and which may be used for self-references.
  748. @var{tail} is the label of the @code{$ktail} for this function,
  749. corresponding to the function's tail continuation. @var{clause} is the
  750. label of the first @code{$kclause} for the first @code{case-lambda}
  751. clause in the function, or otherwise @code{#f}.
  752. @end deftp
  753. @deftp {CPS Continuation} $ktail
  754. A tail continuation.
  755. @end deftp
  756. @deftp {CPS Continuation} $kclause arity cont alternate
  757. A clause of a function with a given arity. Applications of a function
  758. with a compatible set of actual arguments will continue to the
  759. continuation labelled @var{cont}, a @code{$kargs} instance representing
  760. the clause body. If the arguments are incompatible, control proceeds to
  761. @var{alternate}, which is a @code{$kclause} for the next clause, or
  762. @code{#f} if there is no next clause.
  763. @end deftp
  764. @node Building CPS
  765. @subsubsection Building CPS
  766. Unlike Tree-IL, the CPS language is built to be constructed and
  767. deconstructed with abstract macros instead of via procedural
  768. constructors or accessors, or instead of S-expression matching.
  769. Deconstruction and matching is handled adequately by the @code{match}
  770. form from @code{(ice-9 match)}. @xref{Pattern Matching}. Construction
  771. is handled by a set of mutually builder macros:
  772. @code{build-term}, @code{build-cont}, and @code{build-exp}.
  773. In the following interface definitions, consider @code{term} and
  774. @code{exp} to be built by @code{build-term} or @code{build-exp},
  775. respectively. Consider any other name to be evaluated as a Scheme
  776. expression. Many of these forms recognize @code{unquote} in some
  777. contexts, to splice in a previously-built value; see the specifications
  778. below for full details.
  779. @deffn {Scheme Syntax} build-term ,val
  780. @deffnx {Scheme Syntax} build-term ($continue k src exp)
  781. @deffnx {Scheme Syntax} build-exp ,val
  782. @deffnx {Scheme Syntax} build-exp ($const val)
  783. @deffnx {Scheme Syntax} build-exp ($prim name)
  784. @deffnx {Scheme Syntax} build-exp ($fun kentry)
  785. @deffnx {Scheme Syntax} build-exp ($const-fun kentry)
  786. @deffnx {Scheme Syntax} build-exp ($code kentry)
  787. @deffnx {Scheme Syntax} build-exp ($rec names syms funs)
  788. @deffnx {Scheme Syntax} build-exp ($call proc (arg ...))
  789. @deffnx {Scheme Syntax} build-exp ($call proc args)
  790. @deffnx {Scheme Syntax} build-exp ($callk k proc (arg ...))
  791. @deffnx {Scheme Syntax} build-exp ($callk k proc args)
  792. @deffnx {Scheme Syntax} build-exp ($primcall name param (arg ...))
  793. @deffnx {Scheme Syntax} build-exp ($primcall name param args)
  794. @deffnx {Scheme Syntax} build-exp ($values (arg ...))
  795. @deffnx {Scheme Syntax} build-exp ($values args)
  796. @deffnx {Scheme Syntax} build-exp ($prompt escape? tag handler)
  797. @deffnx {Scheme Syntax} build-term ($branch kf kt src op param (arg ...))
  798. @deffnx {Scheme Syntax} build-term ($branch kf kt src op param args)
  799. @deffnx {Scheme Syntax} build-term ($throw src op param (arg ...))
  800. @deffnx {Scheme Syntax} build-term ($throw src op param args)
  801. @deffnx {Scheme Syntax} build-term ($prompt k kh src escape? tag)
  802. @deffnx {Scheme Syntax} build-cont ,val
  803. @deffnx {Scheme Syntax} build-cont ($kargs (name ...) (sym ...) term)
  804. @deffnx {Scheme Syntax} build-cont ($kargs names syms term)
  805. @deffnx {Scheme Syntax} build-cont ($kreceive req rest kargs)
  806. @deffnx {Scheme Syntax} build-cont ($kfun src meta self ktail kclause)
  807. @deffnx {Scheme Syntax} build-cont ($kclause ,arity kbody kalt)
  808. @deffnx {Scheme Syntax} build-cont ($kclause (req opt rest kw aok?) kbody)
  809. Construct a CPS term, expression, or continuation.
  810. @end deffn
  811. There are a few more miscellaneous interfaces as well.
  812. @deffn {Scheme Procedure} make-arity req opt rest kw allow-other-keywords?
  813. A procedural constructor for @code{$arity} objects.
  814. @end deffn
  815. @deffn {Scheme Syntax} rewrite-term val (pat term) ...
  816. @deffnx {Scheme Syntax} rewrite-exp val (pat exp) ...
  817. @deffnx {Scheme Syntax} rewrite-cont val (pat cont) ...
  818. Match @var{val} against the series of patterns @var{pat...}, using
  819. @code{match}. The body of the matching clause should be a template in
  820. the syntax of @code{build-term}, @code{build-exp}, or @code{build-cont},
  821. respectively.
  822. @end deffn
  823. @node CPS Soup
  824. @subsubsection CPS Soup
  825. We describe programs in Guile's CPS language as being a kind of ``soup''
  826. because all continuations in the program are mixed into the same
  827. ``pot'', so to speak, without explicit markers as to what function or
  828. scope a continuation is in. A program in CPS is a map from continuation
  829. labels to continuation values. As discussed in the introduction, a
  830. continuation label is an integer. No label may be negative.
  831. As a matter of convention, label 0 should map to the @code{$kfun}
  832. continuation of the entry to the program, which should be a function of
  833. no arguments. The body of a function consists of the labelled
  834. continuations that are reachable from the function entry. A program can
  835. refer to other functions, either via @code{$fun} and @code{$rec} in
  836. higher-order CPS, or via @code{$const-fun}, @code{$callk}, and allocated
  837. closures in first-order CPS. The program logically contains all
  838. continuations of all functions reachable from the entry function. A
  839. compiler pass may leave unreachable continuations in a program;
  840. subsequent compiler passes should ensure that their transformations and
  841. analyses only take reachable continuations into account. It's OK though
  842. if transformation runs over all continuations if including the
  843. unreachable continuations has no effect on the transformations on the
  844. live continuations.
  845. @cindex intmap
  846. The ``soup'' itself is implemented as an @dfn{intmap}, a functional
  847. array-mapped trie specialized for integer keys. Intmaps associate
  848. integers with values of any kind. Currently intmaps are a private data
  849. structure only used by the CPS phase of the compiler. To work with
  850. intmaps, load the @code{(language cps intmap)} module:
  851. @example
  852. (use-modules (language cps intmap))
  853. @end example
  854. Intmaps are functional data structures, so there is no constructor as
  855. such: one can simply start with the empty intmap and add entries to it.
  856. @example
  857. (intmap? empty-intmap) @result{} #t
  858. (define x (intmap-add empty-intmap 42 "hi"))
  859. (intmap? x) @result{} #t
  860. (intmap-ref x 42) @result{} "hi"
  861. (intmap-ref x 43) @result{} @i{error: 43 not present}
  862. (intmap-ref x 43 (lambda (k) "yo!")) @result{} "yo"
  863. (intmap-add x 42 "hej") @result{} @i{error: 42 already present}
  864. @end example
  865. @code{intmap-ref} and @code{intmap-add} are the core of the intmap
  866. interface. There is also @code{intmap-replace}, which replaces the
  867. value associated with a given key, requiring that the key was present
  868. already, and @code{intmap-remove}, which removes a key from an intmap.
  869. Intmaps have a tree-like structure that is well-suited to set operations
  870. such as union and intersection, so there are also the binary
  871. @code{intmap-union} and @code{intmap-intersect} procedures. If the
  872. result is equivalent to either argument, that argument is returned
  873. as-is; in that way, one can detect whether the set operation produced a
  874. new result simply by checking with @code{eq?}. This makes intmaps
  875. useful when computing fixed points.
  876. If a key is present in both intmaps and the associated values are not
  877. the same in the sense of @code{eq?}, the resulting value is determined
  878. by a ``meet'' procedure, which is the optional last argument to
  879. @code{intmap-union}, @code{intmap-intersect}, and also to
  880. @code{intmap-add}, @code{intmap-replace}, and similar functions. The
  881. meet procedure will be called with the two values and should return the
  882. intersected or unioned value in some domain-specific way. If no meet
  883. procedure is given, the default meet procedure will raise an error.
  884. To traverse over the set of values in an intmap, there are the
  885. @code{intmap-next} and @code{intmap-prev} procedures. For example, if
  886. intmap @var{x} has one entry mapping 42 to some value, we would have:
  887. @example
  888. (intmap-next x) @result{} 42
  889. (intmap-next x 0) @result{} 42
  890. (intmap-next x 42) @result{} 42
  891. (intmap-next x 43) @result{} #f
  892. (intmap-prev x) @result{} 42
  893. (intmap-prev x 42) @result{} 42
  894. (intmap-prev x 41) @result{} #f
  895. @end example
  896. There is also the @code{intmap-fold} procedure, which folds over keys
  897. and values in the intmap from lowest to highest value, and
  898. @code{intmap-fold-right} which does so in the opposite direction. These
  899. procedures may take up to 3 seed values. The number of values that the
  900. fold procedure returns is the number of seed values.
  901. @example
  902. (define q (intmap-add (intmap-add empty-intmap 1 2) 3 4))
  903. (intmap-fold acons q '()) @result{} ((3 . 4) (1 . 2))
  904. (intmap-fold-right acons q '()) @result{} ((1 . 2) (3 . 4))
  905. @end example
  906. When an entry in an intmap is updated (removed, added, or changed), a
  907. new intmap is created that shares structure with the original intmap.
  908. This operation ensures that the result of existing computations is not
  909. affected by future computations: no mutation is ever visible to user
  910. code. This is a great property in a compiler data structure, as it lets
  911. us hold a copy of a program before a transformation and use it while we
  912. build a post-transformation program. Updating an intmap is O(log
  913. @var{n}) in the size of the intmap.
  914. However, the O(log @var{n}) allocation costs are sometimes too much,
  915. especially in cases when we know that we can just update the intmap in
  916. place. As an example, say we have an intmap mapping the integers 1 to
  917. 100 to the integers 42 to 141. Let's say that we want to transform this
  918. map by adding 1 to each value. There is already an efficient
  919. @code{intmap-map} procedure in the @code{(language cps utils}) module,
  920. but if we didn't know about that we might do:
  921. @example
  922. (define (intmap-increment map)
  923. (let lp ((k 0) (map map))
  924. (let ((k (intmap-next map k)))
  925. (if k
  926. (let ((v (intmap-ref map k)))
  927. (lp (1+ k) (intmap-replace map k (1+ v))))
  928. map))))
  929. @end example
  930. @cindex intmap, transient
  931. @cindex transient intmaps
  932. Observe that the intermediate values created by @code{intmap-replace}
  933. are completely invisible to the program -- only the last result of
  934. @code{intmap-replace} value is needed. The rest might as well share
  935. state with the last one, and we could update in place. Guile allows
  936. this kind of interface via @dfn{transient intmaps}, inspired by
  937. Clojure's transient interface (@uref{http://clojure.org/transients}).
  938. The in-place @code{intmap-add!} and @code{intmap-replace!} procedures
  939. return transient intmaps. If one of these in-place procedures is called
  940. on a normal persistent intmap, a new transient intmap is created. This
  941. is an O(1) operation. In all other respects the interface is like their
  942. persistent counterparts, @code{intmap-add} and @code{intmap-replace}.
  943. If an in-place procedure is called on a transient intmap, the intmap is
  944. mutated in-place and the same value is returned.
  945. If a persistent operation like @code{intmap-add} is called on a
  946. transient intmap, the transient's mutable substructure is then marked as
  947. persistent, and @code{intmap-add} then runs on a new persistent intmap
  948. sharing structure but not state with the original transient. Mutating a
  949. transient will cause enough copying to ensure that it can make its
  950. change, but if part of its substructure is already ``owned'' by it, no
  951. more copying is needed.
  952. We can use transients to make @code{intmap-increment} more efficient.
  953. The two changed elements have been marked @strong{like this}.
  954. @example
  955. (define (intmap-increment map)
  956. (let lp ((k 0) (map map))
  957. (let ((k (intmap-next map k)))
  958. (if k
  959. (let ((v (intmap-ref map k)))
  960. (lp (1+ k) (@strong{intmap-replace!} map k (1+ v))))
  961. (@strong{persistent-intmap} map)))))
  962. @end example
  963. Be sure to tag the result as persistent using the
  964. @code{persistent-intmap} procedure to prevent the mutability from
  965. leaking to other parts of the program. For added paranoia, you could
  966. call @code{persistent-intmap} on the incoming map, to ensure that if it
  967. were already transient, that the mutations in the body of
  968. @code{intmap-increment} wouldn't affect the incoming value.
  969. In summary, programs in CPS are intmaps whose values are continuations.
  970. See the source code of @code{(language cps utils)} for a number of
  971. useful facilities for working with CPS values.
  972. @node Compiling CPS
  973. @subsubsection Compiling CPS
  974. Compiling CPS in Guile has three phases: conversion, optimization, and
  975. code generation.
  976. CPS conversion is the process of taking a higher-level language and
  977. compiling it to CPS. Source languages can do this directly, or they can
  978. convert to Tree-IL (which is probably easier) and let Tree-IL convert to
  979. CPS later. Going through Tree-IL has the advantage of running Tree-IL
  980. optimization passes, like partial evaluation. Also, the compiler from
  981. Tree-IL to CPS handles assignment conversion, in which assigned local
  982. variables (in Tree-IL, locals that are @code{<lexical-set>}) are
  983. converted to being boxed values on the heap. @xref{Variables and the
  984. VM}.
  985. After CPS conversion, Guile runs some optimization passes over the CPS.
  986. Most optimization in Guile is done on the CPS language. The one major
  987. exception is partial evaluation, which for historic reasons is done on
  988. Tree-IL.
  989. The major optimization performed on CPS is contification, in which
  990. functions that are always called with the same continuation are
  991. incorporated directly into a function's body. This opens up space for
  992. more optimizations, and turns procedure calls into @code{goto}. It can
  993. also make loops out of recursive function nests. Guile also does dead
  994. code elimination, common subexpression elimination, loop peeling and
  995. invariant code motion, and range and type inference.
  996. The rest of the optimization passes are really cleanups and
  997. canonicalizations. CPS spans the gap between high-level languages and
  998. low-level bytecodes, which allows much of the compilation process to be
  999. expressed as source-to-source transformations. Such is the case for
  1000. closure conversion, in which references to variables that are free in a
  1001. function are converted to closure references, and in which functions are
  1002. converted to closures. There are a few more passes to ensure that the
  1003. only primcalls left in the term are those that have a corresponding
  1004. instruction in the virtual machine, and that their continuations expect
  1005. the right number of values.
  1006. Finally, the backend of the CPS compiler emits bytecode for each
  1007. function, one by one. To do so, it determines the set of live variables
  1008. at all points in the function. Using this liveness information, it
  1009. allocates stack slots to each variable, such that a variable can live in
  1010. one slot for the duration of its lifetime, without shuffling. (Of
  1011. course, variables with disjoint lifetimes can share a slot.) Finally
  1012. the backend emits code, typically just one VM instruction, for each
  1013. continuation in the function.
  1014. @node Bytecode
  1015. @subsection Bytecode
  1016. As mentioned before, Guile compiles all code to bytecode, and that
  1017. bytecode is contained in ELF images. @xref{Object File Format}, for
  1018. more on Guile's use of ELF.
  1019. To produce a bytecode image, Guile provides an assembler and a linker.
  1020. The assembler, defined in the @code{(system vm assembler)} module, has a
  1021. relatively straightforward imperative interface. It provides a
  1022. @code{make-assembler} function to instantiate an assembler and a set of
  1023. @code{emit-@var{inst}} procedures to emit instructions of each kind.
  1024. The @code{emit-@var{inst}} procedures are actually generated at
  1025. compile-time from a machine-readable description of the VM. With a few
  1026. exceptions for certain operand types, each operand of an emit procedure
  1027. corresponds to an operand of the corresponding instruction.
  1028. Consider @code{allocate-words}, from @pxref{Memory Access Instructions}.
  1029. It is documented as:
  1030. @deftypefn Instruction {} allocate-words s12:@var{dst} s12:@var{nwords}
  1031. @end deftypefn
  1032. Therefore the emit procedure has the form:
  1033. @deffn {Scheme Procedure} emit-allocate-words asm dst nwords
  1034. @end deffn
  1035. All emit procedure take the assembler as their first argument, and
  1036. return no useful values.
  1037. The argument types depend on the operand types. @xref{Instruction Set}.
  1038. Most are integers within a restricted range, though labels are generally
  1039. expressed as opaque symbols. Besides the emitters that correspond to
  1040. instructions, there are a few additional helpers defined in the
  1041. assembler module.
  1042. @deffn {Scheme Procedure} emit-label asm label
  1043. Define a label at the current program point.
  1044. @end deffn
  1045. @deffn {Scheme Procedure} emit-source asm source
  1046. Associate @var{source} with the current program point.
  1047. @end deffn
  1048. @deffn {Scheme Procedure} emit-cache-ref asm dst key
  1049. @deffnx {Scheme Procedure} emit-cache-set! asm key val
  1050. Macro-instructions to implement compilation-unit caches. A single cache
  1051. cell corresponding to @var{key} will be allocated for the compilation
  1052. unit.
  1053. @end deffn
  1054. @deffn {Scheme Procedure} emit-load-constant asm dst constant
  1055. Load the Scheme datum @var{constant} into @var{dst}.
  1056. @end deffn
  1057. @deffn {Scheme Procedure} emit-begin-program asm label properties
  1058. @deffnx {Scheme Procedure} emit-end-program asm
  1059. Delimit the bounds of a procedure, with the given @var{label} and the
  1060. metadata @var{properties}.
  1061. @end deffn
  1062. @deffn {Scheme Procedure} emit-load-static-procedure asm dst label
  1063. Load a procedure with the given @var{label} into local @var{dst}. This
  1064. macro-instruction should only be used with procedures without free
  1065. variables -- procedures that are not closures.
  1066. @end deffn
  1067. @deffn {Scheme Procedure} emit-begin-standard-arity asm req nlocals alternate
  1068. @deffnx {Scheme Procedure} emit-begin-opt-arity asm req opt rest nlocals alternate
  1069. @deffnx {Scheme Procedure} emit-begin-kw-arity asm req opt rest kw-indices allow-other-keys? nlocals alternate
  1070. @deffnx {Scheme Procedure} emit-end-arity asm
  1071. Delimit a clause of a procedure.
  1072. @end deffn
  1073. The linker is a complicated beast. Hackers interested in how it works
  1074. would do well do read Ian Lance Taylor's series of articles on linkers.
  1075. Searching the internet should find them easily. From the user's
  1076. perspective, there is only one knob to control: whether the resulting
  1077. image will be written out to a file or not. If the user passes
  1078. @code{#:to-file? #t} as part of the compiler options (@pxref{The Scheme
  1079. Compiler}), the linker will align the resulting segments on page
  1080. boundaries, and otherwise not.
  1081. @deffn {Scheme Procedure} link-assembly asm #:page-aligned?=#t
  1082. Link an ELF image, and return the bytevector. If @var{page-aligned?} is
  1083. true, Guile will align the segments with different permissions on
  1084. page-sized boundaries, in order to maximize code sharing between
  1085. different processes. Otherwise, padding is minimized, to minimize
  1086. address space consumption.
  1087. @end deffn
  1088. To write an image to disk, just use @code{put-bytevector} from
  1089. @code{(ice-9 binary-ports)}.
  1090. Compiling object code to the fake language, @code{value}, is performed
  1091. via loading objcode into a program, then executing that thunk with
  1092. respect to the compilation environment. Normally the environment
  1093. propagates through the compiler transparently, but users may specify the
  1094. compilation environment manually as well, as a module. Procedures to
  1095. load images can be found in the @code{(system vm loader)} module:
  1096. @lisp
  1097. (use-modules (system vm loader))
  1098. @end lisp
  1099. @deffn {Scheme Variable} load-thunk-from-file file
  1100. @deffnx {C Function} scm_load_thunk_from_file (file)
  1101. Load object code from a file named @var{file}. The file will be mapped
  1102. into memory via @code{mmap}, so this is a very fast operation.
  1103. @end deffn
  1104. @deffn {Scheme Variable} load-thunk-from-memory bv
  1105. @deffnx {C Function} scm_load_thunk_from_memory (bv)
  1106. Load object code from a bytevector. The data will be copied out of the
  1107. bytevector in order to ensure proper alignment of embedded Scheme
  1108. values.
  1109. @end deffn
  1110. Additionally there are procedures to find the ELF image for a given
  1111. pointer, or to list all mapped ELF images:
  1112. @deffn {Scheme Variable} find-mapped-elf-image ptr
  1113. Given the integer value @var{ptr}, find and return the ELF image that
  1114. contains that pointer, as a bytevector. If no image is found, return
  1115. @code{#f}. This routine is mostly used by debuggers and other
  1116. introspective tools.
  1117. @end deffn
  1118. @deffn {Scheme Variable} all-mapped-elf-images
  1119. Return all mapped ELF images, as a list of bytevectors.
  1120. @end deffn
  1121. @node Writing New High-Level Languages
  1122. @subsection Writing New High-Level Languages
  1123. In order to integrate a new language @var{lang} into Guile's compiler
  1124. system, one has to create the module @code{(language @var{lang} spec)}
  1125. containing the language definition and referencing the parser,
  1126. compiler and other routines processing it. The module hierarchy in
  1127. @code{(language brainfuck)} defines a very basic Brainfuck
  1128. implementation meant to serve as easy-to-understand example on how to
  1129. do this. See for instance @url{http://en.wikipedia.org/wiki/Brainfuck}
  1130. for more information about the Brainfuck language itself.
  1131. @node Extending the Compiler
  1132. @subsection Extending the Compiler
  1133. At this point we take a detour from the impersonal tone of the rest of
  1134. the manual. Admit it: if you've read this far into the compiler
  1135. internals manual, you are a junkie. Perhaps a course at your university
  1136. left you unsated, or perhaps you've always harbored a desire to hack the
  1137. holy of computer science holies: a compiler. Well you're in good
  1138. company, and in a good position. Guile's compiler needs your help.
  1139. There are many possible avenues for improving Guile's compiler.
  1140. Probably the most important improvement, speed-wise, will be some form
  1141. of optimized ahead-of-time native compilation with global register
  1142. allocation. A first pass could simply extend the compiler to also emit
  1143. machine code in addition to bytecode, pre-filling the corresponding JIT
  1144. data structures referenced by the @code{instrument-entry} bytecodes.
  1145. @xref{Instrumentation Instructions}.
  1146. The compiler also needs help at the top end, enhancing the Scheme that
  1147. it knows to also understand R7RS, and adding new high-level compilers.
  1148. We have JavaScript and Emacs Lisp mostly complete, but they could use
  1149. some love; Lua would be nice as well, but whatever language it is
  1150. that strikes your fancy would be welcome too.
  1151. Compilers are for hacking, not for admiring or for complaining about.
  1152. Get to it!