book.tex 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059
  1. \documentclass[12pt]{book}
  2. \usepackage[T1]{fontenc}
  3. \usepackage[utf8]{inputenc}
  4. \usepackage{lmodern}
  5. \usepackage{hyperref}
  6. \usepackage{graphicx}
  7. \usepackage[english]{babel}
  8. \usepackage{listings}
  9. \usepackage{amsmath}
  10. \usepackage{amsthm}
  11. \usepackage{amssymb}
  12. \usepackage{natbib}
  13. \usepackage{stmaryrd}
  14. \usepackage{xypic}
  15. \usepackage{semantic}
  16. \usepackage{wrapfig}
  17. % Computer Modern is already the default. -Jeremy
  18. %\renewcommand{\ttdefault}{cmtt}
  19. \lstset{%
  20. language=Lisp,
  21. basicstyle=\ttfamily\small,
  22. escapechar=@,
  23. columns=fullflexible
  24. }
  25. \newtheorem{theorem}{Theorem}
  26. \newtheorem{lemma}[theorem]{Lemma}
  27. \newtheorem{corollary}[theorem]{Corollary}
  28. \newtheorem{proposition}[theorem]{Proposition}
  29. \newtheorem{constraint}[theorem]{Constraint}
  30. \newtheorem{definition}[theorem]{Definition}
  31. \newtheorem{exercise}[theorem]{Exercise}
  32. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  33. % 'dedication' environment: To add a dedication paragraph at the start of book %
  34. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  35. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  36. \newenvironment{dedication}
  37. {
  38. \cleardoublepage
  39. \thispagestyle{empty}
  40. \vspace*{\stretch{1}}
  41. \hfill\begin{minipage}[t]{0.66\textwidth}
  42. \raggedright
  43. }
  44. {
  45. \end{minipage}
  46. \vspace*{\stretch{3}}
  47. \clearpage
  48. }
  49. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  50. % Chapter quote at the start of chapter %
  51. % Source: http://tex.stackexchange.com/a/53380 %
  52. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  53. \makeatletter
  54. \renewcommand{\@chapapp}{}% Not necessary...
  55. \newenvironment{chapquote}[2][2em]
  56. {\setlength{\@tempdima}{#1}%
  57. \def\chapquote@author{#2}%
  58. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  59. \itshape}
  60. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  61. \makeatother
  62. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  63. \newcommand{\itm}[1]{\ensuremath{\mathit{#1}}}
  64. \newcommand{\Stmt}{\itm{stmt}}
  65. \newcommand{\Exp}{\itm{exp}}
  66. \newcommand{\Instr}{\itm{instr}}
  67. \newcommand{\Prog}{\itm{prog}}
  68. \newcommand{\Arg}{\itm{arg}}
  69. \newcommand{\Int}{\itm{int}}
  70. \newcommand{\Var}{\itm{var}}
  71. \newcommand{\Op}{\itm{op}}
  72. \newcommand{\key}[1]{\texttt{#1}}
  73. \newcommand{\READ}{(\key{read})}
  74. \newcommand{\UNIOP}[2]{(\key{#1}\,#2)}
  75. \newcommand{\BINOP}[3]{(\key{#1}\,#2\,#3)}
  76. \newcommand{\LET}[3]{(\key{let}\,([#1\;#2])\,#3)}
  77. \newcommand{\ASSIGN}[2]{(\key{assign}\,#1\;#2)}
  78. \newcommand{\RETURN}[1]{(\key{return}\,#1)}
  79. \newcommand{\INT}[1]{(\key{int}\;#1)}
  80. \newcommand{\REG}[1]{(\key{reg}\;#1)}
  81. \newcommand{\VAR}[1]{(\key{var}\;#1)}
  82. \newcommand{\STACKLOC}[1]{(\key{stack}\;#1)}
  83. \newcommand{\IF}[3]{(\key{if}\,#1\;#2\;#3)}
  84. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  85. \title{\Huge \textbf{Essentials of Compilation} \\
  86. \huge An Incremental Approach}
  87. \author{\textsc{Jeremy G. Siek} \\
  88. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  89. Indiana University \\
  90. \\
  91. with contributions from: \\
  92. Carl Factora
  93. }
  94. \begin{document}
  95. \frontmatter
  96. \maketitle
  97. \begin{dedication}
  98. This book is dedicated to the programming language wonks at Indiana
  99. University.
  100. \end{dedication}
  101. \tableofcontents
  102. %\listoffigures
  103. %\listoftables
  104. \mainmatter
  105. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  106. \chapter*{Preface}
  107. Talk about nano-pass \citep{Sarkar:2004fk,Keep:2012aa} and incremental
  108. compilers \citep{Ghuloum:2006bh}.
  109. Talk about pre-requisites.
  110. %\section*{Structure of book}
  111. % You might want to add short description about each chapter in this book.
  112. %\section*{About the companion website}
  113. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  114. %\begin{itemize}
  115. % \item A link to (freely downlodable) latest version of this document.
  116. % \item Link to download LaTeX source for this document.
  117. % \item Miscellaneous material (e.g. suggested readings etc).
  118. %\end{itemize}
  119. \section*{Acknowledgments}
  120. Need to give thanks to
  121. \begin{itemize}
  122. \item Kent Dybvig
  123. \item Daniel P. Friedman
  124. \item Abdulaziz Ghuloum
  125. \item Oscar Waddell
  126. \item Dipanwita Sarkar
  127. \item Ronald Garcia
  128. \item Bor-Yuh Evan Chang
  129. \end{itemize}
  130. %\mbox{}\\
  131. %\noindent Amber Jain \\
  132. %\noindent \url{http://amberj.devio.us/}
  133. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  134. \chapter{Preliminaries}
  135. \label{ch:trees-recur}
  136. In this chapter, we review the basic tools that are needed for
  137. implementing a compiler. We use abstract syntax trees (ASTs) in the
  138. form of S-expressions to represent programs (Section~\ref{sec:ast})
  139. and pattern matching to inspect an AST node
  140. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  141. and deconstruct entire ASTs (Section~\ref{sec:recursion}).
  142. \section{Abstract Syntax Trees}
  143. \label{sec:ast}
  144. The primary data structure that is commonly used for representing
  145. programs is the \emph{abstract syntax tree} (AST). When considering
  146. some part of a program, a compiler needs to ask what kind of part it
  147. is and what sub-parts it has. For example, the program on the left is
  148. represented by the AST on the right.
  149. \begin{center}
  150. \begin{minipage}{0.4\textwidth}
  151. \begin{lstlisting}
  152. (+ (read) (- 8))
  153. \end{lstlisting}
  154. \end{minipage}
  155. \begin{minipage}{0.4\textwidth}
  156. \begin{equation}
  157. \xymatrix@=15pt{
  158. & *++[Fo]{+} \ar[dl]\ar[dr]& \\
  159. *+[Fo]{\tt read} & & *++[Fo]{-} \ar[d] \\
  160. & & *++[Fo]{\tt 8}
  161. } \label{eq:arith-prog}
  162. \end{equation}
  163. \end{minipage}
  164. \end{center}
  165. We shall use the standard terminology for trees: each square above is
  166. called a \emph{node}. The arrows connect a node to its \emph{children}
  167. (which are also nodes). The top-most node is the \emph{root}. Every
  168. node except for the root has a \emph{parent} (the node it is the child
  169. of). If a node has no children, it is a \emph{leaf} node. Otherwise
  170. it is an \emph{internal} node.
  171. When deciding how to compile the above program, we need to know that
  172. the root node an addition and that it has two children: \texttt{read}
  173. and the negation of \texttt{8}. The abstract syntax tree data
  174. structure directly supports these queries and hence is a good
  175. choice. In this book, we will often write down the textual
  176. representation of a program even when we really have in mind the AST,
  177. simply because the textual representation is easier to typeset. We
  178. recommend that, in your mind, you should alway interpret programs as
  179. abstract syntax trees.
  180. \section{Grammars}
  181. \label{sec:grammar}
  182. A programming language can be thought of as a \emph{set} of programs.
  183. The set is typically infinite (one can always create larger and larger
  184. programs), so one cannot simply describe a language by listing all of
  185. the programs in the language. Instead we write down a set of rules, a
  186. \emph{grammar}, for building programs. We shall write our rules in a
  187. variant of Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  188. As an example, we describe a small language, named $\itm{arith}$, of
  189. integers and arithmetic operations. The first rule says that any
  190. integer is in the language:
  191. \begin{equation}
  192. \itm{arith} ::= \Int \label{eq:arith-int}
  193. \end{equation}
  194. Each rule has a left-hand-side and a right-hand-side. The way to read
  195. a rule is that if you have all the program parts on the
  196. right-hand-side, then you can create and AST node and categorize it
  197. according to the left-hand-side. (We do not define $\Int$ because the
  198. reader already knows what an integer is.) A name such as $\itm{arith}$
  199. that is defined by the rules, is a \emph{non-terminal}.
  200. The second rule for the $\itm{arith}$ language is the \texttt{read}
  201. function to receive an input integer from the user of the program.
  202. \begin{equation}
  203. \itm{arith} ::= (\key{read}) \label{eq:arith-read}
  204. \end{equation}
  205. The third rule says that, given an $\itm{arith}$, you can build
  206. another arith by negating it.
  207. \begin{equation}
  208. \itm{arith} ::= (\key{-} \; \itm{arith}) \label{eq:arith-neg}
  209. \end{equation}
  210. Symbols such as \key{-} that play an auxilliary role in the abstract
  211. syntax are called \emph{terminal} symbols.
  212. By rule \eqref{eq:arith-int}, \texttt{8} is an $\itm{arith}$, then by
  213. rule \eqref{eq:arith-neg}, the following AST is an $\itm{arith}$.
  214. \begin{center}
  215. \begin{minipage}{0.25\textwidth}
  216. \begin{lstlisting}
  217. (- 8)
  218. \end{lstlisting}
  219. \end{minipage}
  220. \begin{minipage}{0.25\textwidth}
  221. \begin{equation}
  222. \xymatrix@=15pt{
  223. *+[Fo]{-} \ar[d] \\
  224. *+[Fo]{\tt 8}
  225. }
  226. \label{eq:arith-neg8}
  227. \end{equation}
  228. \end{minipage}
  229. \end{center}
  230. The last rule for the $\itm{arith}$ language is for addition:
  231. \begin{equation}
  232. \itm{arith} ::= (\key{+} \; \itm{arith} \; \itm{arith}) \label{eq:arith-add}
  233. \end{equation}
  234. Now we can see that the AST \eqref{eq:arith-prog} is in $\itm{arith}$.
  235. We know that \lstinline{(read)} is in $\itm{arith}$ by rule
  236. \eqref{eq:arith-read} and we have shown that \texttt{(- 8)} is in
  237. $\itm{arith}$, so we can apply rule \eqref{eq:arith-add} to show that
  238. \texttt{(+ (read) (- 8))} is in the $\itm{arith}$ language.
  239. If you have an AST for which the above four rules do not apply, then
  240. the AST is not in $\itm{arith}$. For example, the AST \texttt{(- (read)
  241. (+ 8))} is not in $\itm{arith}$ because there are no rules for $+$
  242. with only one argument, nor for $-$ with two arguments. Whenever we
  243. define a language through a grammar, we implicitly mean for the
  244. language to be the smallest set of programs that are justified by the
  245. rules. That is, the language only includes those programs that the
  246. rules allow.
  247. It is common to have many rules with the same left-hand side, so the
  248. following vertical bar notation is used to gather several rules on one
  249. line. We refer to each clause between a vertical bar as an
  250. ``alternative''.
  251. \[
  252. \itm{arith} ::= \Int \mid (\key{read}) \mid (\key{-} \; \itm{arith}) \mid
  253. (\key{+} \; \itm{arith} \; \itm{arith})
  254. \]
  255. \section{S-Expressions}
  256. \label{sec:s-expr}
  257. Racket, as a descendant of Lisp~\citep{McCarthy:1960dz}, has
  258. particularly convenient support for creating and manipulating abstract
  259. syntax trees with its \emph{symbolic expression} feature, or
  260. S-expression for short. We can create an S-expression simply by
  261. writing a backquote followed by the textual representation of the
  262. AST. (Technically speaking, this is called a \emph{quasiquote} in
  263. Racket.) For example, an S-expression to represent the AST
  264. \eqref{eq:arith-prog} is created by the following Racket expression:
  265. \begin{center}
  266. \texttt{`(+ (read) (- 8))}
  267. \end{center}
  268. To build larger S-expressions one often needs to splice together
  269. several smaller S-expressions. Racket provides the comma operator to
  270. splice an S-expression into a larger one. For example, instead of
  271. creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  272. we could have first created an S-expression for AST
  273. \eqref{eq:arith-neg8} and then spliced that into the addition
  274. S-expression.
  275. \begin{lstlisting}
  276. (define ast1.4 `(- 8))
  277. (define ast1.1 `(+ (read) ,ast1.4))
  278. \end{lstlisting}
  279. In general, the Racket expression that follows the comma (splice)
  280. can be any expression that computes an S-expression.
  281. \section{Pattern Matching}
  282. \label{sec:pattern-matching}
  283. As mentioned above, one of the operations that a compiler needs to
  284. perform on an AST is to access the children of a node. Racket
  285. provides the \texttt{match} form to access the parts of an
  286. S-expression. Consider the following example and the output on the
  287. right.
  288. \begin{center}
  289. \begin{minipage}{0.5\textwidth}
  290. \begin{lstlisting}
  291. (match ast1.1
  292. [`(,op ,child1 ,child2)
  293. (print op) (newline)
  294. (print child1) (newline)
  295. (print child2)])
  296. \end{lstlisting}
  297. \end{minipage}
  298. \vrule
  299. \begin{minipage}{0.25\textwidth}
  300. \begin{lstlisting}
  301. '+
  302. '(read)
  303. '(- 8)
  304. \end{lstlisting}
  305. \end{minipage}
  306. \end{center}
  307. The \texttt{match} form takes AST \eqref{eq:arith-prog} and binds its
  308. parts to the three variables \texttt{op}, \texttt{child1}, and
  309. \texttt{child2}. In general, a match clause consists of a
  310. \emph{pattern} and a \emph{body}. The pattern is a quoted S-expression
  311. that may contain pattern-variables (preceded by a comma). The body
  312. may contain any Racket code.
  313. A \texttt{match} form may contain several clauses, as in the following
  314. function \texttt{leaf?} that recognizes when an $\itm{arith}$ node is
  315. a leaf. The \texttt{match} proceeds through the clauses in order,
  316. checking whether the pattern can match the input S-expression. The
  317. body of the first clause that matches is executed. The output of
  318. \texttt{leaf?} for several S-expressions is shown on the right. In the
  319. below \texttt{match}, we see another form of pattern: the \texttt{(?
  320. fixnum?)} applies the predicate \texttt{fixnum?} to the input
  321. S-expression to see if it is a machine-representable integer.
  322. \begin{center}
  323. \begin{minipage}{0.5\textwidth}
  324. \begin{lstlisting}
  325. (define (leaf? arith)
  326. (match arith
  327. [(? fixnum?) #t]
  328. [`(read) #t]
  329. [`(- ,c1) #f]
  330. [`(+ ,c1 ,c2) #f]))
  331. (leaf? `(read))
  332. (leaf? `(- 8))
  333. (leaf? `(+ (read) (- 8)))
  334. \end{lstlisting}
  335. \end{minipage}
  336. \vrule
  337. \begin{minipage}{0.25\textwidth}
  338. \begin{lstlisting}
  339. #t
  340. #f
  341. #f
  342. \end{lstlisting}
  343. \end{minipage}
  344. \end{center}
  345. %% From this grammar, we have defined {\tt arith} by constraining its
  346. %% syntax. Effectively, we have defined {\tt arith} by first defining
  347. %% what a legal expression (or program) within the language is. To
  348. %% clarify further, we can think of {\tt arith} as a \textit{set} of
  349. %% expressions, where, under syntax constraints, \mbox{{\tt (+ 1 1)}} and
  350. %% {\tt -1} are inhabitants and {\tt (+ 3.2 3)} and {\tt (++ 2 2)} are
  351. %% not (see ~Figure\ref{fig:ast}).
  352. %% The relationship between a grammar and an AST is then similar to that
  353. %% of a set and an inhabitant. From this, every syntaxically valid
  354. %% expression, under the constraints of a grammar, can be represented by
  355. %% an abstract syntax tree. This is because {\tt arith} is essentially a
  356. %% specification of a Tree-like data-structure. In this case, tree nodes
  357. %% are the arithmetic operators {\tt +} and {\tt -}, and the leaves are
  358. %% integer constants. From this, we can represent any expression of {\tt
  359. %% arith} using a \textit{syntax expression} (s-exp).
  360. %% \begin{figure}[htbp]
  361. %% \centering
  362. %% \fbox{
  363. %% \begin{minipage}{0.85\textwidth}
  364. %% \[
  365. %% \begin{array}{lcl}
  366. %% exp &::=& sexp \mid (sexp*) \mid (unquote \; sexp) \\
  367. %% sexp &::=& Val \mid Var \mid (quote \; exp) \mid (quasiquote \; exp)
  368. %% \end{array}
  369. %% \]
  370. %% \end{minipage}
  371. %% }
  372. %% \caption{\textit{s-exp} syntax: $Val$ and $Var$ are shorthand for Value and Variable.}
  373. %% \label{fig:sexp-syntax}
  374. %% \end{figure}
  375. %% For our purposes, we will treat s-exps equivalent to \textit{possibly
  376. %% deeply-nested lists}. For the sake of brevity, the symbols $single$
  377. %% $quote$ ('), $backquote$ (`), and $comma$ (,) are reader sugar for
  378. %% {\tt quote}, {\tt quasiquote}, and {\tt unquote}. We provide several
  379. %% examples of s-exps and functions that return s-exps below. We use the
  380. %% {\tt >} symbol to represent interaction with a Racket REPL.
  381. %% \begin{verbatim}
  382. %% (define 1plus1 `(1 + 1))
  383. %% (define (1plusX x) `(1 + ,x))
  384. %% (define (XplusY x y) `(,x + ,y))
  385. %% > 1plus1
  386. %% '(1 + 1)
  387. %% > (1plusX 1)
  388. %% '(1 + 1)
  389. %% > (XplusY 1 1)
  390. %% '(1 + 1)
  391. %% > `,1plus1
  392. %% '(1 + 1)
  393. %% \end{verbatim}
  394. %% In any expression wrapped with {\tt quasiquote} ({\tt `}), sub-expressions
  395. %% wrapped with an {\tt unquote} expression are evaluated before the entire
  396. %% expression is returned wrapped in a {\tt quote} expression.
  397. % \marginpar{\scriptsize Introduce s-expressions, quote, and quasi-quote, and comma in
  398. % this section. Make sure to include examples of ASTs. The description
  399. % here of grammars is incomplete. It doesn't really say what grammars are or what they do, it
  400. % just shows an example. I would recommend reading my blog post: a crash course on
  401. % notation in PL theory, especially the sections on Definition by Rules
  402. % and Language Syntax and Grammars. -JGS}
  403. % \marginpar{\scriptsize The lambda calculus is more complex of an example that what we really
  404. % need at this point. I think we can make due with just integers and arithmetic. -JGS}
  405. % \marginpar{\scriptsize Regarding de-Bruijnizing as an example... that strikes me
  406. % as something that may be foreign to many readers. The examples in this
  407. % first chapter should try to be simple and hopefully connect with things
  408. % that the reader is already familiar with. -JGS}
  409. % \begin{enumerate}
  410. % \item Syntax transformation
  411. % \item Some Racket examples (factorial?)
  412. % \end{enumerate}
  413. %% For our purposes, our compiler will take a Scheme-like expression and
  414. %% transform it to X86\_64 Assembly. Along the way, we transform each
  415. %% input expression into a handful of \textit{intermediary languages}
  416. %% (IL). A key tool for transforming one language into another is
  417. %% \textit{pattern matching}.
  418. %% Racket provides a built-in pattern-matcher, {\tt match}, that we can
  419. %% use to perform operations on s-exps. As a preliminary example, we
  420. %% include a familiar definition of factorial, first without using match.
  421. %% \begin{verbatim}
  422. %% (define (! n)
  423. %% (if (zero? n) 1
  424. %% (* n (! (sub1 n)))))
  425. %% \end{verbatim}
  426. %% In this form of factorial, we are simply conditioning (viz. {\tt zero?})
  427. %% on the inputted natural number, {\tt n}. If we rewrite factorial using
  428. %% {\tt match}, we can match on the actual value of {\tt n}.
  429. %% \begin{verbatim}
  430. %% (define (! n)
  431. %% (match n
  432. %% (0 1)
  433. %% (n (* n (! (sub1 n))))))
  434. %% \end{verbatim}
  435. %% In this definition of factorial, the first {\tt match} line (viz. {\tt (0 1)})
  436. %% can be read as "if {\tt n} is 0, then return 1." The second line matches on an
  437. %% arbitrary variable, {\tt n}, and does not place any constraints on it. We could
  438. %% have also written this line as {\tt (else (* n (! (sub1 n))))}, where {\tt n}
  439. %% is scoped by {\tt match}. Of course, we can also use {\tt match} to pattern
  440. %% match on more complex expressions.
  441. \section{Recursion}
  442. \label{sec:recursion}
  443. Programs are inherently recursive in that an $\itm{arith}$ AST is made
  444. up of smaller $\itm{arith}$ ASTs. Thus, the natural way to process in
  445. entire program is with a recursive function. As a first example of
  446. such a function, we define \texttt{arith?} below, which takes an
  447. arbitrary S-expression, {\tt sexp}, and determines whether or not {\tt
  448. sexp} is in {\tt arith}. Note that each match clause corresponds to
  449. one grammar rule for $\itm{arith}$ and the body of each clause makes a
  450. recursive call for each child node. This pattern of recursive function
  451. is so common that it has a name, \emph{structural recursion}. In
  452. general, when a recursive function is defined using a set of match
  453. clauses that correspond to a grammar, and each clause body makes a
  454. recursive call on each child node, then we say the function is defined
  455. by structural recursion.
  456. \begin{center}
  457. \begin{minipage}{0.7\textwidth}
  458. \begin{lstlisting}
  459. (define (arith? sexp)
  460. (match sexp
  461. [(? fixnum?) #t]
  462. [`(read) #t]
  463. [`(- ,e) (arith? e)]
  464. [`(+ ,e1 ,e2)
  465. (and (arith? e1) (arith? e2))]
  466. [else #f]))
  467. (arith? `(+ (read) (- 8)))
  468. (arith? `(- (read) (+ 8)))
  469. \end{lstlisting}
  470. \end{minipage}
  471. \vrule
  472. \begin{minipage}{0.25\textwidth}
  473. \begin{lstlisting}
  474. #t
  475. #f
  476. \end{lstlisting}
  477. \end{minipage}
  478. \end{center}
  479. %% Here, {\tt \#:when} puts constraints on the value of matched expressions.
  480. %% In this case, we make sure that every sub-expression in \textit{op} position
  481. %% is either {\tt +} or {\tt -}. Otherwise, we return an error, signaling a
  482. %% non-{\tt arith} expression. As we mentioned earlier, every expression
  483. %% wrapped in an {\tt unquote} is evaluated first. When used in a LHS {\tt match}
  484. %% sub-expression, these expressions evaluate to the actual value of the matched
  485. %% expression (i.e., {\tt arith-exp}). Thus, {\tt `(,e1 ,op ,e2)} and
  486. %% {\tt `(e1 op e2)} are not equivalent.
  487. % \begin{enumerate}
  488. % \item \textit{What is a base case?}
  489. % \item Using on a language (lambda calculus ->
  490. % \end{enumerate}
  491. %% Before getting into more complex {\tt match} examples, we first
  492. %% introduce the concept of \textit{structural recursion}, which is the
  493. %% general name for recurring over Tree-like or \textit{possibly
  494. %% deeply-nested list} structures. The key to performing structural
  495. %% recursion, which from now on we refer to simply as recursion, is to
  496. %% have some form of specification for the structure we are recurring
  497. %% on. Luckily, we are already familiar with one: a BNF or grammar.
  498. %% For example, let's take the grammar for $S_0$, which we include below.
  499. %% Writing a recursive program that takes an arbitrary expression of $S_0$
  500. %% should handle each expression in the grammar. An example program that
  501. %% we can write is an $interpreter$. To keep our interpreter simple, we
  502. %% ignore the {\tt read} operator.
  503. %% \begin{figure}[htbp]
  504. %% \centering
  505. %% \fbox{
  506. %% \begin{minipage}{0.85\textwidth}
  507. %% \[
  508. %% \begin{array}{lcl}
  509. %% \Op &::=& \key{+} \mid \key{-} \mid \key{*} \mid \key{read} \\
  510. %% \Exp &::=& \Int \mid (\Op \; \Exp^{*}) \mid \Var \mid \LET{\Var}{\Exp}{\Exp}
  511. %% \end{array}
  512. %% \]
  513. %% \end{minipage}
  514. %% }
  515. %% \caption{The syntax of the $S_0$ language. The abbreviation \Op{} is
  516. %% short for operator, \Exp{} is short for expression, \Int{} for integer,
  517. %% and \Var{} for variable.}
  518. %% %\label{fig:s0-syntax}
  519. %% \end{figure}
  520. %% \begin{verbatim}
  521. %% \end{verbatim}
  522. \section{Interpreter}
  523. \label{sec:interp-arith}
  524. The meaning, or semantics, of a program is typically defined in the
  525. specification of the language. For example, the Scheme language is
  526. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  527. defined in its reference manual~\citep{plt-tr}. In this book we use an
  528. interpreter to define the meaning of each language that we consider,
  529. following Reynold's advice in this
  530. regard~\citep{reynolds72:_def_interp}. Here we will warm up by writing
  531. an interpreter for the $\itm{arith}$ language, which will also serve
  532. as a second example of structural recursion. The \texttt{interp-arith}
  533. function is defined in Figure~\ref{fig:interp-arith}. The body of the
  534. function is a match on the input expression \texttt{e} and there is
  535. one clause per grammar rule for $\itm{arith}$. The clauses for
  536. internal AST nodes make recursive calls to \texttt{interp-arith} on
  537. each child node.
  538. \begin{figure}[tbp]
  539. \begin{lstlisting}
  540. (define (interp-arith e)
  541. (match e
  542. [(? fixnum?) e]
  543. [`(read)
  544. (define r (read))
  545. (cond [(fixnum? r) r]
  546. [else (error 'interp-arith "expected an integer" r)])]
  547. [`(- ,e)
  548. (fx- 0 (interp-arith e))]
  549. [`(+ ,e1 ,e2)
  550. (fx+ (interp-arith e1) (interp-arith e2))]
  551. ))
  552. \end{lstlisting}
  553. \caption{Interpreter for the $\itm{arith}$ language.}
  554. \label{fig:interp-arith}
  555. \end{figure}
  556. We make the simplifying design decision that the $\itm{arith}$
  557. language (and all of the languages in this book) only handle
  558. machine-representable integers, that is, the \texttt{fixnum} datatype
  559. in Racket. Thus, we implement the arithmetic operations using the
  560. appropriate fixnum operators.
  561. If we interpret the AST \eqref{eq:arith-prog} and give it the input
  562. \texttt{50}
  563. \begin{lstlisting}
  564. (interp-arith ast1.1)
  565. \end{lstlisting}
  566. we get the answer to life, the universe, and everything
  567. \begin{lstlisting}
  568. 42
  569. \end{lstlisting}
  570. The job of a compiler is to translate programs in one language into
  571. programs in another language (typically but not always a language with
  572. a lower level of abstraction) in such a way that each output program
  573. behaves the same way as the input program. This idea is depicted in
  574. the following diagram. Suppose we have two languages, $\mathcal{L}_1$
  575. and $\mathcal{L}_2$, and an interpreter for each language. Suppose
  576. that the compiler translates program $P_1$ in language $\mathcal{L}_1$
  577. into program $P_2$ in language $\mathcal{L}_2$. Then interpreting
  578. $P_1$ and $P_2$ on the respective interpreters for the two languages,
  579. and given the same inputs $i$, should yield the same output $o$.
  580. \begin{equation} \label{eq:compile-correct}
  581. \xymatrix@=50pt{
  582. P_1 \ar[r]^{compile}\ar[dr]_{\mathcal{L}_1-interp(i)} & P_2 \ar[d]^{\mathcal{L}_2-interp(i)} \\
  583. & o
  584. }
  585. \end{equation}
  586. In the next section we will see our first example of a compiler, which
  587. is also be another example of structural recursion.
  588. \section{Partial Evaluation}
  589. \label{sec:partial-evaluation}
  590. In this section we consider a compiler that translates $\itm{arith}$
  591. programs into $\itm{arith}$ programs that are more efficient, that is,
  592. this compiler is an optimizer. Our optimizer will accomplish this by
  593. trying to eagerly compute the parts of the program that do not depend
  594. on any inputs. For example, given the following program
  595. \begin{lstlisting}
  596. (+ (read) (- (+ 5 3)))
  597. \end{lstlisting}
  598. our compiler will translate it into the program
  599. \begin{lstlisting}
  600. (+ (read) -8)
  601. \end{lstlisting}
  602. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  603. evaluator for the $\itm{arith}$ language. The output of the partial
  604. evaluator is an $\itm{arith}$ program, which we build up using a
  605. combination of quasiquotes and commas. (Though no quasiquote is
  606. necessary for integers.) In Figure~\ref{fig:pe-arith}, the normal
  607. structural recursion is captured in the main \texttt{pe-arith}
  608. function whereas the code for partially evaluating negation and
  609. addition is factored out the into two separate helper functions:
  610. \texttt{pe-neg} and \texttt{pe-add}. The input to these helper
  611. functions is the output of partially evaluating the children nodes.
  612. \begin{figure}[tbp]
  613. \begin{lstlisting}
  614. (define (pe-neg r)
  615. (match r
  616. [(? fixnum?) (fx- 0 r)]
  617. [else `(- ,r)]))
  618. (define (pe-add r1 r2)
  619. (match (list r1 r2)
  620. [`(,n1 ,n2) #:when (and (fixnum? n1) (fixnum? n2))
  621. (fx+ r1 r2)]
  622. [else `(+ ,r1 ,r2)]))
  623. (define (pe-arith e)
  624. (match e
  625. [(? fixnum?) e]
  626. [`(read) `(read)]
  627. [`(- ,e1) (pe-neg (pe-arith e1))]
  628. [`(+ ,e1 ,e2) (pe-add (pe-arith e1) (pe-arith e2))]))
  629. \end{lstlisting}
  630. \caption{A partial evaluator for the $\itm{arith}$ language.}
  631. \label{fig:pe-arith}
  632. \end{figure}
  633. Our code for \texttt{pe-neg} and \texttt{pe-add} implements the simple
  634. idea of checking whether the inputs are integers and if they are, to
  635. go ahead perform the arithmetic. Otherwise, we use quasiquote to
  636. create an AST node for the appropriate operation (either negation or
  637. addition) and use comma to splice in the child nodes.
  638. To gain some confidence that the partial evaluator is correct, we can
  639. test whether it produces programs that get the same result as the
  640. input program. That is, we can test whether it satisfies Diagram
  641. \eqref{eq:compile-correct}. The following code runs the partial
  642. evaluator on several examples and tests the output program. The
  643. \texttt{assert} function is defined in Appendix~\ref{sec:utilities}.
  644. \begin{lstlisting}
  645. (define (test-pe pe p)
  646. (assert "testing pe-arith"
  647. (equal? (interp-arith p) (interp-arith (pe-arith p)))))
  648. (test-pe `(+ (read) (- (+ 5 3))))
  649. (test-pe `(+ 1 (+ (read) 1)))
  650. (test-pe `(- (+ (read) (- 5))))
  651. \end{lstlisting}
  652. \begin{exercise}
  653. We challenge the reader to improve on the simple partial evaluator in
  654. Figure~\ref{fig:pe-arith} by replacing the \texttt{pe-neg} and
  655. \texttt{pe-add} helper functions with functions that know more about
  656. arithmetic. For example, your partial evaluator should translate
  657. \begin{lstlisting}
  658. (+ 1 (+ (read) 1))
  659. \end{lstlisting}
  660. into
  661. \begin{lstlisting}
  662. (+ 2 (read))
  663. \end{lstlisting}
  664. To accomplish this, we recomend that your partial evaluator produce
  665. output that takes the form of the $\itm{residual}$ non-terminal in the
  666. following grammar.
  667. \[
  668. \begin{array}{lcl}
  669. e &::=& (\key{read}) \mid (\key{-} \;(\key{read})) \mid (\key{+} \;e\; e)\\
  670. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; e) \mid e
  671. \end{array}
  672. \]
  673. \end{exercise}
  674. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  675. \chapter{Integers and Variables}
  676. \label{ch:int-exp}
  677. This chapter concerns the challenge of compiling a subset of Racket,
  678. which we name $S_0$, to x86-64 assembly code. The chapter begins with
  679. a description of the $S_0$ language (Section~\ref{sec:s0}) and then a
  680. description of x86-64 (Section~\ref{sec:x86-64}). The x86-64 assembly
  681. language is quite large, so we only discuss what is needed for
  682. compiling $S_0$. We will introduce more of x86-64 in later
  683. chapters. Once we have introduced $S_0$ and x86-64, we reflect on
  684. their differences and come up with a plan for a handful of steps that
  685. will take us from $S_0$ to x86-64 (Section~\ref{sec:plan-s0-x86}).
  686. The rest of the sections in this Chapter give detailed hints regarding
  687. what each step should do and how to organize your code
  688. (Sections~\ref{sec:uniquify-s0}, \ref{sec:flatten-s0},
  689. \ref{sec:select-s0} \ref{sec:assign-s0}, and \ref{sec:patch-s0}). We
  690. hope to give enough hints that the well-prepared reader can implement
  691. a compiler from $S_0$ to x86-64 while at the same time leaving room
  692. for some fun and creativity.
  693. \section{The $S_0$ Language}
  694. \label{sec:s0}
  695. The $S_0$ language includes integers, operations on integers
  696. (arithmetic and input), and variable definitions. The syntax of the
  697. $S_0$ language is defined by the grammar in
  698. Figure~\ref{fig:s0-syntax}. This language is rich enough to exhibit
  699. several compilation techniques but simple enough so that we can
  700. implement a compiler for it in two weeks of hard work. To give the
  701. reader a feeling for the scale of this first compiler, the instructor
  702. solution for the $S_0$ compiler consists of 6 recursive functions and
  703. a few small helper functions that together span 256 lines of code.
  704. \begin{figure}[btp]
  705. \centering
  706. \fbox{
  707. \begin{minipage}{0.85\textwidth}
  708. \[
  709. \begin{array}{lcl}
  710. \Op &::=& \key{+} \mid \key{-} \mid \key{*} \mid \key{read} \\
  711. \Exp &::=& \Int \mid (\Op \; \Exp^{*}) \mid \Var \mid \LET{\Var}{\Exp}{\Exp}
  712. \end{array}
  713. \]
  714. \end{minipage}
  715. }
  716. \caption{The syntax of the $S_0$ language. The abbreviation \Op{} is
  717. short for operator, \Exp{} is short for expression, \Int{} for integer,
  718. and \Var{} for variable.}
  719. \label{fig:s0-syntax}
  720. \end{figure}
  721. The result of evaluating an expression is a value. For $S_0$, values
  722. are integers. To make it straightforward to map these integers onto
  723. x86-64 assembly~\citep{Matz:2013aa}, we restrict the integers to just
  724. those representable with 64-bits, the range $-2^{63}$ to $2^{63}$
  725. (``fixnums'' in Racket parlance).
  726. We start with some examples of $S_0$ programs, commenting on aspects
  727. of the language that will be relevant to compiling it. We start with
  728. one of the simplest $S_0$ programs; it adds two integers.
  729. \[
  730. \BINOP{+}{10}{32}
  731. \]
  732. The result is $42$, as you might expected.
  733. %
  734. The next example demonstrates that expressions may be nested within
  735. each other, in this case nesting several additions and negations.
  736. \[
  737. \BINOP{+}{10}{ \UNIOP{-}{ \BINOP{+}{12}{20} } }
  738. \]
  739. What is the result of the above program?
  740. The \key{let} construct defines a variable for used within it's body
  741. and initializes the variable with the value of an expression. So the
  742. following program initializes $x$ to $32$ and then evaluates the body
  743. $\BINOP{+}{10}{x}$, producing $42$.
  744. \[
  745. \LET{x}{ \BINOP{+}{12}{20} }{ \BINOP{+}{10}{x} }
  746. \]
  747. When there are multiple \key{let}'s for the same variable, the closest
  748. enclosing \key{let} is used. That is, variable definitions overshadow
  749. prior definitions. Consider the following program with two \key{let}'s
  750. that define variables named $x$. Can you figure out the result?
  751. \[
  752. \LET{x}{32}{ \BINOP{+}{ \LET{x}{10}{x} }{ x } }
  753. \]
  754. For the purposes of showing which variable uses correspond to which
  755. definitions, the following shows the $x$'s annotated with subscripts
  756. to distinguish them. Double check that your answer for the above is
  757. the same as your answer for this annotated version of the program.
  758. \[
  759. \LET{x_1}{32}{ \BINOP{+}{ \LET{x_2}{10}{x_2} }{ x_1 } }
  760. \]
  761. Moving on, the \key{read} operation prompts the user of the program
  762. for an integer. Given an input of $10$, the following program produces
  763. $42$.
  764. \[
  765. \BINOP{+}{(\key{read})}{32}
  766. \]
  767. We include the \key{read} operation in $S_0$ to demonstrate that order
  768. of evaluation can make a different. Given the input $52$ then $10$,
  769. the following produces $42$ (and not $-42$).
  770. \[
  771. \LET{x}{\READ}{ \LET{y}{\READ}{ \BINOP{-}{x}{y} } }
  772. \]
  773. The initializing expression is always evaluated before the body of the
  774. \key{let}, so in the above, the \key{read} for $x$ is performed before
  775. the \key{read} for $y$.
  776. %
  777. The behavior of the following program is somewhat subtle because
  778. Racket does not specify an evaluation order for arguments of an
  779. operator such as $-$.
  780. \[
  781. \BINOP{-}{\READ}{\READ}
  782. \]
  783. Given the input $42$ then $10$, the above program can result in either
  784. $42$ or $-42$, depending on the whims of the Racket implementation.
  785. The goal for this chapter is to implement a compiler that translates
  786. any program $P_1 \in S_0$ into a x86-64 assembly program $P_2$ such
  787. that the assembly program exhibits the same behavior on an x86
  788. computer as the $S_0$ program running in a Racket implementation.
  789. \[
  790. \xymatrix{
  791. P_1 \in S_0 \ar[rr]^{\text{compile}} \ar[drr]_{\text{run in Racket}\quad} && P_2 \in \text{x86-64} \ar[d]^{\quad\text{run on an x86 machine}}\\
  792. & & n \in \mathbb{Z}
  793. }
  794. \]
  795. In the next section we introduce enough of the x86-64 assembly
  796. language to compile $S_0$.
  797. \section{The x86-64 Assembly Language}
  798. \label{sec:x86-64}
  799. An x86-64 program is a sequence of instructions. The instructions may
  800. refer to integer constants (called \emph{immediate values}), variables
  801. called \emph{registers}, and instructions may load and store values
  802. into \emph{memory}. Memory is a mapping of 64-bit addresses to 64-bit
  803. values. Figure~\ref{fig:x86-a} defines the syntax for the subset of
  804. the x86-64 assembly language needed for this chapter.
  805. An immediate value is written using the notation \key{\$}$n$ where $n$
  806. is an integer.
  807. %
  808. A register is written with a \key{\%} followed by the register name,
  809. such as \key{\%rax}.
  810. %
  811. An access to memory is specified using the syntax $n(\key{\%}r)$,
  812. which reads register $r$, obtaining address $a$, and then offsets the
  813. address by $n$ bytes (8 bits), producing the address $a + n$. The
  814. address is then used to either load or store to memory depending on
  815. whether it occurs as a source or destination argument of an
  816. instruction.
  817. An arithmetic instruction, such as $\key{addq}\,s\,d$, reads from the
  818. source argument $s$ and destination argument $d$, applies the
  819. arithmetic operation, then write the result in the destination $d$. In
  820. this case, computing $d \gets d + s$.
  821. %
  822. The move instruction, $\key{movq}\,s\,d$ reads from $s$ and stores the
  823. result in $d$.
  824. %
  825. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  826. specified by the label, which we shall use to implement
  827. \key{read}.
  828. \begin{figure}[tbp]
  829. \fbox{
  830. \begin{minipage}{0.96\textwidth}
  831. \[
  832. \begin{array}{lcl}
  833. \itm{register} &::=& \key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  834. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  835. && \key{r8} \mid \key{r9} \mid \key{r10}
  836. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  837. \mid \key{r14} \mid \key{r15} \\
  838. \Arg &::=& \key{\$}\Int \mid \key{\%}\itm{register} \mid \Int(\key{\%}\itm{register}) \\
  839. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  840. \key{subq} \; \Arg, \Arg \mid
  841. \key{imulq} \; \Arg,\Arg \mid
  842. \key{negq} \; \Arg \mid \\
  843. && \key{movq} \; \Arg, \Arg \mid
  844. \key{callq} \; \mathit{label} \mid
  845. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \\
  846. \Prog &::= & \key{.globl \_main}\\
  847. & & \key{\_main:} \; \Instr^{+}
  848. \end{array}
  849. \]
  850. \end{minipage}
  851. }
  852. \caption{A subset of the x86-64 assembly language.}
  853. \label{fig:x86-a}
  854. \end{figure}
  855. \begin{wrapfigure}{r}{2.25in}
  856. \begin{lstlisting}
  857. .globl _main
  858. _main:
  859. movq $10, %rax
  860. addq $32, %rax
  861. retq
  862. \end{lstlisting}
  863. \caption{An x86-64 program equivalent to $\BINOP{+}{10}{32}$.}
  864. \label{fig:p0-x86}
  865. \end{wrapfigure}
  866. Figure~\ref{fig:p0-x86} depicts an x86-64 program that is equivalent to
  867. $\BINOP{+}{10}{32}$. The \key{globl} directive says that the
  868. \key{\_main} procedure is externally visible, which is necessary so
  869. that the operating system can call it. The label \key{\_main:}
  870. indicates the beginning of the \key{\_main} procedure which is where
  871. the operating system starting executing this program. The instruction
  872. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  873. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  874. $10$ in \key{rax} and puts the result, $42$, back into
  875. \key{rax}. The instruction \key{retq} finishes the \key{\_main}
  876. function by returning the integer in the \key{rax} register to the
  877. operating system.
  878. \begin{wrapfigure}{r}{2.25in}
  879. \begin{lstlisting}
  880. .globl _main
  881. _main:
  882. pushq %rbp
  883. movq %rsp, %rbp
  884. subq $16, %rsp
  885. movq $10, -8(%rbp)
  886. negq -8(%rbp)
  887. movq $52, %rax
  888. addq -8(%rbp), %rax
  889. addq $16, %rsp
  890. popq %rbp
  891. retq
  892. \end{lstlisting}
  893. \caption{An x86-64 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  894. \label{fig:p1-x86}
  895. \end{wrapfigure}
  896. The next example exhibits the use of memory. Figure~\ref{fig:p1-x86}
  897. lists an x86-64 program that is equivalent to $\BINOP{+}{52}{
  898. \UNIOP{-}{10} }$. To understand how this x86-64 program works, we
  899. need to explain a region of memory called called the \emph{procedure
  900. call stack} (or \emph{stack} for short). The stack consists of a
  901. separate \emph{frame} for each procedure call. The memory layout for
  902. an individual frame is shown in Figure~\ref{fig:frame}. The register
  903. \key{rsp} is called the \emph{stack pointer} and points to the item at
  904. the top of the stack. The stack grows downward in memory, so we
  905. increase the size of the stack by subtracting from the stack
  906. pointer. The frame size is required to be a multiple of 16 bytes. The
  907. register \key{rbp} is the \emph{base pointer} which serves two
  908. purposes: 1) it saves the location of the stack pointer for the
  909. procedure that called the current one and 2) it is used to access
  910. variables associated with the current procedure. We number the
  911. variables from $1$ to $n$. Variable $1$ is stored at address
  912. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  913. \begin{figure}[tbp]
  914. \centering
  915. \begin{tabular}{|r|l|} \hline
  916. Position & Contents \\ \hline
  917. 8(\key{\%rbp}) & return address \\
  918. 0(\key{\%rbp}) & old \key{rbp} \\
  919. -8(\key{\%rbp}) & variable $1$ \\
  920. -16(\key{\%rbp}) & variable $2$ \\
  921. \ldots & \ldots \\
  922. 0(\key{\%rsp}) & variable $n$\\ \hline
  923. \end{tabular}
  924. \caption{Memory layout of a frame.}
  925. \label{fig:frame}
  926. \end{figure}
  927. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  928. three instructions are the typical prelude for a procedure. The
  929. instruction \key{pushq \%rbp} saves the base pointer for the procedure
  930. that called the current one onto the stack and subtracts $8$ from the
  931. stack pointer. The second instruction \key{movq \%rsp, \%rbp} changes
  932. the base pointer to the top of the stack. The instruction \key{subq
  933. \$16, \%rsp} moves the stack pointer down to make enough room for
  934. storing variables. This program just needs one variable ($8$ bytes)
  935. but because the frame size is required to be a multiple of 16 bytes,
  936. it rounds to 16 bytes.
  937. The next four instructions carry out the work of computing
  938. $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction \key{movq \$10,
  939. -8(\%rbp)} stores $10$ in variable $1$. The instruction \key{negq
  940. -8(\%rbp)} changes variable $1$ to $-10$. The \key{movq \$52, \%rax}
  941. places $52$ in the register \key{rax} and \key{addq -8(\%rbp), \%rax}
  942. adds the contents of variable $1$ to \key{rax}, at which point
  943. \key{rax} contains $42$.
  944. The last three instructions are the typical \emph{conclusion} of a
  945. procedure. These instructions are necessary to get the state of the
  946. machine back to where it was before the current procedure was called.
  947. The \key{addq \$16, \%rsp} instruction moves the stack pointer back to
  948. point at the old base pointer. The amount added here needs to match
  949. the amount that was subtracted in the prelude of the procedure. Then
  950. \key{popq \%rbp} returns the old base pointer to \key{rbp} and adds
  951. $8$ to the stack pointer. The \key{retq} instruction jumps back to
  952. the procedure that called this one and subtracts 8 from the stack
  953. pointer.
  954. The compiler will need a convenient representation for manipulating
  955. x86 programs, so we define an abstract syntax for x86 in
  956. Figure~\ref{fig:x86-ast-a}. The \itm{info} field of the \key{program}
  957. AST node is for storing auxilliary information that needs to be
  958. communicated from one step of the compiler to the next. The function
  959. \key{print-x86} provided in the supplemental code converts an x86
  960. abstract syntax tree into the text representation for x86
  961. (Figure~\ref{fig:x86-a}).
  962. \begin{figure}[tbp]
  963. \fbox{
  964. \begin{minipage}{0.96\textwidth}
  965. \vspace{-10pt}
  966. \[
  967. \begin{array}{lcl}
  968. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  969. \mid \STACKLOC{\Int} \\
  970. \Instr &::=& (\key{add} \; \Arg\; \Arg) \mid
  971. (\key{sub} \; \Arg\; \Arg) \mid
  972. (\key{imul} \; \Arg\;\Arg) \mid
  973. (\key{neg} \; \Arg) \mid \\
  974. && (\key{mov} \; \Arg\; \Arg) \mid
  975. (\key{call} \; \mathit{label}) \mid
  976. (\key{push}\;\Arg) \mid (\key{pop}\;\Arg) \mid (\key{ret}) \\
  977. \Prog &::= & (\key{program} \;\itm{info} \; \Instr^{+})
  978. \end{array}
  979. \]
  980. \end{minipage}
  981. }
  982. \caption{Abstract syntax for x86-64 assembly.}
  983. \label{fig:x86-ast-a}
  984. \end{figure}
  985. \section{From $S_0$ to x86-64 via $C_0$}
  986. \label{sec:plan-s0-x86}
  987. To compile one language to another it helps to focus on the
  988. differences between the two languages. It is these differences that
  989. the compiler will need to bridge. What are the differences between
  990. $S_0$ and x86-64 assembly? Here we list some of the most important the
  991. differences.
  992. \begin{enumerate}
  993. \item x86-64 arithmetic instructions typically take two arguments and
  994. update the second argument in place. In contrast, $S_0$ arithmetic
  995. operations only read their arguments and produce a new value.
  996. \item An argument to an $S_0$ operator can be any expression, whereas
  997. x86-64 instructions restrict their arguments to integers, registers,
  998. and memory locations.
  999. \item An $S_0$ program can have any number of variables whereas x86-64
  1000. has only 16 registers.
  1001. \item Variables in $S_0$ can overshadow other variables with the same
  1002. name. The registers and memory locations of x86-64 all have unique
  1003. names.
  1004. \end{enumerate}
  1005. We ease the challenge of compiling from $S_0$ to x86 by breaking down
  1006. the problem into several steps, dealing with the above differences one
  1007. at a time. The main question then becomes: in what order do we tackle
  1008. these differences? This is often one of the most challenging questions
  1009. that a compiler writer must answer because some orderings may be much
  1010. more difficult to implement than others. It is difficult to know ahead
  1011. of time which orders will be better so often some trial-and-error is
  1012. involved. However, we can try to plan ahead and choose the orderings
  1013. based on this planning.
  1014. For example, to handle difference \#2 (nested expressions), we shall
  1015. introduce new variables and pull apart the nested expressions into a
  1016. sequence of assignment statements. To deal with difference \#3 we
  1017. will be replacing variables with registers and/or stack
  1018. locations. Thus, it makes sense to deal with \#2 before \#3 so that
  1019. \#3 can replace both the original variables and the new ones. Next,
  1020. consider where \#1 should fit in. Because it has to do with the format
  1021. of x86 instructions, it makes more sense after we have flattened the
  1022. nested expressions (\#2). Finally, when should we deal with \#4
  1023. (variable overshadowing)? We shall solve this problem by renaming
  1024. variables to make sure they have unique names. Recall that our plan
  1025. for \#2 involves moving nested expressions, which could be problematic
  1026. if it changes the shadowing of variables. However, if we deal with \#4
  1027. first, then it will not be an issue. Thus, we arrive at the following
  1028. ordering.
  1029. \[
  1030. \xymatrix{
  1031. 4 \ar[r] & 2 \ar[r] & 1 \ar[r] & 3
  1032. }
  1033. \]
  1034. We further simplify the translation from $S_0$ to x86 by identifying
  1035. an intermediate language named $C_0$, roughly half-way between $S_0$
  1036. and x86, to provide a rest stop along the way. We name the language
  1037. $C_0$ because it is vaguely similar to the $C$
  1038. language~\citep{Kernighan:1988nx}. The differences \#4 and \#1,
  1039. regarding variables and nested expressions, are handled by the passes
  1040. \textsf{uniquify} and \textsf{flatten} that bring us to $C_0$.
  1041. \[\large
  1042. \xymatrix@=50pt{
  1043. S_0 \ar@/^/[r]^-{\textsf{uniquify}} &
  1044. S_0 \ar@/^/[r]^-{\textsf{flatten}} &
  1045. C_0
  1046. }
  1047. \]
  1048. The syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}. The
  1049. $C_0$ language supports the same operators as $S_0$ but the arguments
  1050. of operators are now restricted to just variables and integers. The
  1051. \key{let} construct of $S_0$ is replaced by an assignment statement
  1052. and there is a \key{return} construct to specify the return value of
  1053. the program. A program consists of a sequence of statements that
  1054. include at least one \key{return} statement.
  1055. \begin{figure}[tbp]
  1056. \fbox{
  1057. \begin{minipage}{0.96\textwidth}
  1058. \[
  1059. \begin{array}{lcl}
  1060. \Arg &::=& \Int \mid \Var \\
  1061. \Exp &::=& \Arg \mid (\Op \; \Arg^{*})\\
  1062. \Stmt &::=& \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} \\
  1063. \Prog & ::= & (\key{program}\;\itm{info}\;\Stmt^{+})
  1064. \end{array}
  1065. \]
  1066. \end{minipage}
  1067. }
  1068. \caption{The $C_0$ intermediate language.}
  1069. \label{fig:c0-syntax}
  1070. \end{figure}
  1071. To get from $C_0$ to x86-64 assembly requires three more steps, which
  1072. we discuss below.
  1073. \[\large
  1074. \xymatrix@=50pt{
  1075. C_0 \ar@/^/[r]^-{\textsf{select\_instr.}}
  1076. & \text{x86}^{*} \ar@/^/[r]^-{\textsf{assign\_homes}}
  1077. & \text{x86}^{*} \ar@/^/[r]^-{\textsf{patch\_instr.}}
  1078. & \text{x86}
  1079. }
  1080. \]
  1081. We handle difference \#1, concerning the format of arithmetic
  1082. instructions, in the \textsf{select\_instructions} pass. The result
  1083. of this pass produces programs consisting of x86-64 instructions that
  1084. use variables.
  1085. %
  1086. As there are only 16 registers, we cannot always map variables to
  1087. registers (difference \#3). Fortunately, the stack can grow quite, so
  1088. we can map variables to locations on the stack. This is handled in the
  1089. \textsf{assign\_homes} pass. The topic of
  1090. Chapter~\ref{ch:register-allocation} is implementing a smarter
  1091. approach in which we make a best-effort to map variables to registers,
  1092. resorting to the stack only when necessary.
  1093. The final pass in our journey to x86 handles an indiosycracy of x86
  1094. assembly. Many x86 instructions have two arguments but only one of the
  1095. arguments may be a memory reference. Because we are mapping variables
  1096. to stack locations, many of our generated instructions will violate
  1097. this restriction. The purpose of the \textsf{patch\_instructions} pass
  1098. is to fix this problem by replacing every bad instruction with a short
  1099. sequence of instructions that use the \key{rax} register.
  1100. \section{Uniquify Variables}
  1101. \label{sec:uniquify-s0}
  1102. The purpose of this pass is to make sure that each \key{let} uses a
  1103. unique variable name. For example, the \textsf{uniquify} pass could
  1104. translate
  1105. \[
  1106. \LET{x}{32}{ \BINOP{+}{ \LET{x}{10}{x} }{ x } }
  1107. \]
  1108. to
  1109. \[
  1110. \LET{x.1}{32}{ \BINOP{+}{ \LET{x.2}{10}{x.2} }{ x.1 } }
  1111. \]
  1112. We recommend implementing \textsf{uniquify} as a recursive function
  1113. that mostly just copies the input program. However, when encountering
  1114. a \key{let}, it should generate a unique name for the variable (the
  1115. Racket function \key{gensym} is handy for this) and associate the old
  1116. name with the new unique name in an association list. The
  1117. \textsf{uniquify} function will need to access this association list
  1118. when it gets to a variable reference, so we add another paramter to
  1119. \textsf{uniquify} for the association list.
  1120. \section{Flatten Expressions}
  1121. \label{sec:flatten-s0}
  1122. The purpose of the \textsf{flatten} pass is to get rid of nested
  1123. expressions, such as the $\UNIOP{-}{10}$ in the following program,
  1124. without changing the behavior of the program.
  1125. \[
  1126. \BINOP{+}{52}{ \UNIOP{-}{10} }
  1127. \]
  1128. This can be accomplished by introducing a new variable, assigning the
  1129. nested expression to the new variable, and then using the new variable
  1130. in place of the nested expressions. For example, the above program is
  1131. translated to the following one.
  1132. \[
  1133. \begin{array}{l}
  1134. \ASSIGN{ \itm{x} }{ \UNIOP{-}{10} } \\
  1135. \RETURN{ \BINOP{+}{52}{ \itm{x} } }
  1136. \end{array}
  1137. \]
  1138. We recommend implementing \textsf{flatten} as a recursive function
  1139. that returns two things, 1) the newly flattened expression, and 2) a
  1140. list of assignment statements, one for each of the new variables
  1141. introduced while flattening the expression.
  1142. Take special care for programs such as the following that initialize
  1143. variables with integers or other variables.
  1144. \[
  1145. \LET{a}{42}{ \LET{b}{a}{ b }}
  1146. \]
  1147. This program should be translated to
  1148. \[
  1149. \ASSIGN{a}{42} \;
  1150. \ASSIGN{b}{a} \;
  1151. \RETURN{b}
  1152. \]
  1153. and not the following, which could result from a naive implementation
  1154. of \textsf{flatten}.
  1155. \[
  1156. \ASSIGN{x.1}{42}\;
  1157. \ASSIGN{a}{x.1}\;
  1158. \ASSIGN{x.2}{a}\;
  1159. \ASSIGN{b}{x.2}\;
  1160. \RETURN{b}
  1161. \]
  1162. \section{Select Instructions}
  1163. \label{sec:select-s0}
  1164. In the \textsf{select\_instructions} pass we begin the work of
  1165. translating from $C_0$ to x86. The target language of this pass is a
  1166. pseudo-x86 language that still uses variables, so we add an AST node
  1167. of the form $\VAR{\itm{var}}$. The \textsf{select\_instructions} pass
  1168. deals with the differing format of arithmetic operations. For example,
  1169. in $C_0$ an addition operation could take the following form:
  1170. \[
  1171. \ASSIGN{x}{ \BINOP{+}{10}{32} }
  1172. \]
  1173. To translate to x86, we need to express this addition using the
  1174. \key{add} instruction that does an inplace update. So we first move
  1175. $10$ to $x$ then perform the \key{add}.
  1176. \[
  1177. (\key{mov}\,\INT{10}\, \VAR{x})\; (\key{add} \;\INT{32}\; \VAR{x})
  1178. \]
  1179. There are some cases that require special care to avoid generating
  1180. needlessly complicated code. If one of the arguments is the same as
  1181. the left-hand side of the assignment, then there is no need for the
  1182. extra move instruction. For example, the following
  1183. \[
  1184. \ASSIGN{x}{ \BINOP{+}{10}{x} }
  1185. \quad\text{should translate to}\quad
  1186. (\key{add} \; \INT{10}\; \VAR{x})
  1187. \]
  1188. Regarding the \RETURN{e} statement of $C_0$, we recommend treating it
  1189. as an assignment to the \key{rax} register and let the procedure
  1190. conclusion handle the transfer of control back to the calling
  1191. procedure.
  1192. \section{Assign Homes}
  1193. \label{sec:assign-s0}
  1194. As discussed in Section~\ref{sec:plan-s0-x86}, the
  1195. \textsf{assign\_homes} pass places all of the variables on the stack.
  1196. Consider again the example $S_0$ program $\BINOP{+}{52}{ \UNIOP{-}{10} }$,
  1197. which after \textsf{select\_instructions} looks like the following.
  1198. \[
  1199. \begin{array}{l}
  1200. (\key{mov}\;\INT{10}\; \VAR{x})\\
  1201. (\key{neg}\; \VAR{x})\\
  1202. (\key{mov}\; \INT{52}\; \REG{\itm{rax}})\\
  1203. (\key{add}\; \VAR{x} \REG{\itm{rax}})
  1204. \end{array}
  1205. \]
  1206. The one and only variable $x$ is assigned to stack location
  1207. \key{-8(\%rbp)}, so the \textsf{assign\_homes} pass translates the
  1208. above to
  1209. \[
  1210. \begin{array}{l}
  1211. (\key{mov}\;\INT{10}\; \STACKLOC{{-}8})\\
  1212. (\key{neg}\; \STACKLOC{{-}8})\\
  1213. (\key{mov}\; \INT{52}\; \REG{\itm{rax}})\\
  1214. (\key{add}\; \STACKLOC{{-}8}\; \REG{\itm{rax}})
  1215. \end{array}
  1216. \]
  1217. In the process of assigning stack locations to variables, it is
  1218. convenient to compute and store the size of the frame which will be
  1219. needed later to generate the procedure conclusion.
  1220. \section{Patch Instructions}
  1221. \label{sec:patch-s0}
  1222. The purpose of this pass is to make sure that each instruction adheres
  1223. to the restrictions regarding which arguments can be memory
  1224. references. For most instructions, the rule is that at most one
  1225. argument may be a memory reference.
  1226. Consider again the following example.
  1227. \[
  1228. \LET{a}{42}{ \LET{b}{a}{ b }}
  1229. \]
  1230. After \textsf{assign\_homes} pass, the above has been translated to
  1231. \[
  1232. \begin{array}{l}
  1233. (\key{mov} \;\INT{42}\; \STACKLOC{{-}8})\\
  1234. (\key{mov}\;\STACKLOC{{-}8}\; \STACKLOC{{-}16})\\
  1235. (\key{mov}\;\STACKLOC{{-}16}\; \REG{\itm{rax}})
  1236. \end{array}
  1237. \]
  1238. The second \key{mov} instruction is problematic because both arguments
  1239. are stack locations. We suggest fixing this problem by moving from the
  1240. source to \key{rax} and then from \key{rax} to the destination, as
  1241. follows.
  1242. \[
  1243. \begin{array}{l}
  1244. (\key{mov} \;\INT{42}\; \STACKLOC{{-}8})\\
  1245. (\key{mov}\;\STACKLOC{{-}8}\; \REG{\itm{rax}})\\
  1246. (\key{mov}\;\REG{\itm{rax}}\; \STACKLOC{{-}16})\\
  1247. (\key{mov}\;\STACKLOC{{-}16}\; \REG{\itm{rax}})
  1248. \end{array}
  1249. \]
  1250. The \key{imul} instruction is a special case because the destination
  1251. argument must be a register.
  1252. \section{Testing with Interpreters}
  1253. The typical way to test a compiler is to run the generated assembly
  1254. code on a diverse set of programs and check whether they behave as
  1255. expected. However, when a compiler is structured as our is, with many
  1256. passes, when there is an error in the generated assembly code it can
  1257. be hard to determine which pass contains the source of the error. A
  1258. good way to isolate the error is to not only test the generated
  1259. assembly code but to also test the output of every pass. This requires
  1260. having interpreters for all the intermediate languages. Indeed, the
  1261. file \key{interp.rkt} in the supplemental code provides interpreters
  1262. for all the intermediate languages described in this book, starting
  1263. with interpreters for $S_0$, $C_0$, and x86 (in abstract syntax).
  1264. The file \key{run-tests.rkt} automates the process of running the
  1265. interpreters on the output programs of each pass and checking their
  1266. result.
  1267. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1268. \chapter{Register Allocation}
  1269. \label{ch:register-allocation}
  1270. In Chapter~\ref{ch:int-exp} we simplified the generation of x86
  1271. assembly by placing all variables on the stack. We can improve the
  1272. performance of the generated code considerably if we instead try to
  1273. place as many variables as possible into registers. The CPU can
  1274. access a register in a single cycle, whereas accessing the stack can
  1275. take from several cycles (to go to cache) to hundreds of cycles (to go
  1276. to main memory). Figure~\ref{fig:reg-eg} shows a program with four
  1277. variables that serves as a running example. We show the source program
  1278. and also the output of instruction selection. At that point the
  1279. program is almost x86 assembly but not quite; it still contains
  1280. variables instead of stack locations or registers.
  1281. \begin{figure}
  1282. \begin{minipage}{0.45\textwidth}
  1283. Source program:
  1284. \begin{lstlisting}
  1285. (let ([v 1])
  1286. (let ([w 46])
  1287. (let ([x (+ v 7)])
  1288. (let ([y (+ 4 x)])
  1289. (let ([z (+ x w)])
  1290. (- z y))))))
  1291. \end{lstlisting}
  1292. \end{minipage}
  1293. \begin{minipage}{0.45\textwidth}
  1294. After instruction selection:
  1295. \begin{lstlisting}
  1296. (program (v w x y z)
  1297. (mov (int 1) (var v))
  1298. (mov (int 46) (var w))
  1299. (mov (var v) (var x))
  1300. (add (int 7) (var x))
  1301. (mov (var x) (var y))
  1302. (add (int 4) (var y))
  1303. (mov (var x) (var z))
  1304. (add (var w) (var z))
  1305. (mov (var z) (reg rax))
  1306. (sub (var y) (reg rax)))
  1307. \end{lstlisting}
  1308. \end{minipage}
  1309. \caption{Running example for this chapter.}
  1310. \label{fig:reg-eg}
  1311. \end{figure}
  1312. The goal of register allocation is to fit as many variables into
  1313. registers as possible. It is often the case that we have more
  1314. variables than registers, so we can't naively map each variable to a
  1315. register. Fortunately, it is also common for different variables to be
  1316. needed during different periods of time, and in such cases the
  1317. variables can be mapped to the same register. Consider variables $x$
  1318. and $y$ in Figure~\ref{fig:reg-eg}. After the variable $x$ is moved
  1319. to $z$ it is no longer needed. Variable $y$, on the other hand, is
  1320. used only after this point, so $x$ and $y$ could share the same
  1321. register. The topic of the next section is how we compute where a
  1322. variable is needed.
  1323. \section{Liveness Analysis}
  1324. A variable is \emph{live} if the variable is used at some later point
  1325. in the program and there is not an intervening assignment to the
  1326. variable.
  1327. %
  1328. To understand the latter condition, consider the following code
  1329. fragment in which there are two writes to $b$. Are $a$ and
  1330. $b$ both live at the same time?
  1331. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  1332. (mov (int 5) (var a)) ; @$a \gets 5$@
  1333. (mov (int 30) (var b)) ; @$b \gets 30$@
  1334. (mov (var a) (var c)) ; @$c \gets x$@
  1335. (mov (int 10) (var b)) ; @$b \gets 10$@
  1336. (add (var b) (var c)) ; @$c \gets c + b$@
  1337. \end{lstlisting}
  1338. The answer is no because the value $30$ written to $b$ on line 2 is
  1339. never used. The variable $b$ is read on line 5 and there is an
  1340. intervening write to $b$ on line 4, so the read on line 5 receives the
  1341. value written on line 4, not line 2.
  1342. The live variables can be computed by traversing the instruction
  1343. sequence back to front (i.e., backwards in execution order). Let
  1344. $I_1,\ldots, I_n$ be the instruction sequence. We write
  1345. $L_{\mathsf{after}}(k)$ for the set of live variables after
  1346. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  1347. variables before instruction $I_k$. The live variables after an
  1348. instruction are always the same as the live variables before the next
  1349. instruction.
  1350. \begin{equation*}
  1351. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  1352. \end{equation*}
  1353. To start things off, there are no live variables after the last
  1354. instruction, so
  1355. \begin{equation*}
  1356. L_{\mathsf{after}}(n) = \emptyset
  1357. \end{equation*}
  1358. We then apply the following rule repeatedly, traversing the
  1359. instruction sequence back to front.
  1360. \begin{equation*}
  1361. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  1362. \end{equation*}
  1363. where $W(k)$ are the variables written to by instruction $I_k$ and
  1364. $R(k)$ are the variables read by instruction $I_k$.
  1365. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  1366. for the running example. Next to each instruction we write its
  1367. $L_{\mathtt{after}}$ set.
  1368. \begin{figure}[tbp]
  1369. \begin{lstlisting}
  1370. (program (v w x y z)
  1371. (mov (int 1) (var v)) @$\{ v \}$@
  1372. (mov (int 46) (var w)) @$\{ v, w \}$@
  1373. (mov (var v) (var x)) @$\{ w, x \}$@
  1374. (add (int 7) (var x)) @$\{ w, x \}$@
  1375. (mov (var x) (var y)) @$\{ w, x, y\}$@
  1376. (add (int 4) (var y)) @$\{ w, x, y \}$@
  1377. (mov (var x) (var z)) @$\{ w, y, z \}$@
  1378. (add (var w) (var z)) @$\{ y, z \}$@
  1379. (mov (var z) (reg rax)) @$\{ y \}$@
  1380. (sub (var y) (reg rax))) @$\{\}$@
  1381. \end{lstlisting}
  1382. \caption{Running example program annotated with live-after sets.}
  1383. \label{fig:live-eg}
  1384. \end{figure}
  1385. \section{Building the Interference Graph}
  1386. Based on the liveness analysis, we know the program regions where each
  1387. variable is needed. However, during register allocation, we need to
  1388. answer questions of the specific form: are variables $u$ and $v$ ever
  1389. live at the same time? (And therefore cannot be assigned to the same
  1390. register.) To make this question easier to answer, we create an
  1391. explicit data structure, an \emph{interference graph}. An
  1392. interference graph is an undirected graph that has an edge between two
  1393. variables if they are live at the same time, that is, if they
  1394. interfere with each other.
  1395. The most obvious way to compute the interference graph is to look at
  1396. the set of live variables between each statement in the program, and
  1397. add an edge to the graph for every pair of variables in the same set.
  1398. This approach is less than ideal for two reasons. First, it can be
  1399. rather expensive because it takes $O(n^2)$ time to look at every pair
  1400. in a set of $n$ live variables. Second, there is a special case in
  1401. which two variables that are live at the same time do not actually
  1402. interfere with each other: when they both contain the same value
  1403. because we have assigned one to the other.
  1404. A better way to compute the edges of the intereference graph is given
  1405. by the following rules.
  1406. \begin{itemize}
  1407. \item If instruction $I_k$ is a move: (\key{mov} $s$\, $d$), then add
  1408. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  1409. d$ or $v = s$.
  1410. \item If instruction $I_k$ is not a move but some other arithmetic
  1411. instruction such as (\key{add} $s$\, $d$), then add the edge $(d,v)$
  1412. for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  1413. \item If instruction $I_k$ is of the form (\key{call}
  1414. $\mathit{label}$), then add an edge $(r,v)$ for every caller-save
  1415. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  1416. \end{itemize}
  1417. Working from the top to bottom of Figure~\ref{fig:live-eg}, $z$
  1418. interferes with $x$, $y$ interferes with $z$, and $w$ interferes with
  1419. $y$ and $z$. The resulting interference graph is shown in
  1420. Figure~\ref{fig:interfere}.
  1421. \begin{figure}[tbp]
  1422. \large
  1423. \[
  1424. \xymatrix@=40pt{
  1425. v \ar@{-}[r] & w \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x \ar@{-}[dl]\\
  1426. & y \ar@{-}[r] & z
  1427. }
  1428. \]
  1429. \caption{Interference graph for the running example.}
  1430. \label{fig:interfere}
  1431. \end{figure}
  1432. \section{Graph Coloring via Sudoku}
  1433. We now come to the main event, mapping variables to registers (or to
  1434. stack locations in the event that we run out of registers). We need
  1435. to make sure not to map two variables to the same register if the two
  1436. variables interfere with each other. In terms of the interference
  1437. graph, this means we cannot map adjacent nodes to the same register.
  1438. If we think of registers as colors, the register allocation problem
  1439. becomes the widely-studied graph coloring
  1440. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  1441. The reader may be more familar with the graph coloring problem then he
  1442. or she realizes; the popular game of Sudoku is an instance of the
  1443. graph coloring problem. The following describes how to build a graph
  1444. out of a Sudoku board.
  1445. \begin{itemize}
  1446. \item There is one node in the graph for each Sudoku square.
  1447. \item There is an edge between two nodes if the corresponding squares
  1448. are in the same row or column, or if the squares are in the same
  1449. $3\times 3$ region.
  1450. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  1451. \item Based on the initial assignment of numbers to squares in the
  1452. Sudoku board, assign the corresponding colors to the corresponding
  1453. nodes in the graph.
  1454. \end{itemize}
  1455. If you can color the remaining nodes in the graph with the nine
  1456. colors, then you've also solved the corresponding game of Sudoku.
  1457. Given that Sudoku is graph coloring, one can use Sudoku strategies to
  1458. come up with an algorithm for allocating registers. For example, one
  1459. of the basic techniques for Sudoku is Pencil Marks. The idea is that
  1460. you use a process of elimination to determine what numbers still make
  1461. sense for a square, and write down those numbers in the square
  1462. (writing very small). At first, each number might be a
  1463. possibility, but as the board fills up, more and more of the
  1464. possibilities are crossed off (or erased). For example, if the number
  1465. $1$ is assigned to a square, then by process of elimination, you can
  1466. cross off the $1$ pencil mark from all the squares in the same row,
  1467. column, and region. Many Sudoku computer games provide automatic
  1468. support for Pencil Marks. This heuristic also reduces the degree of
  1469. branching in the search tree.
  1470. The Pencil Marks technique corresponds to the notion of color
  1471. \emph{saturation} due to \cite{Brelaz:1979eu}. The
  1472. saturation of a node, in Sudoku terms, is the number of possibilities
  1473. that have been crossed off using the process of elimination mentioned
  1474. above. In graph terminology, we have the following definition:
  1475. \begin{equation*}
  1476. \mathrm{saturation}(u) = |\{ c \;|\; \exists v. v \in \mathrm{Adj}(u)
  1477. \text{ and } \mathrm{color}(v) = c \}|
  1478. \end{equation*}
  1479. where $\mathrm{Adj}(u)$ is the set of nodes adjacent to $u$ and
  1480. the notation $|S|$ stands for the size of the set $S$.
  1481. Using the Pencil Marks technique leads to a simple strategy for
  1482. filling in numbers: if there is a square with only one possible number
  1483. left, then write down that number! But what if there are no squares
  1484. with only one possibility left? One brute-force approach is to just
  1485. make a guess. If that guess ultimately leads to a solution, great. If
  1486. not, backtrack to the guess and make a different guess. Of course,
  1487. this is horribly time consuming. One standard way to reduce the amount
  1488. of backtracking is to use the most-constrained-first heuristic. That
  1489. is, when making a guess, always choose a square with the fewest
  1490. possibilities left (the node with the highest saturation). The idea
  1491. is that choosing highly constrained squares earlier rather than later
  1492. is better because later there may not be any possibilities left.
  1493. In some sense, register allocation is easier than Sudoku because we
  1494. can always cheat and add more numbers by spilling variables to the
  1495. stack. Also, we'd like to minimize the time needed to color the graph,
  1496. and backtracking is expensive. Thus, it makes sense to keep the
  1497. most-constrained-first heuristic but drop the backtracking in favor of
  1498. greedy search (guess and just keep going).
  1499. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  1500. greedy algorithm for register allocation based on saturation and the
  1501. most-constrained-first heuristic, which is roughly equivalent to the
  1502. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as
  1503. saturation degree ordering
  1504. (SDO)~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in Sudoku,
  1505. the algorithm represents colors with integers, with the first $k$
  1506. colors corresponding to the $k$ registers in a given machine and the
  1507. rest of the integers corresponding to stack locations.
  1508. \begin{figure}[btp]
  1509. \centering
  1510. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  1511. Algorithm: DSATUR
  1512. Input: a graph @$G$@
  1513. Output: an assignment @$\mathrm{color}[v]$@ for each node @$v \in G$@
  1514. @$W \gets \mathit{vertices}(G)$@
  1515. while @$W \neq \emptyset$@ do
  1516. pick a node @$u$@ from @$W$@ with the highest saturation,
  1517. breaking ties randomly
  1518. find the lowest color @$c$@ that is not in @$\{ \mathrm{color}[v] \;|\; v \in \mathrm{Adj}(v)\}$@
  1519. @$\mathrm{color}[u] \gets c$@
  1520. @$W \gets W - \{u\}$@
  1521. \end{lstlisting}
  1522. \caption{Saturation-based greedy graph coloring algorithm.}
  1523. \label{fig:satur-algo}
  1524. \end{figure}
  1525. With this algorithm in hand, let us return to the running example and
  1526. consider how to color the interference graph in
  1527. Figure~\ref{fig:interfere}. Initially, all of the nodes are not yet
  1528. colored and they are unsaturated, so we annotate each of them with a
  1529. dash for their color and an empty set for the saturation.
  1530. \[
  1531. \xymatrix{
  1532. v:-,\{\} \ar@{-}[r] & w:-,\{\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:-,\{\} \ar@{-}[dl]\\
  1533. & y:-,\{\} \ar@{-}[r] & z:-,\{\}
  1534. }
  1535. \]
  1536. We select a maximally saturated node and color it $0$. In this case we
  1537. have a 5-way tie, so we arbitrarily pick $y$. The color $0$ is no
  1538. longer available for $w$, $x$, and $z$ because they interfere with
  1539. $y$.
  1540. \[
  1541. \xymatrix{
  1542. v:-,\{\} \ar@{-}[r] & w:-,\{0\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:-,\{0\} \ar@{-}[dl]\\
  1543. & y:0,\{\} \ar@{-}[r] & z:-,\{0\}
  1544. }
  1545. \]
  1546. Now we repeat the process, selecting another maximally saturated node.
  1547. This time there is a three-way tie between $w$, $x$, and $z$. We color
  1548. $w$ with $1$.
  1549. \[
  1550. \xymatrix{
  1551. v:-,\{1\} \ar@{-}[r] & w:1,\{0\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:-,\{0,1\} \ar@{-}[dl]\\
  1552. & y:0,\{1\} \ar@{-}[r] & z:-,\{0,1\}
  1553. }
  1554. \]
  1555. The most saturated nodes are now $x$ and $z$. We color $x$ with the
  1556. next avialable color which is $2$.
  1557. \[
  1558. \xymatrix{
  1559. v:-,\{1\} \ar@{-}[r] & w:1,\{0,2\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:2,\{0,1\} \ar@{-}[dl]\\
  1560. & y:0,\{1,2\} \ar@{-}[r] & z:-,\{0,1\}
  1561. }
  1562. \]
  1563. We have only two nodes left to color, $v$ and $z$, but $z$ is
  1564. more highly saturaded, so we color $z$ with $2$.
  1565. \[
  1566. \xymatrix{
  1567. v:-,\{1\} \ar@{-}[r] & w:1,\{0,2\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:2,\{0,1\} \ar@{-}[dl]\\
  1568. & y:0,\{1,2\} \ar@{-}[r] & z:2,\{0,1\}
  1569. }
  1570. \]
  1571. The last iteration of the coloring algorithm assigns color $0$ to $v$.
  1572. \[
  1573. \xymatrix{
  1574. v:0,\{1\} \ar@{-}[r] & w:1,\{0,2\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:2,\{0,1\} \ar@{-}[dl]\\
  1575. & y:0,\{1,2\} \ar@{-}[r] & z:2,\{0,1\}
  1576. }
  1577. \]
  1578. With the coloring complete, we can finalize assignment of variables to
  1579. registers and stack locations. Recall that if we have $k$ registers,
  1580. we map the first $k$ colors to registers and the rest to stack
  1581. lcoations. Suppose for the moment that we just have one extra register
  1582. to use for register allocation, just \key{rbx}. Then the following is
  1583. the mapping of colors to registers and stack allocations.
  1584. \[
  1585. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  1586. \]
  1587. Putting this together with the above coloring of the variables, we
  1588. arrive at the following assignment.
  1589. \[
  1590. \{ v \mapsto \key{\%rbx}, \;
  1591. w \mapsto \key{-8(\%rbp)}, \;
  1592. x \mapsto \key{-16(\%rbp)}, \;
  1593. y \mapsto \key{\%rbx}, \;
  1594. z\mapsto \key{-16(\%rbp)} \}
  1595. \]
  1596. Applying this assignment to our running example
  1597. (Figure~\ref{fig:reg-eg}) yields the following program.
  1598. % why frame size of 32? -JGS
  1599. \begin{lstlisting}
  1600. (program 32
  1601. (mov (int 1) (reg rbx))
  1602. (mov (int 46) (stack-loc -8))
  1603. (mov (reg rbx) (stack-loc -16))
  1604. (add (int 7) (stack-loc -16))
  1605. (mov (stack-loc 16) (reg rbx))
  1606. (add (int 4) (reg rbx))
  1607. (mov (stack-loc -16) (stack-loc -16))
  1608. (add (stack-loc -8) (stack-loc -16))
  1609. (mov (stack-loc -16) (reg rax))
  1610. (sub (reg rbx) (reg rax)))
  1611. \end{lstlisting}
  1612. This program is almost an x86 program. The remaining step is to apply
  1613. the patch instructions pass. In this example, the trivial move of
  1614. \key{-16(\%rbp)} to itself is deleted and the addition of
  1615. \key{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  1616. \key{\%rax}. The following shows the portion of the program that
  1617. changed.
  1618. \begin{lstlisting}
  1619. (add (int 4) (reg rbx))
  1620. (mov (stack-loc -8) (reg rax)
  1621. (add (reg rax) (stack-loc -16))
  1622. \end{lstlisting}
  1623. An overview of all of the passes involved in register allocation is
  1624. shown in Figure~\ref{fig:reg-alloc-passes}.
  1625. \begin{figure}[tbp]
  1626. \[
  1627. \xymatrix{
  1628. C_0 \ar@/^/[r]^-{\textsf{select\_instr.}}
  1629. & \text{x86}^{*} \ar[d]^-{\textsf{uncover\_live}} \\
  1630. & \text{x86}^{*} \ar[d]^-{\textsf{build\_interference}} \\
  1631. & \text{x86}^{*} \ar[d]_-{\textsf{allocate\_register}} \\
  1632. & \text{x86}^{*} \ar@/^/[r]^-{\textsf{patch\_instr.}}
  1633. & \text{x86}
  1634. }
  1635. \]
  1636. \caption{Diagram of the passes for register allocation.}
  1637. \label{fig:reg-alloc-passes}
  1638. \end{figure}
  1639. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1640. \chapter{Booleans, Type Checking, and Control Flow}
  1641. \label{ch:bool-types}
  1642. \section{The $S_1$ Language}
  1643. \begin{figure}[htbp]
  1644. \centering
  1645. \fbox{
  1646. \begin{minipage}{0.85\textwidth}
  1647. \[
  1648. \begin{array}{lcl}
  1649. \Op &::=& \ldots \mid \key{and} \mid \key{or} \mid \key{not} \mid \key{eq?} \\
  1650. \Exp &::=& \ldots \mid \key{\#t} \mid \key{\#f} \mid
  1651. \IF{\Exp}{\Exp}{\Exp}
  1652. \end{array}
  1653. \]
  1654. \end{minipage}
  1655. }
  1656. \caption{The $S_1$ language, an extension of $S_0$
  1657. (Figure~\ref{fig:s0-syntax}).}
  1658. \label{fig:s1-syntax}
  1659. \end{figure}
  1660. \section{Type Checking $S_1$ Programs}
  1661. % T ::= Integer | Boolean
  1662. It is common practice to specify a type system by writing rules for
  1663. each kind of AST node. For example, the rule for \key{if} is:
  1664. \begin{quote}
  1665. For any expressions $e_1, e_2, e_3$ and any type $T$, if $e_1$ has
  1666. type \key{bool}, $e_2$ has type $T$, and $e_3$ has type $T$, then
  1667. $\IF{e_1}{e_2}{e_3}$ has type $T$.
  1668. \end{quote}
  1669. It is also common practice to write rules using a horizontal line,
  1670. with the conditions written above the line and the conclusion written
  1671. below the line.
  1672. \begin{equation*}
  1673. \inference{e_1 \text{ has type } \key{bool} &
  1674. e_2 \text{ has type } T & e_3 \text{ has type } T}
  1675. {\IF{e_1}{e_2}{e_3} \text{ has type } T}
  1676. \end{equation*}
  1677. Because the phrase ``has type'' is repeated so often in these type
  1678. checking rules, it is abbreviated to just a colon. So the above rule
  1679. is abbreviated to the following.
  1680. \begin{equation*}
  1681. \inference{e_1 : \key{bool} & e_2 : T & e_3 : T}
  1682. {\IF{e_1}{e_2}{e_3} : T}
  1683. \end{equation*}
  1684. The $\LET{x}{e_1}{e_2}$ construct poses an interesting challenge. The
  1685. variable $x$ is assigned the value of $e_1$ and then $x$ can be used
  1686. inside $e_2$. When we get to an occurrence of $x$ inside $e_2$, how do
  1687. we know what type the variable should be? The answer is that we need
  1688. a way to map from variable names to types. Such a mapping is called a
  1689. \emph{type environment} (aka. \emph{symbol table}). The capital Greek
  1690. letter gamma, written $\Gamma$, is used for referring to type
  1691. environments environments. The notation $\Gamma, x : T$ stands for
  1692. making a copy of the environment $\Gamma$ and then associating $T$
  1693. with the variable $x$ in the new environment. We write $\Gamma(x)$ to
  1694. lookup the associated type for $x$. The type checking rules for
  1695. \key{let} and variables are as follows.
  1696. \begin{equation*}
  1697. \inference{e_1 : T_1 \text{ in } \Gamma &
  1698. e_2 : T_2 \text{ in } \Gamma,x:T_1}
  1699. {\LET{x}{e_1}{e_2} : T_2 \text{ in } \Gamma}
  1700. \qquad
  1701. \inference{\Gamma(x) = T}
  1702. {x : T \text{ in } \Gamma}
  1703. \end{equation*}
  1704. Type checking has roots in logic, and logicians have a tradition of
  1705. writing the environment on the left-hand side and separating it from
  1706. the expression with a turn-stile ($\vdash$). The turn-stile does not
  1707. have any intrinsic meaning per se. It is punctuation that separates
  1708. the environment $\Gamma$ from the expression $e$. So the above typing
  1709. rules are written as follows.
  1710. \begin{equation*}
  1711. \inference{\Gamma \vdash e_1 : T_1 &
  1712. \Gamma,x:T_1 \vdash e_2 : T_2}
  1713. {\Gamma \vdash \LET{x}{e_1}{e_2} : T_2}
  1714. \qquad
  1715. \inference{\Gamma(x) = T}
  1716. {\Gamma \vdash x : T}
  1717. \end{equation*}
  1718. Overall, the statement $\Gamma \vdash e : T$ is an example of what is
  1719. called a \emph{judgment}. In particular, this judgment says, ``In
  1720. environment $\Gamma$, expression $e$ has type $T$.''
  1721. Figure~\ref{fig:S1-type-system} shows the type checking rules for
  1722. $S_1$.
  1723. \begin{figure}
  1724. \begin{gather*}
  1725. \inference{\Gamma(x) = T}
  1726. {\Gamma \vdash x : T}
  1727. \qquad
  1728. \inference{\Gamma \vdash e_1 : T_1 &
  1729. \Gamma,x:T_1 \vdash e_2 : T_2}
  1730. {\Gamma \vdash \LET{x}{e_1}{e_2} : T_2}
  1731. \\[2ex]
  1732. \inference{}{\Gamma \vdash n : \key{Integer}}
  1733. \quad
  1734. \inference{\Gamma \vdash e_i : T_i \ ^{\forall i \in 1\ldots n} & \Delta(\Op,T_1,\ldots,T_n) = T}
  1735. {\Gamma \vdash (\Op \; e_1 \ldots e_n) : T}
  1736. \\[2ex]
  1737. \inference{}{\Gamma \vdash \key{\#t} : \key{Boolean}}
  1738. \quad
  1739. \inference{}{\Gamma \vdash \key{\#f} : \key{Boolean}}
  1740. \quad
  1741. \inference{\Gamma \vdash e_1 : \key{bool} \\
  1742. \Gamma \vdash e_2 : T &
  1743. \Gamma \vdash e_3 : T}
  1744. {\Gamma \vdash \IF{e_1}{e_2}{e_3} : T}
  1745. \end{gather*}
  1746. \caption{Type System for $S_1$.}
  1747. \label{fig:S1-type-system}
  1748. \end{figure}
  1749. \begin{figure}
  1750. \begin{align*}
  1751. \Delta(\key{+},\key{Integer},\key{Integer}) &= \key{Integer} \\
  1752. \Delta(\key{-},\key{Integer},\key{Integer}) &= \key{Integer} \\
  1753. \Delta(\key{-},\key{Integer}) &= \key{Integer} \\
  1754. \Delta(\key{*},\key{Integer},\key{Integer}) &= \key{Integer} \\
  1755. \Delta(\key{read}) &= \key{Integer} \\
  1756. \Delta(\key{and},\key{Boolean},\key{Boolean}) &= \key{Boolean} \\
  1757. \Delta(\key{or},\key{Boolean},\key{Boolean}) &= \key{Boolean} \\
  1758. \Delta(\key{not},\key{Boolean}) &= \key{Boolean} \\
  1759. \Delta(\key{eq?},\key{Integer},\key{Integer}) &= \key{Boolean} \\
  1760. \Delta(\key{eq?},\key{Boolean},\key{Boolean}) &= \key{Boolean}
  1761. \end{align*}
  1762. \caption{Types for the primitives operators.}
  1763. \end{figure}
  1764. \section{The $C_1$ Language}
  1765. \begin{figure}[htbp]
  1766. \[
  1767. \begin{array}{lcl}
  1768. \Arg &::=& \ldots \mid \key{\#t} \mid \key{\#f} \\
  1769. \Stmt &::=& \ldots \mid \IF{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  1770. \end{array}
  1771. \]
  1772. \caption{The $C_1$ intermediate language, an extension of $C_0$
  1773. (Figure~\ref{fig:c0-syntax}).}
  1774. \label{fig:c1-syntax}
  1775. \end{figure}
  1776. \section{Flatten Expressions}
  1777. \section{Select Instructions}
  1778. \section{Register Allocation}
  1779. \section{Patch Instructions}
  1780. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1781. \chapter{Tuples and Heap Allocation}
  1782. \label{ch:tuples}
  1783. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1784. \chapter{Garbage Collection}
  1785. \label{ch:gc}
  1786. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1787. \chapter{Functions}
  1788. \label{ch:functions}
  1789. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1790. \chapter{Lexically Scoped Functions}
  1791. \label{ch:lambdas}
  1792. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1793. \chapter{Mutable Data}
  1794. \label{ch:mutable-data}
  1795. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1796. \chapter{The Dynamic Type}
  1797. \label{ch:type-dynamic}
  1798. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1799. \chapter{Parametric Polymorphism}
  1800. \label{ch:parametric-polymorphism}
  1801. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1802. \chapter{High-level Optimization}
  1803. \label{ch:high-level-optimization}
  1804. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1805. \chapter{Appendix}
  1806. \section{Utility Functions}
  1807. \label{sec:utilities}
  1808. \begin{lstlisting}
  1809. (define assert
  1810. (lambda (msg b)
  1811. (if (not b)
  1812. (begin
  1813. (display "ERROR: ")
  1814. (display msg)
  1815. (newline))
  1816. (void))))
  1817. \end{lstlisting}
  1818. \bibliographystyle{plainnat}
  1819. \bibliography{all}
  1820. \end{document}
  1821. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita
  1822. %% LocalWords: Sarkar lcl Matz aa representable