book.tex 85 KB

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