compiler.texi 60 KB

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