book.tex 85 KB

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