book.tex 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  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. \lstset{%
  17. language=Lisp,
  18. basicstyle=\ttfamily\small,
  19. escapechar=@
  20. }
  21. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  22. % 'dedication' environment: To add a dedication paragraph at the start of book %
  23. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  24. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  25. \newenvironment{dedication}
  26. {
  27. \cleardoublepage
  28. \thispagestyle{empty}
  29. \vspace*{\stretch{1}}
  30. \hfill\begin{minipage}[t]{0.66\textwidth}
  31. \raggedright
  32. }
  33. {
  34. \end{minipage}
  35. \vspace*{\stretch{3}}
  36. \clearpage
  37. }
  38. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  39. % Chapter quote at the start of chapter %
  40. % Source: http://tex.stackexchange.com/a/53380 %
  41. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  42. \makeatletter
  43. \renewcommand{\@chapapp}{}% Not necessary...
  44. \newenvironment{chapquote}[2][2em]
  45. {\setlength{\@tempdima}{#1}%
  46. \def\chapquote@author{#2}%
  47. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  48. \itshape}
  49. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  50. \makeatother
  51. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  52. \newcommand{\itm}[1]{\ensuremath{\mathit{#1}}}
  53. \newcommand{\Stmt}{\itm{stmt}}
  54. \newcommand{\Exp}{\itm{exp}}
  55. \newcommand{\Instr}{\itm{instr}}
  56. \newcommand{\Prog}{\itm{prog}}
  57. \newcommand{\Arg}{\itm{arg}}
  58. \newcommand{\Int}{\itm{int}}
  59. \newcommand{\Var}{\itm{var}}
  60. \newcommand{\Op}{\itm{op}}
  61. \newcommand{\key}[1]{\texttt{#1}}
  62. \newcommand{\READ}{(\key{read})}
  63. \newcommand{\UNIOP}[2]{(\key{#1}\,#2)}
  64. \newcommand{\BINOP}[3]{(\key{#1}\,#2\,#3)}
  65. \newcommand{\LET}[3]{(\key{let}\,([#1\;#2])\,#3)}
  66. \newcommand{\ASSIGN}[2]{(\key{assign}\,#1\;#2)}
  67. \newcommand{\RETURN}[1]{(\key{return}\,#1)}
  68. \newcommand{\INT}[1]{(\key{int}\;#1)}
  69. \newcommand{\REG}[1]{(\key{reg}\;#1)}
  70. \newcommand{\VAR}[1]{(\key{var}\;#1)}
  71. \newcommand{\STACKLOC}[1]{(\key{stack}\;#1)}
  72. \newcommand{\IF}[3]{(\key{if}\,#1\;#2\;#3)}
  73. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  74. \title{\Huge \textbf{Essentials of Compilation} \\
  75. \huge An Incremental Approach}
  76. \author{\textsc{Jeremy G. Siek} \\
  77. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  78. Indiana University \\
  79. \\
  80. with contributions from: \\
  81. Carl Factora
  82. }
  83. \begin{document}
  84. \frontmatter
  85. \maketitle
  86. \begin{dedication}
  87. This book is dedicated to the programming language wonks at Indiana
  88. University.
  89. \end{dedication}
  90. \tableofcontents
  91. %\listoffigures
  92. %\listoftables
  93. \mainmatter
  94. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  95. \chapter*{Preface}
  96. Talk about nano-pass \citep{Sarkar:2004fk,Keep:2012aa} and incremental
  97. compilers \citep{Ghuloum:2006bh}.
  98. %\section*{Structure of book}
  99. % You might want to add short description about each chapter in this book.
  100. %\section*{About the companion website}
  101. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  102. %\begin{itemize}
  103. % \item A link to (freely downlodable) latest version of this document.
  104. % \item Link to download LaTeX source for this document.
  105. % \item Miscellaneous material (e.g. suggested readings etc).
  106. %\end{itemize}
  107. \section*{Acknowledgments}
  108. Need to give thanks to
  109. \begin{itemize}
  110. \item Kent Dybvig
  111. \item Daniel P. Friedman
  112. \item Abdulaziz Ghuloum
  113. \item Oscar Waddell
  114. \item Dipanwita Sarkar
  115. \item Ronald Garcia
  116. \item Bor-Yuh Evan Chang
  117. \end{itemize}
  118. %\mbox{}\\
  119. %\noindent Amber Jain \\
  120. %\noindent \url{http://amberj.devio.us/}
  121. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  122. \chapter{Abstract Syntax Trees and Recursion}
  123. \label{ch:trees-recur}
  124. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  125. \chapter{Integers and Variables}
  126. \label{ch:int-exp}
  127. %\begin{chapquote}{Author's name, \textit{Source of this quote}}
  128. %``This is a quote and I don't know who said this.''
  129. %\end{chapquote}
  130. \section{The $S_0$ Language}
  131. The $S_0$ language includes integers, operations on integers,
  132. (arithmetic and input), and variable definitions. The syntax of the
  133. $S_0$ language is defined by the grammar in
  134. Figure~\ref{fig:s0-syntax}. This language is rich enough to exhibit
  135. several compilation techniques but simple enough so that we can
  136. implement a compiler for it in two weeks of hard work. To give the
  137. reader a feeling for the scale of this first compiler, the instructor
  138. solution for the $S_0$ compiler consists of 6 recursive functions and
  139. a few small helper functions that together span 256 lines of code.
  140. \begin{figure}[htbp]
  141. \centering
  142. \fbox{
  143. \begin{minipage}{0.85\textwidth}
  144. \[
  145. \begin{array}{lcl}
  146. \Op &::=& \key{+} \mid \key{-} \mid \key{*} \mid \key{read} \\
  147. \Exp &::=& \Int \mid (\Op \; \Exp^{*}) \mid \Var \mid \LET{\Var}{\Exp}{\Exp}
  148. \end{array}
  149. \]
  150. \end{minipage}
  151. }
  152. \caption{The syntax of the $S_0$ language. The abbreviation \Op{} is
  153. short for operator, \Exp{} is short for expression, \Int{} for integer,
  154. and \Var{} for variable.}
  155. \label{fig:s0-syntax}
  156. \end{figure}
  157. The result of evaluating an expression is a value. For $S_0$, values
  158. are integers. To make it straightforward to map these integers onto
  159. x86-64 assembly~\citep{Matz:2013aa}, we restrict the integers to just
  160. those representable with 64-bits, the range $-2^{63}$ to $2^{63}$.
  161. We will walk through some examples of $S_0$ programs, commenting on
  162. aspects of the language that will be relevant to compiling it. We
  163. start with one of the simplest $S_0$ programs; it adds two integers.
  164. \[
  165. \BINOP{+}{10}{32}
  166. \]
  167. The result is $42$, as you might expected.
  168. %
  169. The next example demonstrates that expressions may be nested within
  170. each other, in this case nesting several additions and negations.
  171. \[
  172. \BINOP{+}{10}{ \UNIOP{-}{ \BINOP{+}{12}{20} } }
  173. \]
  174. What is the result of the above program?
  175. The \key{let} construct stores a value in a variable which can then be
  176. used within the body of the \key{let}. So the following program stores
  177. $32$ in $x$ and then computes $\BINOP{+}{10}{x}$, producing $42$.
  178. \[
  179. \LET{x}{ \BINOP{+}{12}{20} }{ \BINOP{+}{10}{x} }
  180. \]
  181. When there are multiple \key{let}'s for the same variable, the closest
  182. enclosing \key{let} is used. Consider the following program with two
  183. \key{let}'s that define variables named $x$.
  184. \[
  185. \LET{x}{32}{ \BINOP{+}{ \LET{x}{10}{x} }{ x } }
  186. \]
  187. For the purposes of showing which variable uses correspond to which
  188. definitions, the following shows the $x$'s annotated with subscripts
  189. to distinguish them.
  190. \[
  191. \LET{x_1}{32}{ \BINOP{+}{ \LET{x_2}{10}{x_2} }{ x_1 } }
  192. \]
  193. The \key{read} operation prompts the user of the program for an
  194. integer. Given an input of $10$, the following program produces $42$.
  195. \[
  196. \BINOP{+}{(\key{read})}{32}
  197. \]
  198. We include the \key{read} operation in $S_0$ to demonstrate that order
  199. of evaluation can make a different. Given the input $52$ then $10$,
  200. the following produces $42$ (and not $-42$).
  201. \[
  202. \LET{x}{\READ}{ \LET{y}{\READ}{ \BINOP{-}{x}{y} } }
  203. \]
  204. The initializing expression is always evaluated before the body of the
  205. \key{let}, so in the above, the \key{read} for $x$ is performed before
  206. the \key{read} for $y$.
  207. %
  208. The behavior of the following program is somewhat subtle because
  209. Scheme does not specify an evaluation order for arguments of an
  210. operator such as $-$.
  211. \[
  212. \BINOP{-}{\READ}{\READ}
  213. \]
  214. Given the input $42$ then $10$, the above program can result in either
  215. $42$ or $-42$, depending on the whims of the Scheme implementation.
  216. The goal for this chapter is to implement a compiler that translates
  217. any program $p \in S_0$ into a x86-64 assembly program $p'$ such that
  218. the assembly program exhibits the same behavior on an x86 computer as
  219. the $S_0$ program running in a Scheme implementation.
  220. \[
  221. \xymatrix{
  222. p \in S_0 \ar[rr]^{\text{compile}} \ar[drr]_{\text{run in Scheme}\quad} && p' \in \text{x86-64} \ar[d]^{\quad\text{run on an x86 machine}}\\
  223. & & n \in \mathbb{Z}
  224. }
  225. \]
  226. In the next section we introduce enough of the x86-64 assembly
  227. language to compile $S_0$.
  228. \section{The x86-64 Assembly Language}
  229. An x86-64 program is a sequence of instructions. The instructions
  230. manipulate 16 variables called \emph{registers} and can also load and
  231. store values into \emph{memory}. Memory is a mapping of 64-bit
  232. addresses to 64-bit values. The syntax $n(r)$ is used to read the
  233. address $a$ stored in register $r$ and then offset it by $n$ bytes (8
  234. bits), producing the address $a + n$. The arithmetic instructions,
  235. such as $\key{addq}\,s\,d$, read from the source $s$ and destination
  236. argument $d$, apply the arithmetic operation, then stores the result
  237. in the destination $d$. In this case, computing $d \gets d + s$. The
  238. move instruction, $\key{movq}\,s\,d$ reads from $s$ and stores the
  239. result in $d$. The $\key{callq}\,\mathit{label}$ instruction executes
  240. the procedure specified by the label, which we shall use to implement
  241. \key{read}. Figure~\ref{fig:x86-a} defines the syntax for this subset
  242. of the x86-64 assembly language.
  243. \begin{figure}[tbp]
  244. \fbox{
  245. \begin{minipage}{0.96\textwidth}
  246. \[
  247. \begin{array}{lcl}
  248. \itm{register} &::=& \key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  249. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  250. && \key{r8} \mid \key{r9} \mid \key{r10}
  251. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  252. \mid \key{r14} \mid \key{r15} \\
  253. \Arg &::=& \key{\$}\Int \mid \key{\%}\itm{register} \mid \Int(\key{\%}\itm{register}) \\
  254. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  255. \key{subq} \; \Arg, \Arg \mid
  256. \key{imulq} \; \Arg,\Arg \mid
  257. \key{negq} \; \Arg \mid \\
  258. && \key{movq} \; \Arg, \Arg \mid
  259. \key{callq} \; \mathit{label} \mid
  260. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \\
  261. \Prog &::= & \key{.globl \_main}\\
  262. & & \key{\_main:} \; \Instr^{+}
  263. \end{array}
  264. \]
  265. \end{minipage}
  266. }
  267. \caption{A subset of the x86-64 assembly language.}
  268. \label{fig:x86-a}
  269. \end{figure}
  270. Figure~\ref{fig:p0-x86} depicts an x86-64 program that is equivalent
  271. to $\BINOP{+}{10}{32}$. The \key{globl} directive says that the
  272. \key{\_main} procedure is externally visible, which is necessary so
  273. that the operating system can call it. The label \key{\_main:}
  274. indicates the beginning of the \key{\_main} procedure. The
  275. instruction $\key{movq}\,\$10, \%\key{rax}$ puts $10$ into the
  276. register \key{rax}. The following instruction $\key{addq}\,\key{\$}32,
  277. \key{\%rax}$ adds $32$ to the $10$ in \key{rax} and puts the result,
  278. $42$, back into \key{rax}. The instruction \key{retq} finishes the
  279. \key{\_main} function by returning the integer in the \key{rax}
  280. register to the operating system.
  281. \begin{figure}[htbp]
  282. \centering
  283. \begin{minipage}{0.6\textwidth}
  284. \begin{lstlisting}
  285. .globl _main
  286. _main:
  287. movq $10, %rax
  288. addq $32, %rax
  289. retq
  290. \end{lstlisting}
  291. \end{minipage}
  292. \caption{A simple x86-64 program equivalent to $\BINOP{+}{10}{32}$.}
  293. \label{fig:p0-x86}
  294. \end{figure}
  295. The next example exhibits the use of memory. Figure~\ref{fig:p1-x86}
  296. lists an x86-64 program that is equivalent to $\BINOP{+}{52}{
  297. \UNIOP{-}{10} }$. To understand how this x86-64 program uses memory,
  298. we need to explain a region of memory called called the
  299. \emph{procedure call stack} (\emph{stack} for short). The stack
  300. consists of a separate \emph{frame} for each procedure call. The
  301. memory layout for an individual frame is shown in
  302. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  303. \emph{stack pointer} and points to the item at the top of the
  304. stack. The stack grows downward in memory, so we increase the size of
  305. the stack by subtracting from the stack pointer. The frame size is
  306. required to be a multiple of 16 bytes. The register \key{rbp} is the
  307. \emph{base pointer} which serves two purposes: 1) it saves the
  308. location of the stack pointer for the procedure that called the
  309. current one and 2) it is used to access variables associated with the
  310. current procedure. We number the variables from $1$ to $n$. Variable
  311. $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$ at
  312. $-16\key{(\%rbp)}$, etc.
  313. \begin{figure}
  314. \centering
  315. \begin{minipage}{0.6\textwidth}
  316. \begin{lstlisting}
  317. .globl _main
  318. _main:
  319. pushq %rbp
  320. movq %rsp, %rbp
  321. subq $16, %rsp
  322. movq $10, -8(%rbp)
  323. negq -8(%rbp)
  324. movq $52, %rax
  325. addq -8(%rbp), %rax
  326. addq $16, %rsp
  327. popq %rbp
  328. retq
  329. \end{lstlisting}
  330. \end{minipage}
  331. \caption{An x86-64 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  332. \label{fig:p1-x86}
  333. \end{figure}
  334. \begin{figure}
  335. \centering
  336. \begin{tabular}{|r|l|} \hline
  337. Position & Contents \\ \hline
  338. 8(\key{\%rbp}) & return address \\
  339. 0(\key{\%rbp}) & old \key{rbp} \\
  340. -8(\key{\%rbp}) & variable $1$ \\
  341. -16(\key{\%rbp}) & variable $2$ \\
  342. \ldots & \ldots \\
  343. 0(\key{\%rsp}) & variable $n$\\ \hline
  344. \end{tabular}
  345. \caption{Memory layout of a frame.}
  346. \label{fig:frame}
  347. \end{figure}
  348. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  349. three instructions are the typical prelude for a procedure. The
  350. instruction \key{pushq \%rbp} saves the base pointer for the procedure
  351. that called the current one onto the stack and subtracts $8$ from the
  352. stack pointer. The second instruction \key{movq \%rsp, \%rbp} changes
  353. the base pointer to the top of the stack. The instruction \key{subq
  354. \$16, \%rsp} moves the stack pointer down to make enough room for
  355. storing variables. This program just needs one variable ($8$ bytes)
  356. but because the frame size is required to be a multiple of 16 bytes,
  357. it rounds to 16 bytes.
  358. The next four instructions carry out the work of computing
  359. $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction \key{movq \$10,
  360. -8(\%rbp)} stores $10$ in variable $1$. The instruction \key{negq
  361. -8(\%rbp)} changes variable $1$ to $-10$. The \key{movq \$52, \%rax}
  362. places $52$ in the register \key{rax} and \key{addq -8(\%rbp), \%rax}
  363. adds the contents of variable $1$ to \key{rax}, at which point
  364. \key{rax} contains $42$.
  365. The last three instructions are the typical \emph{conclusion} of a
  366. procedure. The \key{addq \$16, \%rsp} instruction moves the stack
  367. pointer back to point at the old base pointer. The amount added here
  368. needs to match the amount that was subtracted in the prelude of the
  369. procedure. Then \key{popq \%rbp} returns the old base pointer to
  370. \key{rbp} and adds $8$ to the stack pointer. The \key{retq}
  371. instruction jumps back to the procedure that called this one and
  372. subtracts 8 from the stack pointer.
  373. The compiler will need a convenient representation for manipulating
  374. x86 programs, so we define an abstract syntax for x86 in
  375. Figure~\ref{fig:x86-ast-a}. The \itm{info} field of the \key{program}
  376. AST node is for storing auxilliary information that needs to be
  377. communicated from one pass to the next. The function \key{print-x86}
  378. provided in the supplemental code converts an x86 abstract syntax tree
  379. into the text representation for x86 (Figure~\ref{fig:x86-a}).
  380. \begin{figure}[tbp]
  381. \fbox{
  382. \begin{minipage}{0.96\textwidth}
  383. \[
  384. \begin{array}{lcl}
  385. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  386. \mid \STACKLOC{\Int} \\
  387. \Instr &::=& (\key{add} \; \Arg\; \Arg) \mid
  388. (\key{sub} \; \Arg\; \Arg) \mid
  389. (\key{imul} \; \Arg\;\Arg) \mid
  390. (\key{neg} \; \Arg) \mid \\
  391. && (\key{mov} \; \Arg\; \Arg) \mid
  392. (\key{call} \; \mathit{label}) \mid
  393. (\key{push}\;\Arg) \mid (\key{pop}\;\Arg) \mid (\key{ret}) \\
  394. \Prog &::= & (\key{program} \;\itm{info} \; \Instr^{+})
  395. \end{array}
  396. \]
  397. \end{minipage}
  398. }
  399. \caption{Abstract syntax for x86-64 assembly.}
  400. \label{fig:x86-ast-a}
  401. \end{figure}
  402. \section{From $S_0$ to x86-64 through $C_0$}
  403. \label{sec:plan-s0-x86}
  404. To compile one language to another it helps to focus on the
  405. differences between the two languages. It is these differences that
  406. the compiler will need to bridge. What are the differences between
  407. $S_0$ and x86-64 assembly? Here we list some of the most important the
  408. differences.
  409. \begin{enumerate}
  410. \item x86-64 arithmetic instructions typically take two arguments and
  411. update the second argument in place. In contrast, $S_0$ arithmetic
  412. operations only read their arguments and produce a new value.
  413. \item An argument to an $S_0$ operator can be any expression, whereas
  414. x86-64 instructions restrict their arguments to integers, registers,
  415. and memory locations.
  416. \item An $S_0$ program can have any number of variables whereas x86-64
  417. has only 16 registers.
  418. \item Variables in $S_0$ can overshadow other variables with the same
  419. name. The registers and memory locations of x86-64 all have unique
  420. names.
  421. \end{enumerate}
  422. We ease the challenge of compiling from $S_0$ to x86 by breaking down
  423. the problem into several steps, dealing with the above differences one
  424. at a time. The main question then becomes: in what order to we tackle
  425. these differences? This is often one of the most challenging questions
  426. that a compiler writer must answer because some orderings may be much
  427. more difficult to implement than others. It is difficult to know ahead
  428. of time which orders will be better so often some trial-and-error is
  429. involved. However, we can try to plan ahead and choose the orderings
  430. based on what we find out.
  431. For example, to handle difference \#2 (nested expressions), we shall
  432. introduce new variables and pull apart the nested expressions into a
  433. sequence of assignment statements. To deal with difference \#3 we
  434. will be replacing variables with registers and/or stack
  435. locations. Thus, it makes sense to deal with \#2 before \#3 so that
  436. \#3 can replace both the original variables and the new ones. Next,
  437. consider where \#1 should fit in. Because it has to do with the format
  438. of x86 instructions, it makes more sense after we have flattened the
  439. nested expressions (\#2). Finally, when should we deal with \#4
  440. (variable overshadowing)? We shall be solving this problem by
  441. renaming variables to make sure they have unique names. Recall that
  442. our plan for \#2 involves moving nested expressions, which could be
  443. problematic if it changes the shadowing of variables. However, if we
  444. deal with \#4 first, then it will not be an issue. Thus, we arrive at
  445. the following ordering.
  446. \[
  447. \xymatrix{
  448. 4 \ar[r] & 2 \ar[r] & 1 \ar[r] & 3
  449. }
  450. \]
  451. We further simplify the translation from $S_0$ to x86 by identifying
  452. an intermediate language named $C_0$, roughly half-way between $S_0$
  453. and x86, to provide a rest stop along the way. The name $C_0$ comes
  454. from this language being vaguely similar to the $C$ language. The
  455. differences \#4 and \#1, regarding variables and nested expressions,
  456. are handled by the passes \textsf{uniquify} and \textsf{flatten} that
  457. bring us to $C_0$.
  458. \[\large
  459. \xymatrix@=50pt{
  460. S_0 \ar@/^/[r]^-{\textsf{uniquify}} &
  461. S_0 \ar@/^/[r]^-{\textsf{flatten}} &
  462. C_0
  463. }
  464. \]
  465. The syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}. The
  466. $C_0$ language supports the same operators as $S_0$ but the arguments
  467. of operators are now restricted to just variables and integers. The
  468. \key{let} construct of $S_0$ is replaced by an assignment statement
  469. and there is a \key{return} construct to specify the return value of
  470. the program. A program consists of a sequence of statements that
  471. include at least one \key{return} statement.
  472. \begin{figure}[htbp]
  473. \[
  474. \begin{array}{lcl}
  475. \Arg &::=& \Int \mid \Var \\
  476. \Exp &::=& \Arg \mid (\Op \; \Arg^{*})\\
  477. \Stmt &::=& \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} \\
  478. \Prog & ::= & (\key{program}\;\itm{info}\;\Stmt^{+})
  479. \end{array}
  480. \]
  481. \caption{The $C_0$ intermediate language.}
  482. \label{fig:c0-syntax}
  483. \end{figure}
  484. To get from $C_0$ to x86-64 assembly requires three more steps, which
  485. we discuss below.
  486. \[\large
  487. \xymatrix@=50pt{
  488. C_0 \ar@/^/[r]^-{\textsf{select\_instr.}}
  489. & \text{x86}^{*} \ar@/^/[r]^-{\textsf{assign\_homes}}
  490. & \text{x86}^{*} \ar@/^/[r]^-{\textsf{patch\_instr.}}
  491. & \text{x86}
  492. }
  493. \]
  494. We handle difference \#1, concerning the format of arithmetic
  495. instructions, in the \textsf{select\_instructions} pass. The result
  496. of this pass produces programs consisting of x86-64 instructions that
  497. use variables.
  498. %
  499. As there are only 16 registers, we cannot always map variables to
  500. registers (difference \#3). Fortunately, the stack can grow quite, so
  501. we can map variables to locations on the stack. This is handled in the
  502. \textsf{assign\_homes} pass. The topic of
  503. Chapter~\ref{ch:register-allocation} is implementing a smarter
  504. approach in which we make a best-effort to map variables to registers,
  505. resorting to the stack only when necessary.
  506. The final pass in our journey to x86 handles an indiosycracy of x86
  507. assembly. Many x86 instructions have two arguments but only one of the
  508. arguments may be a memory reference. Because we are mapping variables
  509. to stack locations, many of our generated instructions will violate
  510. this restriction. The purpose of the \textsf{patch\_instructions} pass
  511. is to fix this problem by replacing every bad instruction with a short
  512. sequence of instructions that use the \key{rax} register.
  513. \section{Uniquify Variables}
  514. The purpose of this pass is to make sure that each \key{let} uses a
  515. unique variable name. For example, the \textsf{uniquify} pass could
  516. translate
  517. \[
  518. \LET{x}{32}{ \BINOP{+}{ \LET{x}{10}{x} }{ x } }
  519. \]
  520. to
  521. \[
  522. \LET{x.1}{32}{ \BINOP{+}{ \LET{x.2}{10}{x.2} }{ x.1 } }
  523. \]
  524. We recommend implementing \textsf{uniquify} as a recursive function
  525. that mostly just copies the input program. However, when encountering
  526. a \key{let}, it should generate a unique name for the variable (the
  527. Racket function \key{gensym} is handy for this) and associate the old
  528. name with the new unique name in an association list. The
  529. \textsf{uniquify} function will need to access this association list
  530. when it gets to a variable reference, so we add another paramter to
  531. \textsf{uniquify} for the association list.
  532. \section{Flatten Expressions}
  533. The purpose of the \textsf{flatten} pass is to get rid of nested
  534. expressions, such as the $\UNIOP{-}{10}$ in the following program,
  535. without changing the behavior of the program.
  536. \[
  537. \BINOP{+}{52}{ \UNIOP{-}{10} }
  538. \]
  539. This can be accomplished by introducing a new variable, assigning the
  540. nested expression to the new variable, and then using the new variable
  541. in place of the nested expressions. For example, the above program is
  542. translated to the following one.
  543. \[
  544. \begin{array}{l}
  545. \ASSIGN{ \itm{x} }{ \UNIOP{-}{10} } \\
  546. \RETURN{ \BINOP{+}{52}{ \itm{x} } }
  547. \end{array}
  548. \]
  549. We recommend implementing \textsf{flatten} as a recursive function
  550. that returns two things, 1) the newly flattened expression, and 2) a
  551. list of assignment statements, one for each of the new variables
  552. introduced while flattening the expression.
  553. Take special care for programs such as the following that initialize
  554. variables with integers or other variables.
  555. \[
  556. \LET{a}{42}{ \LET{b}{a}{ b }}
  557. \]
  558. This program should be translated to
  559. \[
  560. \ASSIGN{a}{42} \;
  561. \ASSIGN{b}{a} \;
  562. \RETURN{b}
  563. \]
  564. and not the following, which could result from a naive implementation
  565. of \textsf{flatten}.
  566. \[
  567. \ASSIGN{x.1}{42}\;
  568. \ASSIGN{a}{x.1}\;
  569. \ASSIGN{x.2}{a}\;
  570. \ASSIGN{b}{x.2}\;
  571. \RETURN{b}
  572. \]
  573. \section{Select Instructions}
  574. In the \textsf{select\_instructions} pass we begin the work of
  575. translating from $C_0$ to x86. The target language of this pass is a
  576. pseudo-x86 language that still uses variables, so we add an AST node
  577. of the form $\VAR{\itm{var}}$. The \textsf{select\_instructions} pass
  578. deals with the differing format of arithmetic operations. For example,
  579. in $C_0$ an addition operation could take the following form:
  580. \[
  581. \ASSIGN{x}{ \BINOP{+}{10}{32} }
  582. \]
  583. To translate to x86, we need to express this addition using the
  584. \key{add} instruction that does an inplace update. So we first move
  585. $10$ to $x$ then perform the \key{add}.
  586. \[
  587. (\key{mov}\,\INT{10}\, \VAR{x})\; (\key{add} \;\INT{32}\; \VAR{x})
  588. \]
  589. There are some cases that require special care to avoid generating
  590. needlessly complicated code. If one of the arguments is the same as
  591. the left-hand side of the assignment, then there is no need for the
  592. extra move instruction. For example, the following
  593. \[
  594. \ASSIGN{x}{ \BINOP{+}{10}{x} }
  595. \quad\text{should translate to}\quad
  596. (\key{add} \; \INT{10}\; \VAR{x})
  597. \]
  598. Regarding the \RETURN{e} statement of $C_0$, we recommend treating it
  599. as an assignment to the \key{rax} register and let the procedure
  600. conclusion handle the transfer of control back to the calling
  601. procedure.
  602. \section{Assign Homes}
  603. As discussed in Section~\ref{sec:plan-s0-x86}, the
  604. \textsf{assign\_homes} pass places all of the variables on the stack.
  605. Consider again the example $S_0$ program $\BINOP{+}{52}{ \UNIOP{-}{10} }$,
  606. which after \textsf{select\_instructions} looks like the following.
  607. \[
  608. \begin{array}{l}
  609. (\key{mov}\;\INT{10}\; \VAR{x})\\
  610. (\key{neg}\; \VAR{x})\\
  611. (\key{mov}\; \INT{52}\; \REG{\itm{rax}})\\
  612. (\key{add}\; \VAR{x} \REG{\itm{rax}})
  613. \end{array}
  614. \]
  615. The one and only variable $x$ is assigned to stack location
  616. \key{-8(\%rbp)}, so the \textsf{assign\_homes} pass translates the
  617. above to
  618. \[
  619. \begin{array}{l}
  620. (\key{mov}\;\INT{10}\; \STACKLOC{{-}8})\\
  621. (\key{neg}\; \STACKLOC{{-}8})\\
  622. (\key{mov}\; \INT{52}\; \REG{\itm{rax}})\\
  623. (\key{add}\; \STACKLOC{{-}8}\; \REG{\itm{rax}})
  624. \end{array}
  625. \]
  626. In the process of assigning stack locations to variables, it is
  627. convenient to compute and store the size of the frame which will be
  628. needed later to generate the procedure conclusion.
  629. \section{Patch Instructions}
  630. The purpose of this pass is to make sure that each instruction adheres
  631. to the restrictions regarding which arguments can be memory
  632. references. For most instructions, the rule is that at most one
  633. argument may be a memory reference.
  634. Consider again the following example.
  635. \[
  636. \LET{a}{42}{ \LET{b}{a}{ b }}
  637. \]
  638. After \textsf{assign\_homes} pass, the above has been translated to
  639. \[
  640. \begin{array}{l}
  641. (\key{mov} \;\INT{42}\; \STACKLOC{{-}8})\\
  642. (\key{mov}\;\STACKLOC{{-}8}\; \STACKLOC{{-}16})\\
  643. (\key{mov}\;\STACKLOC{{-}16}\; \REG{\itm{rax}})
  644. \end{array}
  645. \]
  646. The second \key{mov} instruction is problematic because both arguments
  647. are stack locations. We suggest fixing this problem by moving from the
  648. source to \key{rax} and then from \key{rax} to the destination, as
  649. follows.
  650. \[
  651. \begin{array}{l}
  652. (\key{mov} \;\INT{42}\; \STACKLOC{{-}8})\\
  653. (\key{mov}\;\STACKLOC{{-}8}\; \REG{\itm{rax}})\\
  654. (\key{mov}\;\REG{\itm{rax}}\; \STACKLOC{{-}16})\\
  655. (\key{mov}\;\STACKLOC{{-}16}\; \REG{\itm{rax}})
  656. \end{array}
  657. \]
  658. The \key{imul} instruction is a special case because the destination
  659. argument must be a register.
  660. \section{Testing with Interpreters}
  661. The typical way to test a compiler is to run the generated assembly
  662. code on a diverse set of programs and check whether they behave as
  663. expected. However, when a compiler is structured as our is, with many
  664. passes, when there is an error in the generated assembly code it can
  665. be hard to determine which pass contains the source of the error. A
  666. good way to isolate the error is to not only test the generated
  667. assembly code but to also test the output of every pass. This requires
  668. having interpreters for all the intermediate languages. Indeed, the
  669. file \key{interp.rkt} in the supplemental code provides interpreters
  670. for all the intermediate languages described in this book, starting
  671. with interpreters for $S_0$, $C_0$, and x86 (in abstract syntax).
  672. The file \key{run-tests.rkt} automates the process of running the
  673. interpreters on the output programs of each pass and checking their
  674. result.
  675. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  676. \chapter{Register Allocation}
  677. \label{ch:register-allocation}
  678. In Chapter~\ref{ch:int-exp} we simplified the generation of x86
  679. assembly by placing all variables on the stack. We can improve the
  680. performance of the generated code considerably if we instead try to
  681. place as many variables as possible into registers. The CPU can
  682. access a register in a single cycle, whereas accessing the stack can
  683. take from several cycles (to go to cache) to hundreds of cycles (to go
  684. to main memory). Figure~\ref{fig:reg-eg} shows a program with four
  685. variables that serves as a running example. We show the source program
  686. and also the output of instruction selection. At that point the
  687. program is almost x86 assembly but not quite; it still contains
  688. variables instead of stack locations or registers.
  689. \begin{figure}
  690. \begin{minipage}{0.45\textwidth}
  691. Source program:
  692. \begin{lstlisting}
  693. (let ([v 1])
  694. (let ([w 46])
  695. (let ([x (+ v 7)])
  696. (let ([y (+ 4 x)])
  697. (let ([z (+ x w)])
  698. (- z y))))))
  699. \end{lstlisting}
  700. \end{minipage}
  701. \begin{minipage}{0.45\textwidth}
  702. After instruction selection:
  703. \begin{lstlisting}
  704. (program (v w x y z)
  705. (mov (int 1) (var v))
  706. (mov (int 46) (var w))
  707. (mov (var v) (var x))
  708. (add (int 7) (var x))
  709. (mov (var x) (var y))
  710. (add (int 4) (var y))
  711. (mov (var x) (var z))
  712. (add (var w) (var z))
  713. (mov (var z) (reg rax))
  714. (sub (var y) (reg rax)))
  715. \end{lstlisting}
  716. \end{minipage}
  717. \caption{Running example for this chapter.}
  718. \label{fig:reg-eg}
  719. \end{figure}
  720. The goal of register allocation is to fit as many variables into
  721. registers as possible. It is often the case that we have more
  722. variables than registers, so we can't naively map each variable to a
  723. register. Fortunately, it is also common for different variables to be
  724. needed during different periods of time, and in such cases the
  725. variables can be mapped to the same register. Consider variables $x$
  726. and $y$ in Figure~\ref{fig:reg-eg}. After the variable $x$ is moved
  727. to $z$ it is no longer needed. Variable $y$, on the other hand, is
  728. used only after this point, so $x$ and $y$ could share the same
  729. register. The topic of the next section is how we compute where a
  730. variable is needed.
  731. \section{Liveness Analysis}
  732. A variable is \emph{live} if the variable is used at some later point
  733. in the program and there is not an intervening assignment to the
  734. variable.
  735. %
  736. To understand the latter condition, consider the following code
  737. fragment in which there are two writes to $b$. Are $a$ and
  738. $b$ both live at the same time?
  739. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  740. (mov (int 5) (var a)) ; @$a \gets 5$@
  741. (mov (int 30) (var b)) ; @$b \gets 30$@
  742. (mov (var a) (var c)) ; @$c \gets x$@
  743. (mov (int 10) (var b)) ; @$b \gets 10$@
  744. (add (var b) (var c)) ; @$c \gets c + b$@
  745. \end{lstlisting}
  746. The answer is no because the value $30$ written to $b$ on line 2 is
  747. never used. The variable $b$ is read on line 5 and there is an
  748. intervening write to $b$ on line 4, so the read on line 5 receives the
  749. value written on line 4, not line 2.
  750. The live variables can be computed by traversing the instruction
  751. sequence back to front (i.e., backwards in execution order). Let
  752. $I_1,\ldots, I_n$ be the instruction sequence. We write
  753. $L_{\mathsf{after}}(k)$ for the set of live variables after
  754. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  755. variables before instruction $I_k$. The live variables after an
  756. instruction are always the same as the live variables before the next
  757. instruction.
  758. \begin{equation*}
  759. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  760. \end{equation*}
  761. To start things off, there are no live variables after the last
  762. instruction, so
  763. \begin{equation*}
  764. L_{\mathsf{after}}(n) = \emptyset
  765. \end{equation*}
  766. We then apply the following rule repeatedly, traversing the
  767. instruction sequence back to front.
  768. \begin{equation*}
  769. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  770. \end{equation*}
  771. where $W(k)$ are the variables written to by instruction $I_k$ and
  772. $R(k)$ are the variables read by instruction $I_k$.
  773. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  774. for the running example. Next to each instruction we write its
  775. $L_{\mathtt{after}}$ set.
  776. \begin{figure}[tbp]
  777. \begin{lstlisting}
  778. (program (v w x y z)
  779. (mov (int 1) (var v)) @$\{ v \}$@
  780. (mov (int 46) (var w)) @$\{ v, w \}$@
  781. (mov (var v) (var x)) @$\{ w, x \}$@
  782. (add (int 7) (var x)) @$\{ w, x \}$@
  783. (mov (var x) (var y)) @$\{ w, x, y\}$@
  784. (add (int 4) (var y)) @$\{ w, x, y \}$@
  785. (mov (var x) (var z)) @$\{ w, y, z \}$@
  786. (add (var w) (var z)) @$\{ y, z \}$@
  787. (mov (var z) (reg rax)) @$\{ y \}$@
  788. (sub (var y) (reg rax))) @$\{\}$@
  789. \end{lstlisting}
  790. \caption{Running example program annotated with live-after sets.}
  791. \label{fig:live-eg}
  792. \end{figure}
  793. \section{Building the Interference Graph}
  794. Based on the liveness analysis, we know the program regions where each
  795. variable is needed. However, during register allocation, we need to
  796. answer questions of the specific form: are variables $u$ and $v$ ever
  797. live at the same time? (And therefore cannot be assigned to the same
  798. register.) To make this question easier to answer, we create an
  799. explicit data structure, an \emph{interference graph}. An
  800. interference graph is an undirected graph that has an edge between two
  801. variables if they are live at the same time, that is, if they
  802. interfere with each other.
  803. The most obvious way to compute the interference graph is to look at
  804. the set of live variables between each statement in the program, and
  805. add an edge to the graph for every pair of variables in the same set.
  806. This approach is less than ideal for two reasons. First, it can be
  807. rather expensive because it takes $O(n^2)$ time to look at every pair
  808. in a set of $n$ live variables. Second, there is a special case in
  809. which two variables that are live at the same time do not actually
  810. interfere with each other: when they both contain the same value
  811. because we have assigned one to the other.
  812. A better way to compute the edges of the intereference graph is given
  813. by the following rules.
  814. \begin{itemize}
  815. \item If instruction $I_k$ is a move: (\key{mov} $s$\, $d$), then add
  816. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  817. d$ or $v = s$.
  818. \item If instruction $I_k$ is not a move but some other arithmetic
  819. instruction such as (\key{add} $s$\, $d$), then add the edge $(d,v)$
  820. for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  821. \item If instruction $I_k$ is of the form (\key{call}
  822. $\mathit{label}$), then add an edge $(r,v)$ for every caller-save
  823. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  824. \end{itemize}
  825. Working from the top to bottom of Figure~\ref{fig:live-eg}, $z$
  826. interferes with $x$, $y$ interferes with $z$, and $w$ interferes with
  827. $y$ and $z$. The resulting interference graph is shown in
  828. Figure~\ref{fig:interfere}.
  829. \begin{figure}[tbp]
  830. \large
  831. \[
  832. \xymatrix@=40pt{
  833. v \ar@{-}[r] & w \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x \ar@{-}[dl]\\
  834. & y \ar@{-}[r] & z
  835. }
  836. \]
  837. \caption{Interference graph for the running example.}
  838. \label{fig:interfere}
  839. \end{figure}
  840. \section{Graph Coloring via Sudoku}
  841. We now come to the main event, mapping variables to registers (or to
  842. stack locations in the event that we run out of registers). We need
  843. to make sure not to map two variables to the same register if the two
  844. variables interfere with each other. In terms of the interference
  845. graph, this means we cannot map adjacent nodes to the same register.
  846. If we think of registers as colors, the register allocation problem
  847. becomes the widely-studied graph coloring
  848. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  849. The reader may be more familar with the graph coloring problem then he
  850. or she realizes; the popular game of Sudoku is an instance of the
  851. graph coloring problem. The following describes how to build a graph
  852. out of a Sudoku board.
  853. \begin{itemize}
  854. \item There is one node in the graph for each Sudoku square.
  855. \item There is an edge between two nodes if the corresponding squares
  856. are in the same row or column, or if the squares are in the same
  857. $3\times 3$ region.
  858. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  859. \item Based on the initial assignment of numbers to squares in the
  860. Sudoku board, assign the corresponding colors to the corresponding
  861. nodes in the graph.
  862. \end{itemize}
  863. If you can color the remaining nodes in the graph with the nine
  864. colors, then you've also solved the corresponding game of Sudoku.
  865. Given that Sudoku is graph coloring, one can use Sudoku strategies to
  866. come up with an algorithm for allocating registers. For example, one
  867. of the basic techniques for Sudoku is Pencil Marks. The idea is that
  868. you use a process of elimination to determine what numbers still make
  869. sense for a square, and write down those numbers in the square
  870. (writing very small). At first, each number might be a
  871. possibility, but as the board fills up, more and more of the
  872. possibilities are crossed off (or erased). For example, if the number
  873. $1$ is assigned to a square, then by process of elimination, you can
  874. cross off the $1$ pencil mark from all the squares in the same row,
  875. column, and region. Many Sudoku computer games provide automatic
  876. support for Pencil Marks. This heuristic also reduces the degree of
  877. branching in the search tree.
  878. The Pencil Marks technique corresponds to the notion of color
  879. \emph{saturation} due to \cite{Brelaz:1979eu}. The
  880. saturation of a node, in Sudoku terms, is the number of possibilities
  881. that have been crossed off using the process of elimination mentioned
  882. above. In graph terminology, we have the following definition:
  883. \begin{equation*}
  884. \mathrm{saturation}(u) = |\{ c \;|\; \exists v. v \in \mathrm{Adj}(u)
  885. \text{ and } \mathrm{color}(v) = c \}|
  886. \end{equation*}
  887. where $\mathrm{Adj}(u)$ is the set of nodes adjacent to $u$ and
  888. the notation $|S|$ stands for the size of the set $S$.
  889. Using the Pencil Marks technique leads to a simple strategy for
  890. filling in numbers: if there is a square with only one possible number
  891. left, then write down that number! But what if there are no squares
  892. with only one possibility left? One brute-force approach is to just
  893. make a guess. If that guess ultimately leads to a solution, great. If
  894. not, backtrack to the guess and make a different guess. Of course,
  895. this is horribly time consuming. One standard way to reduce the amount
  896. of backtracking is to use the most-constrained-first heuristic. That
  897. is, when making a guess, always choose a square with the fewest
  898. possibilities left (the node with the highest saturation). The idea
  899. is that choosing highly constrained squares earlier rather than later
  900. is better because later there may not be any possibilities left.
  901. In some sense, register allocation is easier than Sudoku because we
  902. can always cheat and add more numbers by spilling variables to the
  903. stack. Also, we'd like to minimize the time needed to color the graph,
  904. and backtracking is expensive. Thus, it makes sense to keep the
  905. most-constrained-first heuristic but drop the backtracking in favor of
  906. greedy search (guess and just keep going).
  907. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  908. greedy algorithm for register allocation based on saturation and the
  909. most-constrained-first heuristic, which is roughly equivalent to the
  910. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as
  911. saturation degree ordering
  912. (SDO)~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in Sudoku,
  913. the algorithm represents colors with integers, with the first $k$
  914. colors corresponding to the $k$ registers in a given machine and the
  915. rest of the integers corresponding to stack locations.
  916. \begin{figure}[btp]
  917. \centering
  918. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  919. Algorithm: DSATUR
  920. Input: a graph @$G$@
  921. Output: an assignment @$\mathrm{color}[v]$@ for each node @$v \in G$@
  922. @$W \gets \mathit{vertices}(G)$@
  923. while @$W \neq \emptyset$@ do
  924. pick a node @$u$@ from @$W$@ with the highest saturation,
  925. breaking ties randomly
  926. find the lowest color @$c$@ that is not in @$\{ \mathrm{color}[v] \;|\; v \in \mathrm{Adj}(v)\}$@
  927. @$\mathrm{color}[u] \gets c$@
  928. @$W \gets W - \{u\}$@
  929. \end{lstlisting}
  930. \caption{Saturation-based greedy graph coloring algorithm.}
  931. \label{fig:satur-algo}
  932. \end{figure}
  933. With this algorithm in hand, let us return to the running example and
  934. consider how to color the interference graph in
  935. Figure~\ref{fig:interfere}. Initially, all of the nodes are not yet
  936. colored and they are unsaturated, so we annotate each of them with a
  937. dash for their color and an empty set for the saturation.
  938. \[
  939. \xymatrix{
  940. v:-,\{\} \ar@{-}[r] & w:-,\{\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:-,\{\} \ar@{-}[dl]\\
  941. & y:-,\{\} \ar@{-}[r] & z:-,\{\}
  942. }
  943. \]
  944. We select a maximally saturated node and color it $0$. In this case we
  945. have a 5-way tie, so we arbitrarily pick $y$. The color $0$ is no
  946. longer available for $w$, $x$, and $z$ because they interfere with
  947. $y$.
  948. \[
  949. \xymatrix{
  950. v:-,\{\} \ar@{-}[r] & w:-,\{0\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:-,\{0\} \ar@{-}[dl]\\
  951. & y:0,\{\} \ar@{-}[r] & z:-,\{0\}
  952. }
  953. \]
  954. Now we repeat the process, selecting another maximally saturated node.
  955. This time there is a three-way tie between $w$, $x$, and $z$. We color
  956. $w$ with $1$.
  957. \[
  958. \xymatrix{
  959. v:-,\{1\} \ar@{-}[r] & w:1,\{0\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:-,\{0,1\} \ar@{-}[dl]\\
  960. & y:0,\{1\} \ar@{-}[r] & z:-,\{0,1\}
  961. }
  962. \]
  963. The most saturated nodes are now $x$ and $z$. We color $x$ with the
  964. next avialable color which is $2$.
  965. \[
  966. \xymatrix{
  967. v:-,\{1\} \ar@{-}[r] & w:1,\{0,2\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:2,\{0,1\} \ar@{-}[dl]\\
  968. & y:0,\{1,2\} \ar@{-}[r] & z:-,\{0,1\}
  969. }
  970. \]
  971. We have only two nodes left to color, $v$ and $z$, but $z$ is
  972. more highly saturaded, so we color $z$ with $2$.
  973. \[
  974. \xymatrix{
  975. v:-,\{1\} \ar@{-}[r] & w:1,\{0,2\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:2,\{0,1\} \ar@{-}[dl]\\
  976. & y:0,\{1,2\} \ar@{-}[r] & z:2,\{0,1\}
  977. }
  978. \]
  979. The last iteration of the coloring algorithm assigns color $0$ to $v$.
  980. \[
  981. \xymatrix{
  982. v:0,\{1\} \ar@{-}[r] & w:1,\{0,2\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:2,\{0,1\} \ar@{-}[dl]\\
  983. & y:0,\{1,2\} \ar@{-}[r] & z:2,\{0,1\}
  984. }
  985. \]
  986. With the coloring complete, we can finalize assignment of variables to
  987. registers and stack locations. Recall that if we have $k$ registers,
  988. we map the first $k$ colors to registers and the rest to stack
  989. lcoations. Suppose for the moment that we just have one extra register
  990. to use for register allocation, just \key{rbx}. Then the following is
  991. the mapping of colors to registers and stack allocations.
  992. \[
  993. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  994. \]
  995. Putting this together with the above coloring of the variables, we
  996. arrive at the following assignment.
  997. \[
  998. \{ v \mapsto \key{\%rbx}, \;
  999. w \mapsto \key{-8(\%rbp)}, \;
  1000. x \mapsto \key{-16(\%rbp)}, \;
  1001. y \mapsto \key{\%rbx}, \;
  1002. z\mapsto \key{-16(\%rbp)} \}
  1003. \]
  1004. Applying this assignment to our running example
  1005. (Figure~\ref{fig:reg-eg}) yields the following program.
  1006. % why frame size of 32? -JGS
  1007. \begin{lstlisting}
  1008. (program 32
  1009. (mov (int 1) (reg rbx))
  1010. (mov (int 46) (stack-loc -8))
  1011. (mov (reg rbx) (stack-loc -16))
  1012. (add (int 7) (stack-loc -16))
  1013. (mov (stack-loc 16) (reg rbx))
  1014. (add (int 4) (reg rbx))
  1015. (mov (stack-loc -16) (stack-loc -16))
  1016. (add (stack-loc -8) (stack-loc -16))
  1017. (mov (stack-loc -16) (reg rax))
  1018. (sub (reg rbx) (reg rax)))
  1019. \end{lstlisting}
  1020. This program is almost an x86 program. The remaining step is to apply
  1021. the patch instructions pass. In this example, the trivial move of
  1022. \key{-16(\%rbp)} to itself is deleted and the addition of
  1023. \key{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  1024. \key{\%rax}. The following shows the portion of the program that
  1025. changed.
  1026. \begin{lstlisting}
  1027. (add (int 4) (reg rbx))
  1028. (mov (stack-loc -8) (reg rax)
  1029. (add (reg rax) (stack-loc -16))
  1030. \end{lstlisting}
  1031. An overview of all of the passes involved in register allocation is
  1032. shown in Figure~\ref{fig:reg-alloc-passes}.
  1033. \begin{figure}[tbp]
  1034. \[
  1035. \xymatrix{
  1036. C_0 \ar@/^/[r]^-{\textsf{select\_instr.}}
  1037. & \text{x86}^{*} \ar[d]^-{\textsf{uncover\_live}} \\
  1038. & \text{x86}^{*} \ar[d]^-{\textsf{build\_interference}} \\
  1039. & \text{x86}^{*} \ar[d]_-{\textsf{allocate\_register}} \\
  1040. & \text{x86}^{*} \ar@/^/[r]^-{\textsf{patch\_instr.}}
  1041. & \text{x86}
  1042. }
  1043. \]
  1044. \caption{Diagram of the passes for register allocation.}
  1045. \label{fig:reg-alloc-passes}
  1046. \end{figure}
  1047. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1048. \chapter{Booleans, Type Checking, and Control Flow}
  1049. \label{ch:bool-types}
  1050. \section{The $S_1$ Language}
  1051. \begin{figure}[htbp]
  1052. \centering
  1053. \fbox{
  1054. \begin{minipage}{0.85\textwidth}
  1055. \[
  1056. \begin{array}{lcl}
  1057. \Op &::=& \ldots \mid \key{and} \mid \key{or} \mid \key{not} \mid \key{eq?} \\
  1058. \Exp &::=& \ldots \mid \key{\#t} \mid \key{\#f} \mid
  1059. \IF{\Exp}{\Exp}{\Exp}
  1060. \end{array}
  1061. \]
  1062. \end{minipage}
  1063. }
  1064. \caption{The $S_1$ language, an extension of $S_0$
  1065. (Figure~\ref{fig:s0-syntax}).}
  1066. \label{fig:s1-syntax}
  1067. \end{figure}
  1068. \section{Type Checking $S_1$ Programs}
  1069. % T ::= Integer | Boolean
  1070. It is common practice to specify a type system by writing rules for
  1071. each kind of AST node. For example, the rule for \key{if} is:
  1072. \begin{quote}
  1073. For any expressions $e_1, e_2, e_3$ and any type $T$, if $e_1$ has
  1074. type \key{bool}, $e_2$ has type $T$, and $e_3$ has type $T$, then
  1075. $\IF{e_1}{e_2}{e_3}$ has type $T$.
  1076. \end{quote}
  1077. It is also common practice to write rules using a horizontal line,
  1078. with the conditions written above the line and the conclusion written
  1079. below the line.
  1080. \begin{equation*}
  1081. \inference{e_1 \text{ has type } \key{bool} &
  1082. e_2 \text{ has type } T & e_3 \text{ has type } T}
  1083. {\IF{e_1}{e_2}{e_3} \text{ has type } T}
  1084. \end{equation*}
  1085. Because the phrase ``has type'' is repeated so often in these type
  1086. checking rules, it is abbreviated to just a colon. So the above rule
  1087. is abbreviated to the following.
  1088. \begin{equation*}
  1089. \inference{e_1 : \key{bool} & e_2 : T & e_3 : T}
  1090. {\IF{e_1}{e_2}{e_3} : T}
  1091. \end{equation*}
  1092. The $\LET{x}{e_1}{e_2}$ construct poses an interesting challenge. The
  1093. variable $x$ is assigned the value of $e_1$ and then $x$ can be used
  1094. inside $e_2$. When we get to an occurrence of $x$ inside $e_2$, how do
  1095. we know what type the variable should be? The answer is that we need
  1096. a way to map from variable names to types. Such a mapping is called a
  1097. \emph{type environment} (aka. \emph{symbol table}). The capital Greek
  1098. letter gamma, written $\Gamma$, is used for referring to type
  1099. environments environments. The notation $\Gamma, x : T$ stands for
  1100. making a copy of the environment $\Gamma$ and then associating $T$
  1101. with the variable $x$ in the new environment. We write $\Gamma(x)$ to
  1102. lookup the associated type for $x$. The type checking rules for
  1103. \key{let} and variables are as follows.
  1104. \begin{equation*}
  1105. \inference{e_1 : T_1 \text{ in } \Gamma &
  1106. e_2 : T_2 \text{ in } \Gamma,x:T_1}
  1107. {\LET{x}{e_1}{e_2} : T_2 \text{ in } \Gamma}
  1108. \qquad
  1109. \inference{\Gamma(x) = T}
  1110. {x : T \text{ in } \Gamma}
  1111. \end{equation*}
  1112. Type checking has roots in logic, and logicians have a tradition of
  1113. writing the environment on the left-hand side and separating it from
  1114. the expression with a turn-stile ($\vdash$). The turn-stile does not
  1115. have any intrinsic meaning per se. It is punctuation that separates
  1116. the environment $\Gamma$ from the expression $e$. So the above typing
  1117. rules are written as follows.
  1118. \begin{equation*}
  1119. \inference{\Gamma \vdash e_1 : T_1 &
  1120. \Gamma,x:T_1 \vdash e_2 : T_2}
  1121. {\Gamma \vdash \LET{x}{e_1}{e_2} : T_2}
  1122. \qquad
  1123. \inference{\Gamma(x) = T}
  1124. {\Gamma \vdash x : T}
  1125. \end{equation*}
  1126. Overall, the statement $\Gamma \vdash e : T$ is an example of what is
  1127. called a \emph{judgment}. In particular, this judgment says, ``In
  1128. environment $\Gamma$, expression $e$ has type $T$.''
  1129. Figure~\ref{fig:S1-type-system} shows the type checking rules for
  1130. $S_1$.
  1131. \begin{figure}
  1132. \begin{gather*}
  1133. \inference{\Gamma(x) = T}
  1134. {\Gamma \vdash x : T}
  1135. \qquad
  1136. \inference{\Gamma \vdash e_1 : T_1 &
  1137. \Gamma,x:T_1 \vdash e_2 : T_2}
  1138. {\Gamma \vdash \LET{x}{e_1}{e_2} : T_2}
  1139. \\[2ex]
  1140. \inference{}{\Gamma \vdash n : \key{Integer}}
  1141. \quad
  1142. \inference{\Gamma \vdash e_i : T_i \ ^{\forall i \in 1\ldots n} & \Delta(\Op,T_1,\ldots,T_n) = T}
  1143. {\Gamma \vdash (\Op \; e_1 \ldots e_n) : T}
  1144. \\[2ex]
  1145. \inference{}{\Gamma \vdash \key{\#t} : \key{Boolean}}
  1146. \quad
  1147. \inference{}{\Gamma \vdash \key{\#f} : \key{Boolean}}
  1148. \quad
  1149. \inference{\Gamma \vdash e_1 : \key{bool} \\
  1150. \Gamma \vdash e_2 : T &
  1151. \Gamma \vdash e_3 : T}
  1152. {\Gamma \vdash \IF{e_1}{e_2}{e_3} : T}
  1153. \end{gather*}
  1154. \caption{Type System for $S_1$.}
  1155. \label{fig:S1-type-system}
  1156. \end{figure}
  1157. \begin{figure}
  1158. \begin{align*}
  1159. \Delta(\key{+},\key{Integer},\key{Integer}) &= \key{Integer} \\
  1160. \Delta(\key{-},\key{Integer},\key{Integer}) &= \key{Integer} \\
  1161. \Delta(\key{-},\key{Integer}) &= \key{Integer} \\
  1162. \Delta(\key{*},\key{Integer},\key{Integer}) &= \key{Integer} \\
  1163. \Delta(\key{read}) &= \key{Integer} \\
  1164. \Delta(\key{and},\key{Boolean},\key{Boolean}) &= \key{Boolean} \\
  1165. \Delta(\key{or},\key{Boolean},\key{Boolean}) &= \key{Boolean} \\
  1166. \Delta(\key{not},\key{Boolean}) &= \key{Boolean} \\
  1167. \Delta(\key{eq?},\key{Integer},\key{Integer}) &= \key{Boolean} \\
  1168. \Delta(\key{eq?},\key{Boolean},\key{Boolean}) &= \key{Boolean}
  1169. \end{align*}
  1170. \caption{Types for the primitives operators.}
  1171. \end{figure}
  1172. \section{The $C_1$ Language}
  1173. \begin{figure}[htbp]
  1174. \[
  1175. \begin{array}{lcl}
  1176. \Arg &::=& \ldots \mid \key{\#t} \mid \key{\#f} \\
  1177. \Stmt &::=& \ldots \mid \IF{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  1178. \end{array}
  1179. \]
  1180. \caption{The $C_1$ intermediate language, an extension of $C_0$
  1181. (Figure~\ref{fig:c0-syntax}).}
  1182. \label{fig:c1-syntax}
  1183. \end{figure}
  1184. \section{Flatten Expressions}
  1185. \section{Select Instructions}
  1186. \section{Register Allocation}
  1187. \section{Patch Instructions}
  1188. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1189. \chapter{Tuples and Heap Allocation}
  1190. \label{ch:tuples}
  1191. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1192. \chapter{Functions}
  1193. \label{ch:functions}
  1194. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1195. \chapter{Lexically Scoped Functions}
  1196. \label{ch:lambdas}
  1197. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1198. \chapter{Mutable Data}
  1199. \label{ch:mutable-data}
  1200. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1201. \chapter{The Dynamic Type}
  1202. \label{ch:type-dynamic}
  1203. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1204. \chapter{Parametric Polymorphism}
  1205. \label{ch:parametric-polymorphism}
  1206. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1207. \chapter{High-level Optimization}
  1208. \label{ch:high-level-optimization}
  1209. \bibliographystyle{plainnat}
  1210. \bibliography{all}
  1211. \end{document}
  1212. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita
  1213. %% LocalWords: Sarkar lcl Matz aa representable