book.tex 84 KB

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