book.tex 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379
  1. \documentclass[11pt]{book}
  2. \usepackage[T1]{fontenc}
  3. \usepackage[utf8]{inputenc}
  4. \usepackage{lmodern}
  5. \usepackage{hyperref}
  6. \usepackage{graphicx}
  7. \usepackage[english]{babel}
  8. \usepackage{listings}
  9. \usepackage{amsmath}
  10. \usepackage{amsthm}
  11. \usepackage{amssymb}
  12. \usepackage{natbib}
  13. \usepackage{stmaryrd}
  14. \usepackage{xypic}
  15. \usepackage{semantic}
  16. \usepackage{wrapfig}
  17. \usepackage{multirow}
  18. %% For pictures
  19. \usepackage{tikz}
  20. \usetikzlibrary{arrows.meta}
  21. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  22. % Computer Modern is already the default. -Jeremy
  23. %\renewcommand{\ttdefault}{cmtt}
  24. \lstset{%
  25. language=Lisp,
  26. basicstyle=\ttfamily\small,
  27. escapechar=|,
  28. columns=flexible
  29. }
  30. \newtheorem{theorem}{Theorem}
  31. \newtheorem{lemma}[theorem]{Lemma}
  32. \newtheorem{corollary}[theorem]{Corollary}
  33. \newtheorem{proposition}[theorem]{Proposition}
  34. \newtheorem{constraint}[theorem]{Constraint}
  35. \newtheorem{definition}[theorem]{Definition}
  36. \newtheorem{exercise}[theorem]{Exercise}
  37. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  38. % 'dedication' environment: To add a dedication paragraph at the start of book %
  39. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  40. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  41. \newenvironment{dedication}
  42. {
  43. \cleardoublepage
  44. \thispagestyle{empty}
  45. \vspace*{\stretch{1}}
  46. \hfill\begin{minipage}[t]{0.66\textwidth}
  47. \raggedright
  48. }
  49. {
  50. \end{minipage}
  51. \vspace*{\stretch{3}}
  52. \clearpage
  53. }
  54. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  55. % Chapter quote at the start of chapter %
  56. % Source: http://tex.stackexchange.com/a/53380 %
  57. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  58. \makeatletter
  59. \renewcommand{\@chapapp}{}% Not necessary...
  60. \newenvironment{chapquote}[2][2em]
  61. {\setlength{\@tempdima}{#1}%
  62. \def\chapquote@author{#2}%
  63. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  64. \itshape}
  65. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  66. \makeatother
  67. \input{defs}
  68. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  69. \title{\Huge \textbf{Essentials of Compilation} \\
  70. \huge An Incremental Approach}
  71. \author{\textsc{Jeremy G. Siek} \\
  72. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  73. Indiana University \\
  74. \\
  75. with contributions from: \\
  76. Carl Factora \\
  77. Cameron Swords
  78. }
  79. \begin{document}
  80. \frontmatter
  81. \maketitle
  82. \begin{dedication}
  83. This book is dedicated to the programming language wonks at Indiana
  84. University.
  85. \end{dedication}
  86. \tableofcontents
  87. %\listoffigures
  88. %\listoftables
  89. \mainmatter
  90. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  91. \chapter*{Preface}
  92. The tradition of compiler writing at Indiana University goes back to
  93. programming language research and courses taught by Daniel Friedman in
  94. the 1970's and 1980's. Dan had conducted research on lazy evaluation
  95. in the context of Lisp~\citep{McCarthy:1960dz} and then studied
  96. continuations and macros in the context of the
  97. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of students of
  98. those courses, Kent Dybvig, went on to build Chez
  99. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  100. compiler for Scheme. After completing his Ph.D. at the University of
  101. North Carolina, Kent returned to teach at Indiana University.
  102. Throughout the 1990's and early 2000's, Kent continued development of
  103. Chez Scheme and rotated with Dan in teaching the compiler course.
  104. Thanks to this collaboration between Dan and Kent, the compiler course
  105. evolved to incorporate novel pedagogical ideas while also including
  106. elements of effective real-world compilers. One of Dan's ideas was to
  107. split the compiler into many small passes over the input program and
  108. subsequent intermediate representations, so that the code for each
  109. pass would be easy to understood in isolation. (In contrast, most
  110. compilers of the time were organized into only a few monolithic passes
  111. for reasons of compile-time efficiency.) Kent and his students,
  112. Dipanwita Sarkar and Andrew Keep, developed infrastructure to support
  113. this approach and evolved the course, first to use micro-sized passes
  114. and then into even smaller nano
  115. passes~\citep{Sarkar:2004fk,Keep:2012aa}. I took this compiler course
  116. in the early 2000's, as part of my Ph.D. studies at Indiana
  117. University. Needless to say, I enjoyed the course immensely.
  118. One of my classmates, Abdulaziz Ghuloum, observed that the
  119. front-to-back organization of the course made it difficult for
  120. students to understand the rationale for the compiler
  121. design. Abdulaziz proposed an incremental approach in which the
  122. students build the compiler in stages; they start by implementing a
  123. complete compiler for a very small subset of the input language, then
  124. in each subsequent stage they add a feature to the input language and
  125. add or modify passes to handle the new feature~\citep{Ghuloum:2006bh}.
  126. In this way, the students see how the language features motivate
  127. aspects of the compiler design.
  128. After graduating from Indiana University in 2005, I went on to teach
  129. at the University of Colorado. I adapted the nano pass and incremental
  130. approaches to compiling a subset of the Python
  131. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  132. on the surface but there is a large overlap in the compiler techniques
  133. required for the two languages. Thus, I was able to teach much of the
  134. same content from the Indiana compiler course. I very much enjoyed
  135. teaching the course organized in this way, and even better, many of
  136. the students learned a lot and got excited about compilers. (No, I
  137. didn't do a quantitative study to support this claim.)
  138. It is now 2016 and I too have returned to teach at Indiana University.
  139. In my absence the compiler course had switched from the front-to-back
  140. organization to a back-to-front organization. Seeing how well the
  141. incremental approach worked at Colorado, I found this rather
  142. unsatisfactory and have proceeded to reorganize the course, porting
  143. and adapting the structure of the Colorado course back into the land
  144. of Scheme. Of course, in the meantime Scheme has been superseded by
  145. Racket (at least in Indiana), so the course is now about implementing,
  146. in Racket~\citep{plt-tr}, a subset of Racket.
  147. This is the textbook for the incremental version of the compiler
  148. course at Indiana University (Spring 2016) and it is the first
  149. textbook for an Indiana compiler course. With this book I hope to
  150. make the Indiana compiler course available to people that have not had
  151. the chance to study here in person. Many of the compiler design
  152. decisions in this book are drawn from the assignment descriptions of
  153. \cite{Dybvig:2010aa}. I have captured what I think are the most
  154. important topics from \cite{Dybvig:2010aa} but have omitted topics
  155. that I think are less interesting conceptually and I have made
  156. simplifications to reduce complexity. In this way, this book leans
  157. more towards pedagogy than towards absolute efficiency. Also, the book
  158. differs in places where I saw the opportunity to make the topics more
  159. fun, such as in relating register allocation to Sudoku
  160. (Chapter~\ref{ch:register-allocation}).
  161. \section*{Prerequisites}
  162. This material in this book is challenging but rewarding. It is meant
  163. to prepare students for a lifelong career in programming languages. I
  164. do not recommend this book for students who only want to dabble in
  165. programming languages. The book uses the Racket language both for the
  166. implementation of the compiler and for the language that is
  167. compiled. Thus, a student should be proficient with Racket (or Scheme)
  168. prior to reading this book. There are many other excellent resources
  169. for learning Racket and
  170. Scheme~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  171. is helpful but not necessary for the student to have prior exposure to
  172. x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  173. obtain from a computer systems
  174. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  175. parts of x86-64 assembly language that are needed.
  176. %\section*{Structure of book}
  177. % You might want to add short description about each chapter in this book.
  178. %\section*{About the companion website}
  179. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  180. %\begin{itemize}
  181. % \item A link to (freely downlodable) latest version of this document.
  182. % \item Link to download LaTeX source for this document.
  183. % \item Miscellaneous material (e.g. suggested readings etc).
  184. %\end{itemize}
  185. \section*{Acknowledgments}
  186. Need to give thanks to
  187. \begin{itemize}
  188. \item Bor-Yuh Evan Chang
  189. \item Kent Dybvig
  190. \item Daniel P. Friedman
  191. \item Ronald Garcia
  192. \item Abdulaziz Ghuloum
  193. \item Ryan Newton
  194. \item Dipanwita Sarkar
  195. \item Andrew Keep
  196. \item Oscar Waddell
  197. \end{itemize}
  198. \mbox{}\\
  199. \noindent Jeremy G. Siek \\
  200. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  201. \noindent Spring 2016
  202. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  203. \chapter{Preliminaries}
  204. \label{ch:trees-recur}
  205. In this chapter, we review the basic tools that are needed for
  206. implementing a compiler. We use abstract syntax trees (ASTs) in the
  207. form of S-expressions to represent programs (Section~\ref{sec:ast})
  208. and pattern matching to inspect individual nodes in an AST
  209. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  210. and deconstruct entire ASTs (Section~\ref{sec:recursion}).
  211. \section{Abstract Syntax Trees}
  212. \label{sec:ast}
  213. The primary data structure that is commonly used for representing
  214. programs is the \emph{abstract syntax tree} (AST). When considering
  215. some part of a program, a compiler needs to ask what kind of part it
  216. is and what sub-parts it has. For example, the program on the left is
  217. represented by the AST on the right.
  218. \begin{center}
  219. \begin{minipage}{0.4\textwidth}
  220. \begin{lstlisting}
  221. (+ (read) (- 8))
  222. \end{lstlisting}
  223. \end{minipage}
  224. \begin{minipage}{0.4\textwidth}
  225. \begin{equation}
  226. \begin{tikzpicture}
  227. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  228. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  229. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  230. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  231. \draw[->] (plus) to (read);
  232. \draw[->] (plus) to (minus);
  233. \draw[->] (minus) to (8);
  234. \end{tikzpicture}
  235. \label{eq:arith-prog}
  236. \end{equation}
  237. \end{minipage}
  238. \end{center}
  239. We shall use the standard terminology for trees: each circle above is
  240. called a \emph{node}. The arrows connect a node to its \emph{children}
  241. (which are also nodes). The top-most node is the \emph{root}. Every
  242. node except for the root has a \emph{parent} (the node it is the child
  243. of). If a node has no children, it is a \emph{leaf} node. Otherwise
  244. it is an \emph{internal} node.
  245. When deciding how to compile the above program, we need to know that
  246. the root node operation is addition and that it has two children:
  247. \texttt{read} and a negation. The abstract syntax tree data structure
  248. directly supports these queries and hence is a good choice. In this
  249. book, we will often write down the textual representation of a program
  250. even when we really have in mind the AST because the textual
  251. representation is more concise. We recommend that, in your mind, you
  252. always interpret programs as abstract syntax trees.
  253. \section{Grammars}
  254. \label{sec:grammar}
  255. A programming language can be thought of as a \emph{set} of programs.
  256. The set is typically infinite (one can always create larger and larger
  257. programs), so one cannot simply describe a language by listing all of
  258. the programs in the language. Instead we write down a set of rules, a
  259. \emph{grammar}, for building programs. We shall write our rules in a
  260. variant of Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  261. As an example, we describe a small language, named $R_0$, of
  262. integers and arithmetic operations. The first rule says that any
  263. integer is in the language:
  264. \begin{equation}
  265. R_0 ::= \Int \label{eq:arith-int}
  266. \end{equation}
  267. Each rule has a left-hand-side and a right-hand-side. The way to read
  268. a rule is that if you have all the program parts on the
  269. right-hand-side, then you can create and AST node and categorize it
  270. according to the left-hand-side. (We do not define $\Int$ because the
  271. reader already knows what an integer is.) We make the simplifying
  272. design decision that all of the languages in this book only handle
  273. machine-representable integers (those representable with 64-bits,
  274. i.e., the range $-2^{63}$ to $2^{63}$) which corresponds to the
  275. \texttt{fixnum} datatype in Racket. A name such as $R_0$ that is
  276. defined by the grammar rules is a \emph{non-terminal}.
  277. The second rule for the $R_0$ language is the \texttt{read}
  278. operation that receives an input integer from the user of the program.
  279. \begin{equation}
  280. R_0 ::= (\key{read}) \label{eq:arith-read}
  281. \end{equation}
  282. The third rule says that, given an $R_0$ node, you can build another
  283. $R_0$ node by negating it.
  284. \begin{equation}
  285. R_0 ::= (\key{-} \; R_0) \label{eq:arith-neg}
  286. \end{equation}
  287. Symbols such as \key{-} in typewriter font are \emph{terminal} symbols
  288. and must literally appear in the program for the rule to be
  289. applicable.
  290. We can apply the rules to build ASTs in the $R_0$
  291. language. For example, by rule \eqref{eq:arith-int}, \texttt{8} is an
  292. $R_0$, then by rule \eqref{eq:arith-neg}, the following AST is
  293. an $R_0$.
  294. \begin{center}
  295. \begin{minipage}{0.25\textwidth}
  296. \begin{lstlisting}
  297. (- 8)
  298. \end{lstlisting}
  299. \end{minipage}
  300. \begin{minipage}{0.25\textwidth}
  301. \begin{equation}
  302. \begin{tikzpicture}
  303. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  304. \node[draw, circle] (8) at (0, -1.2) {$8$};
  305. \draw[->] (minus) to (8);
  306. \end{tikzpicture}
  307. \label{eq:arith-neg8}
  308. \end{equation}
  309. \end{minipage}
  310. \end{center}
  311. The last rule for the $R_0$ language is for addition:
  312. \begin{equation}
  313. R_0 ::= (\key{+} \; R_0 \; R_0) \label{eq:arith-add}
  314. \end{equation}
  315. Now we can see that the AST \eqref{eq:arith-prog} is in $R_0$.
  316. We know that \lstinline{(read)} is in $R_0$ by rule
  317. \eqref{eq:arith-read} and we have shown that \texttt{(- 8)} is in
  318. $R_0$, so we can apply rule \eqref{eq:arith-add} to show that
  319. \texttt{(+ (read) (- 8))} is in the $R_0$ language.
  320. If you have an AST for which the above four rules do not apply, then
  321. the AST is not in $R_0$. For example, the AST \texttt{(-
  322. (read) (+ 8))} is not in $R_0$ because there are no rules
  323. for \key{+} with only one argument, nor for \key{-} with two
  324. arguments. Whenever we define a language with a grammar, we
  325. implicitly mean for the language to be the smallest set of programs
  326. that are justified by the rules. That is, the language only includes
  327. those programs that the rules allow.
  328. It is common to have many rules with the same left-hand side, so there
  329. is a vertical bar notation for gathering several rules, as shown in
  330. Figure~\ref{fig:r0-syntax}. Each clause between a vertical bar is
  331. called an ``alternative''.
  332. \begin{figure}[tbp]
  333. \fbox{
  334. \begin{minipage}{0.96\textwidth}
  335. \[
  336. R_0 ::= \Int \mid ({\tt \key{read}}) \mid (\key{-} \; R_0) \mid
  337. (\key{+} \; R_0 \; R_0)
  338. \]
  339. \end{minipage}
  340. }
  341. \caption{The syntax of the $R_0$ language.}
  342. \label{fig:r0-syntax}
  343. \end{figure}
  344. \section{S-Expressions}
  345. \label{sec:s-expr}
  346. Racket, as a descendant of Lisp, has
  347. convenient support for creating and manipulating abstract syntax trees
  348. with its \emph{symbolic expression} feature, or S-expression for
  349. short. We can create an S-expression simply by writing a backquote
  350. followed by the textual representation of the AST. (Technically
  351. speaking, this is called a \emph{quasiquote} in Racket.) For example,
  352. an S-expression to represent the AST \eqref{eq:arith-prog} is created
  353. by the following Racket expression:
  354. \begin{center}
  355. \texttt{`(+ (read) (- 8))}
  356. \end{center}
  357. To build larger S-expressions one often needs to splice together
  358. several smaller S-expressions. Racket provides the comma operator to
  359. splice an S-expression into a larger one. For example, instead of
  360. creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  361. we could have first created an S-expression for AST
  362. \eqref{eq:arith-neg8} and then spliced that into the addition
  363. S-expression.
  364. \begin{lstlisting}
  365. (define ast1.4 `(- 8))
  366. (define ast1.1 `(+ (read) ,ast1.4))
  367. \end{lstlisting}
  368. In general, the Racket expression that follows the comma (splice)
  369. can be any expression that computes an S-expression.
  370. \section{Pattern Matching}
  371. \label{sec:pattern-matching}
  372. As mentioned above, one of the operations that a compiler needs to
  373. perform on an AST is to access the children of a node. Racket
  374. provides the \texttt{match} form to access the parts of an
  375. S-expression. Consider the following example and the output on the
  376. right.
  377. \begin{center}
  378. \begin{minipage}{0.5\textwidth}
  379. \begin{lstlisting}
  380. (match ast1.1
  381. [`(,op ,child1 ,child2)
  382. (print op) (newline)
  383. (print child1) (newline)
  384. (print child2)])
  385. \end{lstlisting}
  386. \end{minipage}
  387. \vrule
  388. \begin{minipage}{0.25\textwidth}
  389. \begin{lstlisting}
  390. '+
  391. '(read)
  392. '(- 8)
  393. \end{lstlisting}
  394. \end{minipage}
  395. \end{center}
  396. The \texttt{match} form takes AST \eqref{eq:arith-prog} and binds its
  397. parts to the three variables \texttt{op}, \texttt{child1}, and
  398. \texttt{child2}. In general, a match clause consists of a
  399. \emph{pattern} and a \emph{body}. The pattern is a quoted S-expression
  400. that may contain pattern-variables (preceded by a comma). The body
  401. may contain any Racket code.
  402. A \texttt{match} form may contain several clauses, as in the following
  403. function \texttt{leaf?} that recognizes when an $R_0$ node is
  404. a leaf. The \texttt{match} proceeds through the clauses in order,
  405. checking whether the pattern can match the input S-expression. The
  406. body of the first clause that matches is executed. The output of
  407. \texttt{leaf?} for several S-expressions is shown on the right. In the
  408. below \texttt{match}, we see another form of pattern: the \texttt{(?
  409. fixnum?)} applies the predicate \texttt{fixnum?} to the input
  410. S-expression to see if it is a machine-representable integer.
  411. \begin{center}
  412. \begin{minipage}{0.5\textwidth}
  413. \begin{lstlisting}
  414. (define (leaf? arith)
  415. (match arith
  416. [(? fixnum?) #t]
  417. [`(read) #t]
  418. [`(- ,c1) #f]
  419. [`(+ ,c1 ,c2) #f]))
  420. (leaf? `(read))
  421. (leaf? `(- 8))
  422. (leaf? `(+ (read) (- 8)))
  423. \end{lstlisting}
  424. \end{minipage}
  425. \vrule
  426. \begin{minipage}{0.25\textwidth}
  427. \begin{lstlisting}
  428. #t
  429. #f
  430. #f
  431. \end{lstlisting}
  432. \end{minipage}
  433. \end{center}
  434. \section{Recursion}
  435. \label{sec:recursion}
  436. Programs are inherently recursive in that an $R_0$ AST is made
  437. up of smaller $R_0$ ASTs. Thus, the natural way to process in
  438. entire program is with a recursive function. As a first example of
  439. such a function, we define \texttt{arith?} below, which takes an
  440. arbitrary S-expression, {\tt sexp}, and determines whether or not {\tt
  441. sexp} is in {\tt arith}. Note that each match clause corresponds to
  442. one grammar rule for $R_0$ and the body of each clause makes a
  443. recursive call for each child node. This pattern of recursive function
  444. is so common that it has a name, \emph{structural recursion}. In
  445. general, when a recursive function is defined using a sequence of
  446. match clauses that correspond to a grammar, and each clause body makes
  447. a recursive call on each child node, then we say the function is
  448. defined by structural recursion.
  449. \begin{center}
  450. \begin{minipage}{0.7\textwidth}
  451. \begin{lstlisting}
  452. (define (arith? sexp)
  453. (match sexp
  454. [(? fixnum?) #t]
  455. [`(read) #t]
  456. [`(- ,e) (arith? e)]
  457. [`(+ ,e1 ,e2)
  458. (and (arith? e1) (arith? e2))]
  459. [else #f]))
  460. (arith? `(+ (read) (- 8)))
  461. (arith? `(- (read) (+ 8)))
  462. \end{lstlisting}
  463. \end{minipage}
  464. \vrule
  465. \begin{minipage}{0.25\textwidth}
  466. \begin{lstlisting}
  467. #t
  468. #f
  469. \end{lstlisting}
  470. \end{minipage}
  471. \end{center}
  472. \section{Interpreters}
  473. \label{sec:interp-R0}
  474. The meaning, or semantics, of a program is typically defined in the
  475. specification of the language. For example, the Scheme language is
  476. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  477. defined in its reference manual~\citep{plt-tr}. In this book we use an
  478. interpreter to define the meaning of each language that we consider,
  479. following Reynold's advice in this
  480. regard~\citep{reynolds72:_def_interp}. Here we will warm up by writing
  481. an interpreter for the $R_0$ language, which will also serve
  482. as a second example of structural recursion. The \texttt{interp-R0}
  483. function is defined in Figure~\ref{fig:interp-R0}. The body of the
  484. function is a match on the input expression \texttt{e} and there is
  485. one clause per grammar rule for $R_0$. The clauses for
  486. internal AST nodes make recursive calls to \texttt{interp-R0} on
  487. each child node.
  488. \begin{figure}[tbp]
  489. \begin{lstlisting}
  490. (define (interp-R0 e)
  491. (match e
  492. [(? fixnum?) e]
  493. [`(read)
  494. (define r (read))
  495. (cond [(fixnum? r) r]
  496. [else (error 'interp-R0 "expected an integer" r)])]
  497. [`(- ,e)
  498. (fx- 0 (interp-R0 e))]
  499. [`(+ ,e1 ,e2)
  500. (fx+ (interp-R0 e1) (interp-R0 e2))]
  501. ))
  502. \end{lstlisting}
  503. \caption{Interpreter for the $R_0$ language.}
  504. \label{fig:interp-R0}
  505. \end{figure}
  506. Let us consider the result of interpreting some example $R_0$
  507. programs. The following program simply adds two integers.
  508. \begin{lstlisting}
  509. (+ 10 32)
  510. \end{lstlisting}
  511. The result is \key{42}, as you might expected.
  512. %
  513. The next example demonstrates that expressions may be nested within
  514. each other, in this case nesting several additions and negations.
  515. \begin{lstlisting}
  516. (+ 10 (- (+ 12 20)))
  517. \end{lstlisting}
  518. What is the result of the above program?
  519. If we interpret the AST \eqref{eq:arith-prog} and give it the input
  520. \texttt{50}
  521. \begin{lstlisting}
  522. (interp-R0 ast1.1)
  523. \end{lstlisting}
  524. we get the answer to life, the universe, and everything:
  525. \begin{lstlisting}
  526. 42
  527. \end{lstlisting}
  528. Moving on, the \key{read} operation prompts the user of the program
  529. for an integer. Given an input of \key{10}, the following program
  530. produces \key{42}.
  531. \begin{lstlisting}
  532. (+ (read) 32)
  533. \end{lstlisting}
  534. We include the \key{read} operation in $R_1$ so that a compiler for
  535. $R_1$ cannot be implemented simply by running the interpreter at
  536. compilation time to obtain the output and then generating the trivial
  537. code to return the output. (A clever student at Colorado did this the
  538. first time I taught the course.)
  539. %% The behavior of the following program is somewhat subtle because
  540. %% Racket does not specify an evaluation order for arguments of an
  541. %% operator such as $-$.
  542. %% \marginpar{\scriptsize This is not true of Racket. \\ --Jeremy}
  543. %% \[
  544. %% \BINOP{+}{\READ}{\UNIOP{-}{\READ}}
  545. %% \]
  546. %% Given the input $42$ then $10$, the above program can result in either
  547. %% $42$ or $-42$, depending on the whims of the Racket implementation.
  548. The job of a compiler is to translate a program in one language into a
  549. program in another language so that the output program behaves the
  550. same way as the input program. This idea is depicted in the following
  551. diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  552. $\mathcal{L}_2$, and an interpreter for each language. Suppose that
  553. the compiler translates program $P_1$ in language $\mathcal{L}_1$ into
  554. program $P_2$ in language $\mathcal{L}_2$. Then interpreting $P_1$
  555. and $P_2$ on their respective interpreters with input $i$ should yield
  556. the same output $o$.
  557. \begin{equation} \label{eq:compile-correct}
  558. \begin{tikzpicture}[baseline=(current bounding box.center)]
  559. \node (p1) at (0, 0) {$P_1$};
  560. \node (p2) at (3, 0) {$P_2$};
  561. \node (o) at (3, -2.5) {$o$};
  562. \path[->] (p1) edge [above] node {compile} (p2);
  563. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  564. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  565. \end{tikzpicture}
  566. \end{equation}
  567. In the next section we see our first example of a compiler, which is
  568. another example of structural recursion.
  569. \section{Partial Evaluation}
  570. \label{sec:partial-evaluation}
  571. In this section we consider a compiler that translates $R_0$
  572. programs into $R_0$ programs that are more efficient, that is,
  573. this compiler is an optimizer. Our optimizer will accomplish this by
  574. trying to eagerly compute the parts of the program that do not depend
  575. on any inputs. For example, given the following program
  576. \begin{lstlisting}
  577. (+ (read) (- (+ 5 3)))
  578. \end{lstlisting}
  579. our compiler will translate it into the program
  580. \begin{lstlisting}
  581. (+ (read) -8)
  582. \end{lstlisting}
  583. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  584. evaluator for the $R_0$ language. The output of the partial
  585. evaluator is an $R_0$ program, which we build up using a
  586. combination of quasiquotes and commas. (Though no quasiquote is
  587. necessary for integers.) In Figure~\ref{fig:pe-arith}, the normal
  588. structural recursion is captured in the main \texttt{pe-arith}
  589. function whereas the code for partially evaluating negation and
  590. addition is factored out the into two separate helper functions:
  591. \texttt{pe-neg} and \texttt{pe-add}. The input to these helper
  592. functions is the output of partially evaluating the children nodes.
  593. \begin{figure}[tbp]
  594. \begin{lstlisting}
  595. (define (pe-neg r)
  596. (cond [(fixnum? r) (fx- 0 r)]
  597. [else `(- ,r)]))
  598. (define (pe-add r1 r2)
  599. (cond [(and (fixnum? r1) (fixnum? r2)) (fx+ r1 r2)]
  600. [else `(+ ,r1 ,r2)]))
  601. (define (pe-arith e)
  602. (match e
  603. [(? fixnum?) e]
  604. [`(read) `(read)]
  605. [`(- ,e1) (pe-neg (pe-arith e1))]
  606. [`(+ ,e1 ,e2) (pe-add (pe-arith e1) (pe-arith e2))]))
  607. \end{lstlisting}
  608. \caption{A partial evaluator for the $R_0$ language.}
  609. \label{fig:pe-arith}
  610. \end{figure}
  611. Our code for \texttt{pe-neg} and \texttt{pe-add} implements the simple
  612. idea of checking whether the inputs are integers and if they are, to
  613. go ahead perform the arithmetic. Otherwise, we use quasiquote to
  614. create an AST node for the appropriate operation (either negation or
  615. addition) and use comma to splice in the child nodes.
  616. To gain some confidence that the partial evaluator is correct, we can
  617. test whether it produces programs that get the same result as the
  618. input program. That is, we can test whether it satisfies Diagram
  619. \eqref{eq:compile-correct}. The following code runs the partial
  620. evaluator on several examples and tests the output program. The
  621. \texttt{assert} function is defined in Appendix~\ref{appendix:utilities}.
  622. \begin{lstlisting}
  623. (define (test-pe pe p)
  624. (assert "testing pe-arith"
  625. (equal? (interp-R0 p) (interp-R0 (pe-arith p)))))
  626. (test-pe `(+ (read) (- (+ 5 3))))
  627. (test-pe `(+ 1 (+ (read) 1)))
  628. (test-pe `(- (+ (read) (- 5))))
  629. \end{lstlisting}
  630. \begin{exercise}
  631. \normalfont % I don't like the italics for exercises. -Jeremy
  632. We challenge the reader to improve on the simple partial evaluator in
  633. Figure~\ref{fig:pe-arith} by replacing the \texttt{pe-neg} and
  634. \texttt{pe-add} helper functions with functions that know more about
  635. arithmetic. For example, your partial evaluator should translate
  636. \begin{lstlisting}
  637. (+ 1 (+ (read) 1))
  638. \end{lstlisting}
  639. into
  640. \begin{lstlisting}
  641. (+ 2 (read))
  642. \end{lstlisting}
  643. To accomplish this, we recommend that your partial evaluator produce
  644. output that takes the form of the $\itm{residual}$ non-terminal in the
  645. following grammar.
  646. \[
  647. \begin{array}{lcl}
  648. \Exp &::=& (\key{read}) \mid (\key{-} \;(\key{read})) \mid (\key{+} \; \Exp \; \Exp)\\
  649. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \Exp) \mid \Exp
  650. \end{array}
  651. \]
  652. \end{exercise}
  653. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  654. \chapter{Compiling Integers and Variables}
  655. \label{ch:int-exp}
  656. This chapter concerns the challenge of compiling a subset of Racket,
  657. which we name $R_1$, to x86-64 assembly code~\citep{Intel:2015aa}. The
  658. chapter begins with a description of the $R_1$ language
  659. (Section~\ref{sec:s0}) and then a description of x86-64
  660. (Section~\ref{sec:x86-64}). The x86-64 assembly language is quite
  661. large, so we only discuss what is needed for compiling $R_1$. We
  662. introduce more of x86-64 in later chapters. Once we have introduced
  663. $R_1$ and x86-64, we reflect on their differences and come up with a
  664. plan breaking down the translation from $R_1$ to x86-64 into a handful
  665. of steps (Section~\ref{sec:plan-s0-x86}). The rest of the sections in
  666. this Chapter give detailed hints regarding each step
  667. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  668. to give enough hints that the well-prepared reader can implement a
  669. compiler from $R_1$ to x86-64 while at the same time leaving room for
  670. some fun and creativity.
  671. \section{The $R_1$ Language}
  672. \label{sec:s0}
  673. The $R_1$ language extends the $R_0$ language
  674. (Figure~\ref{fig:r0-syntax}) with variable definitions. The syntax of
  675. the $R_1$ language is defined by the grammar in
  676. Figure~\ref{fig:r1-syntax}. As in $R_0$, \key{read} is a nullary
  677. operator, \key{-} is a unary operator, and \key{+} is a binary
  678. operator. In addition to variable definitions, the $R_1$ language
  679. includes the \key{program} form to mark the top of the program, which
  680. is helpful in some of the compiler passes. The $R_1$ language is rich
  681. enough to exhibit several compilation techniques but simple enough so
  682. that the reader can implement a compiler for it in a week of part-time
  683. work. To give the reader a feeling for the scale of this first
  684. compiler, the instructor solution for the $R_1$ compiler consists of 6
  685. recursive functions and a few small helper functions that together
  686. span 256 lines of code.
  687. \begin{figure}[btp]
  688. \centering
  689. \fbox{
  690. \begin{minipage}{0.96\textwidth}
  691. \[
  692. \begin{array}{rcl}
  693. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  694. R_1 &::=& (\key{program} \; \Exp)
  695. \end{array}
  696. \]
  697. \end{minipage}
  698. }
  699. \caption{The syntax of the $R_1$ language.
  700. The non-terminal \Var{} may be any Racket identifier.}
  701. \label{fig:r1-syntax}
  702. \end{figure}
  703. The \key{let} construct defines a variable for use within its body
  704. and initializes the variable with the value of an expression. So the
  705. following program initializes \code{x} to \code{32} and then evaluates
  706. the body \code{(+ 10 x)}, producing \code{42}.
  707. \begin{lstlisting}
  708. (program
  709. (let ([x (+ 12 20)]) (+ 10 x)))
  710. \end{lstlisting}
  711. When there are multiple \key{let}'s for the same variable, the closest
  712. enclosing \key{let} is used. That is, variable definitions overshadow
  713. prior definitions. Consider the following program with two \key{let}'s
  714. that define variables named \code{x}. Can you figure out the result?
  715. \begin{lstlisting}
  716. (program
  717. (let ([x 32]) (+ (let ([x 10]) x) x)))
  718. \end{lstlisting}
  719. For the purposes of showing which variable uses correspond to which
  720. definitions, the following shows the \code{x}'s annotated with subscripts
  721. to distinguish them. Double check that your answer for the above is
  722. the same as your answer for this annotated version of the program.
  723. \begin{lstlisting}
  724. (program
  725. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|)))
  726. \end{lstlisting}
  727. The initializing expression is always evaluated before the body of the
  728. \key{let}, so in the following, the \key{read} for \code{x} is
  729. performed before the \key{read} for \code{y}. Given the input
  730. \code{52} then \code{10}, the following produces \code{42} (and not
  731. \code{-42}).
  732. \begin{lstlisting}
  733. (program
  734. (let ([x (read)]) (let ([y (read)]) (- x y))))
  735. \end{lstlisting}
  736. Figure~\ref{fig:interp-R1} shows the interpreter for the $R_1$
  737. language. It extends the interpreter for $R_0$ with two new
  738. \key{match} clauses for variables and for \key{let}. For \key{let},
  739. we will need a way to communicate the initializing value of a variable
  740. to all the uses of a variable. To accomplish this, we maintain a
  741. mapping from variables to values, which is traditionally called an
  742. \emph{environment}. For simplicity, here we use an association list to
  743. represent the environment. The \code{interp-R1} function takes the
  744. current environment, \code{env}, as an extra parameter. When the
  745. interpreter encounters a variable, it finds the corresponding value
  746. using the \code{lookup} function (Appendix~\ref{appendix:utilities}).
  747. When the interpreter encounters a \key{let}, it evaluates the
  748. initializing expression, extends the environment with the result bound
  749. to the variable, then evaluates the body of the \key{let}.
  750. \begin{figure}[tbp]
  751. \begin{lstlisting}
  752. (define (interp-R1 env e)
  753. (match e
  754. [(? symbol?) (lookup e env)]
  755. [`(let ([,x ,e]) ,body)
  756. (define v (interp-R1 env e))
  757. (define new-env (cons (cons x v) env))
  758. (interp-R1 new-env body)]
  759. [(? fixnum?) e]
  760. [`(read)
  761. (define r (read))
  762. (cond [(fixnum? r) r]
  763. [else (error 'interp-R1 "expected an integer" r)])]
  764. [`(- ,e)
  765. (fx- 0 (interp-R1 env e))]
  766. [`(+ ,e1 ,e2)
  767. (fx+ (interp-R1 env e1) (interp-R1 env e2))]
  768. [`(program ,e) (interp-R1 '() e)]
  769. ))
  770. \end{lstlisting}
  771. \caption{Interpreter for the $R_1$ language.}
  772. \label{fig:interp-R1}
  773. \end{figure}
  774. The goal for this chapter is to implement a compiler that translates
  775. any program $P_1$ in the $R_1$ language into an x86-64 assembly
  776. program $P_2$ such that $P_2$ exhibits the same behavior on an x86
  777. computer as the $R_1$ program running in a Racket implementation.
  778. That is, they both output the same integer $n$.
  779. \[
  780. \begin{tikzpicture}[baseline=(current bounding box.center)]
  781. \node (p1) at (0, 0) {$P_1$};
  782. \node (p2) at (4, 0) {$P_2$};
  783. \node (o) at (4, -2) {$n$};
  784. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  785. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  786. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  787. \end{tikzpicture}
  788. \]
  789. In the next section we introduce enough of the x86-64 assembly
  790. language to compile $R_1$.
  791. \section{The x86-64 Assembly Language}
  792. \label{sec:x86-64}
  793. An x86-64 program is a sequence of instructions. The instructions may
  794. refer to integer constants (called \emph{immediate values}), variables
  795. called \emph{registers}, and instructions may load and store values
  796. into \emph{memory}. Memory is a mapping of 64-bit addresses to 64-bit
  797. values. Figure~\ref{fig:x86-a} defines the syntax for the subset of
  798. the x86-64 assembly language needed for this chapter. (We use the
  799. AT\&T syntax expected by the GNU assembler inside \key{gcc}.)
  800. An immediate value is written using the notation \key{\$}$n$ where $n$
  801. is an integer.
  802. %
  803. A register is written with a \key{\%} followed by the register name,
  804. such as \key{\%rax}.
  805. %
  806. An access to memory is specified using the syntax $n(\key{\%}r)$,
  807. which reads register $r$ and then offsets the address by $n$ bytes (8
  808. bits). The address is then used to either load or store to memory
  809. depending on whether it occurs as a source or destination argument of
  810. an instruction.
  811. An arithmetic instruction, such as $\key{addq}\,s,\,d$, reads from the
  812. source $s$ and destination $d$, applies the arithmetic operation, then
  813. write the result in $d$.
  814. %
  815. The move instruction, $\key{movq}\,s\,d$ reads from $s$ and stores the
  816. result in $d$.
  817. %
  818. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  819. specified by the label.
  820. \begin{figure}[tbp]
  821. \fbox{
  822. \begin{minipage}{0.96\textwidth}
  823. \[
  824. \begin{array}{lcl}
  825. \Reg &::=& \key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  826. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  827. && \key{r8} \mid \key{r9} \mid \key{r10}
  828. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  829. \mid \key{r14} \mid \key{r15} \\
  830. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int(\key{\%}\Reg) \\
  831. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  832. \key{subq} \; \Arg, \Arg \mid
  833. % \key{imulq} \; \Arg,\Arg \mid
  834. \key{negq} \; \Arg \mid \key{movq} \; \Arg, \Arg \mid \\
  835. && \key{callq} \; \mathit{label} \mid
  836. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \\
  837. \Prog &::= & \key{.globl \_main}\\
  838. & & \key{\_main:} \; \Instr^{+}
  839. \end{array}
  840. \]
  841. \end{minipage}
  842. }
  843. \caption{A subset of the x86-64 assembly language (AT\&T syntax).}
  844. \label{fig:x86-a}
  845. \end{figure}
  846. \begin{wrapfigure}{r}{2.25in}
  847. \begin{lstlisting}
  848. .globl _main
  849. _main:
  850. movq $10, %rax
  851. addq $32, %rax
  852. retq
  853. \end{lstlisting}
  854. \caption{An x86-64 program equivalent to $\BINOP{+}{10}{32}$.}
  855. \label{fig:p0-x86}
  856. \end{wrapfigure}
  857. Figure~\ref{fig:p0-x86} depicts an x86-64 program that is equivalent
  858. to \code{(+ 10 32)}. The \key{globl} directive says that the
  859. \key{\_main} procedure is externally visible, which is necessary so
  860. that the operating system can call it. The label \key{\_main:}
  861. indicates the beginning of the \key{\_main} procedure which is where
  862. the operating system starting executing this program. The instruction
  863. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  864. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  865. $10$ in \key{rax} and puts the result, $42$, back into
  866. \key{rax}. The instruction \key{retq} finishes the \key{\_main}
  867. function by returning the integer in \key{rax} to the
  868. operating system.
  869. \begin{wrapfigure}{r}{2.25in}
  870. \begin{lstlisting}
  871. .globl _main
  872. _main:
  873. pushq %rbp
  874. movq %rsp, %rbp
  875. subq $16, %rsp
  876. movq $10, -8(%rbp)
  877. negq -8(%rbp)
  878. movq $52, %rax
  879. addq -8(%rbp), %rax
  880. addq $16, %rsp
  881. popq %rbp
  882. retq
  883. \end{lstlisting}
  884. \caption{An x86-64 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  885. \label{fig:p1-x86}
  886. \end{wrapfigure}
  887. The next example exhibits the use of memory. Figure~\ref{fig:p1-x86}
  888. lists an x86-64 program that is equivalent to $\BINOP{+}{52}{
  889. \UNIOP{-}{10} }$. To understand how this x86-64 program works, we
  890. need to explain a region of memory called called the \emph{procedure
  891. call stack} (or \emph{stack} for short). The stack consists of a
  892. separate \emph{frame} for each procedure call. The memory layout for
  893. an individual frame is shown in Figure~\ref{fig:frame}. The register
  894. \key{rsp} is called the \emph{stack pointer} and points to the item at
  895. the top of the stack. The stack grows downward in memory, so we
  896. increase the size of the stack by subtracting from the stack
  897. pointer. The frame size is required to be a multiple of 16 bytes. The
  898. register \key{rbp} is the \emph{base pointer} which serves two
  899. purposes: 1) it saves the location of the stack pointer for the
  900. procedure that called the current one and 2) it is used to access
  901. variables associated with the current procedure. We number the
  902. variables from $1$ to $n$. Variable $1$ is stored at address
  903. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  904. \begin{figure}[tbp]
  905. \centering
  906. \begin{tabular}{|r|l|} \hline
  907. Position & Contents \\ \hline
  908. 8(\key{\%rbp}) & return address \\
  909. 0(\key{\%rbp}) & old \key{rbp} \\
  910. -8(\key{\%rbp}) & variable $1$ \\
  911. -16(\key{\%rbp}) & variable $2$ \\
  912. \ldots & \ldots \\
  913. 0(\key{\%rsp}) & variable $n$\\ \hline
  914. \end{tabular}
  915. \caption{Memory layout of a frame.}
  916. \label{fig:frame}
  917. \end{figure}
  918. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  919. three instructions are the typical prelude for a procedure. The
  920. instruction \key{pushq \%rbp} saves the base pointer for the procedure
  921. that called the current one onto the stack and subtracts $8$ from the
  922. stack pointer. The second instruction \key{movq \%rsp, \%rbp} changes
  923. the base pointer to the top of the stack. The instruction \key{subq
  924. \$16, \%rsp} moves the stack pointer down to make enough room for
  925. storing variables. This program just needs one variable ($8$ bytes)
  926. but because the frame size is required to be a multiple of 16 bytes,
  927. it rounds to 16 bytes.
  928. The next four instructions carry out the work of computing
  929. $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction \key{movq \$10,
  930. -8(\%rbp)} stores $10$ in variable $1$. The instruction \key{negq
  931. -8(\%rbp)} changes variable $1$ to $-10$. The \key{movq \$52, \%rax}
  932. places $52$ in the register \key{rax} and \key{addq -8(\%rbp), \%rax}
  933. adds the contents of variable $1$ to \key{rax}, at which point
  934. \key{rax} contains $42$.
  935. The last three instructions are the typical \emph{conclusion} of a
  936. procedure. These instructions are necessary to get the state of the
  937. machine back to where it was before the current procedure was called.
  938. The \key{addq \$16, \%rsp} instruction moves the stack pointer back to
  939. point at the old base pointer. The amount added here needs to match
  940. the amount that was subtracted in the prelude of the procedure. Then
  941. \key{popq \%rbp} returns the old base pointer to \key{rbp} and adds
  942. $8$ to the stack pointer. The \key{retq} instruction jumps back to
  943. the procedure that called this one and subtracts 8 from the stack
  944. pointer.
  945. The compiler will need a convenient representation for manipulating
  946. x86 programs, so we define an abstract syntax for x86 in
  947. Figure~\ref{fig:x86-ast-a}. The \itm{info} field of the \key{program}
  948. AST node is for storing auxiliary information that needs to be
  949. communicated from one step of the compiler to the next.
  950. \begin{figure}[tbp]
  951. \fbox{
  952. \begin{minipage}{0.96\textwidth}
  953. \[
  954. \begin{array}{lcl}
  955. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  956. \mid \STACKLOC{\Int} \\
  957. \Instr &::=& (\key{addq} \; \Arg\; \Arg) \mid
  958. (\key{subq} \; \Arg\; \Arg) \mid
  959. % (\key{imulq} \; \Arg\;\Arg) \mid
  960. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) \\
  961. &\mid& (\key{callq} \; \mathit{label}) \mid
  962. (\key{pushq}\;\Arg) \mid
  963. (\key{popq}\;\Arg) \mid
  964. (\key{retq}) \\
  965. x86_0 &::= & (\key{program} \;\itm{info} \; \Instr^{+})
  966. \end{array}
  967. \]
  968. \end{minipage}
  969. }
  970. \caption{Abstract syntax for x86-64 assembly.}
  971. \label{fig:x86-ast-a}
  972. \end{figure}
  973. \section{Planning the trip from $R_1$ to x86-64}
  974. \label{sec:plan-s0-x86}
  975. To compile one language to another it helps to focus on the
  976. differences between the two languages. It is these differences that
  977. the compiler will need to bridge. What are the differences between
  978. $R_1$ and x86-64 assembly? Here we list some of the most important the
  979. differences.
  980. \begin{enumerate}
  981. \item x86-64 arithmetic instructions typically take two arguments and
  982. update the second argument in place. In contrast, $R_1$ arithmetic
  983. operations only read their arguments and produce a new value.
  984. \item An argument to an $R_1$ operator can be any expression, whereas
  985. x86-64 instructions restrict their arguments to integers, registers,
  986. and memory locations.
  987. \item An $R_1$ program can have any number of variables whereas x86-64
  988. has only 16 registers.
  989. \item Variables in $R_1$ can overshadow other variables with the same
  990. name. The registers and memory locations of x86-64 all have unique
  991. names.
  992. \end{enumerate}
  993. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  994. the problem into several steps, dealing with the above differences one
  995. at a time. The main question then becomes: in what order do we tackle
  996. these differences? This is often one of the most challenging questions
  997. that a compiler writer must answer because some orderings may be much
  998. more difficult to implement than others. It is difficult to know ahead
  999. of time which orders will be better so often some trial-and-error is
  1000. involved. However, we can try to plan ahead and choose the orderings
  1001. based on this planning.
  1002. For example, to handle difference \#2 (nested expressions), we shall
  1003. introduce new variables and pull apart the nested expressions into a
  1004. sequence of assignment statements. To deal with difference \#3 we
  1005. will be replacing variables with registers and/or stack
  1006. locations. Thus, it makes sense to deal with \#2 before \#3 so that
  1007. \#3 can replace both the original variables and the new ones. Next,
  1008. consider where \#1 should fit in. Because it has to do with the format
  1009. of x86 instructions, it makes more sense after we have flattened the
  1010. nested expressions (\#2). Finally, when should we deal with \#4
  1011. (variable overshadowing)? We shall solve this problem by renaming
  1012. variables to make sure they have unique names. Recall that our plan
  1013. for \#2 involves moving nested expressions, which could be problematic
  1014. if it changes the shadowing of variables. However, if we deal with \#4
  1015. first, then it will not be an issue. Thus, we arrive at the following
  1016. ordering.
  1017. \[
  1018. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1019. \foreach \i/\p in {4/1,2/2,1/3,3/4}
  1020. {
  1021. \node (\i) at (\p*1.5,0) {$\i$};
  1022. }
  1023. \foreach \x/\y in {4/2,2/1,1/3}
  1024. {
  1025. \draw[->] (\x) to (\y);
  1026. }
  1027. \end{tikzpicture}
  1028. \]
  1029. We further simplify the translation from $R_1$ to x86 by identifying
  1030. an intermediate language named $C_0$, roughly half-way between $R_1$
  1031. and x86, to provide a rest stop along the way. We name the language
  1032. $C_0$ because it is vaguely similar to the $C$
  1033. language~\citep{Kernighan:1988nx}. The differences \#4 and \#1,
  1034. regarding variables and nested expressions, will be handled by two
  1035. steps, \key{uniquify} and \key{flatten}, which bring us to
  1036. $C_0$.
  1037. \[
  1038. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1039. \foreach \i/\p in {R_1/1,R_1/2,C_0/3}
  1040. {
  1041. \node (\p) at (\p*3,0) {\large $\i$};
  1042. }
  1043. \foreach \x/\y/\lbl in {1/2/uniquify,2/3/flatten}
  1044. {
  1045. \path[->,bend left=15] (\x) edge [above] node {\ttfamily\footnotesize \lbl} (\y);
  1046. }
  1047. \end{tikzpicture}
  1048. \]
  1049. Each of these steps in the compiler is implemented by a function,
  1050. typically a structurally recursive function that translates an input
  1051. AST into an output AST. We refer to such a function as a \emph{pass}
  1052. because it makes a pass over, i.e. traverses, the entire AST.
  1053. The syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}. The
  1054. $C_0$ language supports the same operators as $R_1$ but the arguments
  1055. of operators are now restricted to just variables and integers. The
  1056. \key{let} construct of $R_1$ is replaced by an assignment statement
  1057. and there is a \key{return} construct to specify the return value of
  1058. the program. A program consists of a sequence of statements that
  1059. include at least one \key{return} statement. Each program is also
  1060. annotated with a list of variables. At the start of the program, these
  1061. variables are uninitialized (they contain garbage) and each variable
  1062. becomes initialized on its first assignment. All of the variables used
  1063. in the program must be present in this list.
  1064. \begin{figure}[tbp]
  1065. \fbox{
  1066. \begin{minipage}{0.96\textwidth}
  1067. \[
  1068. \begin{array}{lcl}
  1069. \Arg &::=& \Int \mid \Var \\
  1070. \Exp &::=& \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)\\
  1071. \Stmt &::=& \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} \\
  1072. C_0 & ::= & (\key{program}\;(\Var^{*})\;\Stmt^{+})
  1073. \end{array}
  1074. \]
  1075. \end{minipage}
  1076. }
  1077. \caption{The $C_0$ intermediate language.}
  1078. \label{fig:c0-syntax}
  1079. \end{figure}
  1080. To get from $C_0$ to x86-64 assembly it remains for us to handle
  1081. difference \#1 (the format of instructions) and difference \#3
  1082. (variables versus registers). These two differences are intertwined,
  1083. creating a bit of a Gordian Knot. To handle difference \#3, we need to
  1084. map some variables to registers (there are only 16 registers) and the
  1085. remaining variables to locations on the stack (which is unbounded). To
  1086. make good decisions regarding this mapping, we need the program to be
  1087. close to its final form (in x86-64 assembly) so we know exactly when
  1088. which variables are used. After all, variables that are used in
  1089. disjoint parts of the program can be assigned to the same register.
  1090. However, our choice of x86-64 instructions depends on whether the
  1091. variables are mapped to registers or stack locations, so we have a
  1092. circular dependency. We cut this knot by doing an optimistic selection
  1093. of instructions in the \key{select-instructions} pass, followed by the
  1094. \key{assign-homes} pass to map variables to registers or stack
  1095. locations, and conclude by finalizing the instruction selection in the
  1096. \key{patch-instructions} pass.
  1097. \[
  1098. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1099. \node (1) at (0,0) {\large $C_0$};
  1100. \node (2) at (3,0) {\large $\text{x86}^{*}$};
  1101. \node (3) at (6,0) {\large $\text{x86}^{*}$};
  1102. \node (4) at (9,0) {\large $\text{x86}$};
  1103. \path[->,bend left=15] (1) edge [above] node {\ttfamily\footnotesize select-instr.} (2);
  1104. \path[->,bend left=15] (2) edge [above] node {\ttfamily\footnotesize assign-homes} (3);
  1105. \path[->,bend left=15] (3) edge [above] node {\ttfamily\footnotesize patch-instr.} (4);
  1106. \end{tikzpicture}
  1107. \]
  1108. The \key{select-instructions} pass is optimistic in the sense that it
  1109. treats variables as if they were all mapped to registers. The
  1110. \key{select-instructions} pass generates a program that consists of
  1111. x86-64 instructions but that still uses variables, so it is an
  1112. intermediate language that is technically different than x86-64, which
  1113. explains the asterisks in the diagram above.
  1114. In this Chapter we shall take the easy road to implementing
  1115. \key{assign-homes} and simply map all variables to stack locations.
  1116. The topic of Chapter~\ref{ch:register-allocation} is implementing a
  1117. smarter approach in which we make a best-effort to map variables to
  1118. registers, resorting to the stack only when necessary.
  1119. %% \marginpar{\scriptsize I'm confused: shouldn't `select instructions' do this?
  1120. %% After all, that selects the x86-64 instructions. Even if it is separate,
  1121. %% if we perform `patching' before register allocation, we aren't forced to rely on
  1122. %% \key{rax} as much. This can ultimately make a more-performant result. --
  1123. %% Cam}
  1124. Once variables have been assigned to their homes, we can finalize the
  1125. instruction selection by dealing with an idiosyncrasy of x86
  1126. assembly. Many x86 instructions have two arguments but only one of the
  1127. arguments may be a memory reference (and the stack is a part of
  1128. memory). Because some variables may get mapped to stack locations,
  1129. some of our generated instructions may violate this restriction. The
  1130. purpose of the \key{patch-instructions} pass is to fix this problem by
  1131. replacing every violating instruction with a short sequence of
  1132. instructions that use the \key{rax} register. Once we have implemented
  1133. a good register allocator (Chapter~\ref{ch:register-allocation}), the
  1134. need to patch instructions will be relatively rare.
  1135. \section{Uniquify Variables}
  1136. \label{sec:uniquify-s0}
  1137. The purpose of this pass is to make sure that each \key{let} uses a
  1138. unique variable name. For example, the \code{uniquify} pass should
  1139. translate the program on the left into the program on the right. \\
  1140. \begin{tabular}{lll}
  1141. \begin{minipage}{0.4\textwidth}
  1142. \begin{lstlisting}
  1143. (program
  1144. (let ([x 32])
  1145. (+ (let ([x 10]) x) x)))
  1146. \end{lstlisting}
  1147. \end{minipage}
  1148. &
  1149. $\Rightarrow$
  1150. &
  1151. \begin{minipage}{0.4\textwidth}
  1152. \begin{lstlisting}
  1153. (program
  1154. (let ([x.1 32])
  1155. (+ (let ([x.2 10]) x.2) x.1)))
  1156. \end{lstlisting}
  1157. \end{minipage}
  1158. \end{tabular} \\
  1159. %
  1160. The following is another example translation, this time of a program
  1161. with a \key{let} nested inside the initializing expression of another
  1162. \key{let}.\\
  1163. \begin{tabular}{lll}
  1164. \begin{minipage}{0.4\textwidth}
  1165. \begin{lstlisting}
  1166. (program
  1167. (let ([x (let ([x 4])
  1168. (+ x 1))])
  1169. (+ x 2)))
  1170. \end{lstlisting}
  1171. \end{minipage}
  1172. &
  1173. $\Rightarrow$
  1174. &
  1175. \begin{minipage}{0.4\textwidth}
  1176. \begin{lstlisting}
  1177. (program
  1178. (let ([x.2 (let ([x.1 4])
  1179. (+ x.1 1))])
  1180. (+ x.2 2)))
  1181. \end{lstlisting}
  1182. \end{minipage}
  1183. \end{tabular}
  1184. We recommend implementing \code{uniquify} as a structurally recursive
  1185. function that mostly copies the input program. However, when
  1186. encountering a \key{let}, it should generate a unique name for the
  1187. variable (the Racket function \code{gensym} is handy for this) and
  1188. associate the old name with the new unique name in an association
  1189. list. The \code{uniquify} function will need to access this
  1190. association list when it gets to a variable reference, so we add
  1191. another parameter to \code{uniquify} for the association list. It is
  1192. quite common for a compiler pass to need a map to store extra
  1193. information about variables. Such maps are often called \emph{symbol
  1194. tables}.
  1195. The skeleton of the \code{uniquify} function is shown in
  1196. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1197. convenient to partially apply it to an association list and then apply
  1198. it to different expressions, as in the last clause for primitive
  1199. operations in Figure~\ref{fig:uniquify-s0}. In the last \key{match}
  1200. clause for the primitive operators, note the use of the comma-@
  1201. operator to splice a list of S-expressions into an enclosing
  1202. S-expression.
  1203. \begin{exercise}
  1204. \normalfont % I don't like the italics for exercises. -Jeremy
  1205. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1206. implement the clauses for variables and for the \key{let} construct.
  1207. \end{exercise}
  1208. \begin{figure}[tbp]
  1209. \begin{lstlisting}
  1210. (define uniquify
  1211. (lambda (alist)
  1212. (lambda (e)
  1213. (match e
  1214. [(? symbol?) ___]
  1215. [(? integer?) e]
  1216. [`(let ([,x ,e]) ,body) ___]
  1217. [`(program ,e)
  1218. `(program ,((uniquify alist) e))]
  1219. [`(,op ,es ...)
  1220. `(,op ,@(map (uniquify alist) es))]
  1221. ))))
  1222. \end{lstlisting}
  1223. \caption{Skeleton for the \key{uniquify} pass.}
  1224. \label{fig:uniquify-s0}
  1225. \end{figure}
  1226. \begin{exercise}
  1227. \normalfont % I don't like the italics for exercises. -Jeremy
  1228. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1229. and checking whether the output programs produce the same result as
  1230. the input programs. The $R_1$ programs should be designed to test the
  1231. most interesting parts of the \key{uniquify} pass, that is, the
  1232. programs should include \key{let} constructs, variables, and variables
  1233. that overshadow each other. The five programs should be in a
  1234. subdirectory named \key{tests} and they should have the same file name
  1235. except for a different integer at the end of the name, followed by the
  1236. ending \key{.scm}. Use the \key{interp-tests} function
  1237. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1238. your \key{uniquify} pass on the example programs.
  1239. %% You can use the interpreter \key{interpret-S0} defined in the
  1240. %% \key{interp.rkt} file. The entire sequence of tests should be a short
  1241. %% Racket program so you can re-run all the tests by running the Racket
  1242. %% program. We refer to this as the \emph{regression test} program.
  1243. \end{exercise}
  1244. \section{Flatten Expressions}
  1245. \label{sec:flatten-r1}
  1246. The \code{flatten} pass will transform $R_1$ programs into $C_0$
  1247. programs. In particular, the purpose of the \code{flatten} pass is to
  1248. get rid of nested expressions, such as the \code{(- 10)} in the below
  1249. program. This can be accomplished by introducing a new variable,
  1250. assigning the nested expression to the new variable, and then using
  1251. the new variable in place of the nested expressions, as shown in the
  1252. output of \code{flatten} on the right.\\
  1253. \begin{tabular}{lll}
  1254. \begin{minipage}{0.4\textwidth}
  1255. \begin{lstlisting}
  1256. (program
  1257. (+ 52 (- 10)))
  1258. \end{lstlisting}
  1259. \end{minipage}
  1260. &
  1261. $\Rightarrow$
  1262. &
  1263. \begin{minipage}{0.4\textwidth}
  1264. \begin{lstlisting}
  1265. (program (tmp.1 tmp.2)
  1266. (assign tmp.1 (- 10))
  1267. (assign tmp.2 (+ 52 tmp.1))
  1268. (return tmp.2))
  1269. \end{lstlisting}
  1270. \end{minipage}
  1271. \end{tabular}
  1272. The clause of \code{flatten} for \key{let} is straightforward to
  1273. implement as it just requires the generation of an assignment
  1274. statement for the \key{let}-bound variable. The following shows the
  1275. result of \code{flatten} for a \key{let}. \\
  1276. \begin{tabular}{lll}
  1277. \begin{minipage}{0.4\textwidth}
  1278. \begin{lstlisting}
  1279. (program
  1280. (let ([x (+ (- 10) 11)])
  1281. (+ x 41)))
  1282. \end{lstlisting}
  1283. \end{minipage}
  1284. &
  1285. $\Rightarrow$
  1286. &
  1287. \begin{minipage}{0.4\textwidth}
  1288. \begin{lstlisting}
  1289. (program (tmp.1 x tmp.2)
  1290. (assign tmp.1 (- 10))
  1291. (assign x (+ tmp.1 11))
  1292. (assign tmp.2 (+ x 41))
  1293. (return tmp.2))
  1294. \end{lstlisting}
  1295. \end{minipage}
  1296. \end{tabular}
  1297. We recommend implementing \key{flatten} as a structurally recursive
  1298. function that returns two things, 1) the newly flattened expression,
  1299. and 2) a list of assignment statements, one for each of the new
  1300. variables introduced while flattening the expression. The newly
  1301. flattened expression should be a \emph{simple} expression, that is, an
  1302. integer or a variable. (There will be more kinds of simple expressions
  1303. in the input languages of later Chapters.) You can return multiple
  1304. things from a function using the \key{values} form and you can receive
  1305. multiple things from a function call using the \key{define-values}
  1306. form. If you are not familiar with these constructs, the Racket
  1307. documentation will be of help. Also, the \key{map2} function
  1308. (Appendix~\ref{appendix:utilities}) is useful for applying a function
  1309. to each element of a list, in the case where the function returns two
  1310. values. The result of \key{map2} is two lists.
  1311. The clause of \key{flatten} for the \key{program} node needs to
  1312. recursively flatten the body of the program and also compute the list
  1313. of variables used in the program. I recommend traversing the
  1314. statements in the body of the program (after it has been flattened)
  1315. and collect all variables that appear on the left-hand-side of an
  1316. assignment. Note that each variable should only occur ones in the list
  1317. of variables that you place in the \key{program} form.
  1318. Take special care for programs such as the following that initialize
  1319. variables with integers or other variables. It should be translated
  1320. to the program on the right \\
  1321. \begin{tabular}{lll}
  1322. \begin{minipage}{0.4\textwidth}
  1323. \begin{lstlisting}
  1324. (let ([a 42])
  1325. (let ([b a])
  1326. b))
  1327. \end{lstlisting}
  1328. \end{minipage}
  1329. &
  1330. $\Rightarrow$
  1331. &
  1332. \begin{minipage}{0.4\textwidth}
  1333. \begin{lstlisting}
  1334. (program (a b)
  1335. (assign a 42)
  1336. (assign b a)
  1337. (return b))
  1338. \end{lstlisting}
  1339. \end{minipage}
  1340. \end{tabular} \\
  1341. and not to the following, which could result from a naive
  1342. implementation of \key{flatten}.
  1343. \begin{lstlisting}
  1344. (program (tmp.1 a tmp.2 b)
  1345. (assign tmp.1 42)
  1346. (assign a tmp.1)
  1347. (assign tmp.2 a)
  1348. (assign b tmp.2)
  1349. (return b))
  1350. \end{lstlisting}
  1351. \begin{exercise}
  1352. \normalfont
  1353. Implement the \key{flatten} pass and test it on all of the example
  1354. programs that you created to test the \key{uniquify} pass and create
  1355. three new example programs that are designed to exercise all of the
  1356. interesting code in the \key{flatten} pass. Use the \key{interp-tests}
  1357. function (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to
  1358. test your passes on the example programs.
  1359. \end{exercise}
  1360. \section{Select Instructions}
  1361. \label{sec:select-s0}
  1362. In the \key{select-instructions} pass we begin the work of translating
  1363. from $C_0$ to x86. The target language of this pass is a pseudo-x86
  1364. language that still uses variables, so we add an AST node of the form
  1365. $\VAR{\itm{var}}$ to the x86 abstract syntax. The
  1366. \key{select-instructions} pass deals with the differing format of
  1367. arithmetic operations. For example, in $C_0$ an addition operation can
  1368. take the form below. To translate to x86, we need to use the
  1369. \key{addq} instruction which does an in-place update. So we must first
  1370. move \code{10} to \code{x}. \\
  1371. \begin{tabular}{lll}
  1372. \begin{minipage}{0.4\textwidth}
  1373. \begin{lstlisting}
  1374. (assign x (+ 10 32))
  1375. \end{lstlisting}
  1376. \end{minipage}
  1377. &
  1378. $\Rightarrow$
  1379. &
  1380. \begin{minipage}{0.4\textwidth}
  1381. \begin{lstlisting}
  1382. (movq (int 10) (var x))
  1383. (addq (int 32) (var x))
  1384. \end{lstlisting}
  1385. \end{minipage}
  1386. \end{tabular} \\
  1387. There are some cases that require special care to avoid generating
  1388. needlessly complicated code. If one of the arguments is the same as
  1389. the left-hand side of the assignment, then there is no need for the
  1390. extra move instruction. For example, the following assignment
  1391. statement can be translated into a single \key{addq} instruction.\\
  1392. \begin{tabular}{lll}
  1393. \begin{minipage}{0.4\textwidth}
  1394. \begin{lstlisting}
  1395. (assign x (+ 10 x))
  1396. \end{lstlisting}
  1397. \end{minipage}
  1398. &
  1399. $\Rightarrow$
  1400. &
  1401. \begin{minipage}{0.4\textwidth}
  1402. \begin{lstlisting}
  1403. (addq (int 10) (var x))
  1404. \end{lstlisting}
  1405. \end{minipage}
  1406. \end{tabular} \\
  1407. The \key{read} operation does not have a direct counterpart in x86-64
  1408. assembly, so we have instead implemented this functionality in the C
  1409. language, with the function \code{read\_int} in the file
  1410. \code{runtime.c}. In general, we have refer to all of the
  1411. functionality in this file as the \emph{runtime system}, or simply
  1412. \emph{runtime} for short. When compiling your generated x86-64
  1413. assembly code, you will need to compile \code{runtime.c} and link it
  1414. in. For for purposes of code generation, all you need to do is
  1415. translate an assignment of \key{read} to some left-hand side
  1416. $\itm{lhs}$ into call to the \code{read\_int} function followed by a
  1417. move from \code{rax} into $\itm{lhs}$. (Recall that the return value
  1418. of a function is typically placed in the \code{rax} register.) \\
  1419. \begin{tabular}{lll}
  1420. \begin{minipage}{0.4\textwidth}
  1421. \begin{lstlisting}
  1422. (assign |$\itm{lhs}$| (read))
  1423. \end{lstlisting}
  1424. \end{minipage}
  1425. &
  1426. $\Rightarrow$
  1427. &
  1428. \begin{minipage}{0.4\textwidth}
  1429. \begin{lstlisting}
  1430. (callq _read_int)
  1431. (movq (reg rax) |$\itm{lhs}$|)
  1432. \end{lstlisting}
  1433. \end{minipage}
  1434. \end{tabular} \\
  1435. Regarding the \RETURN{e} statement of $C_0$, we recommend treating it
  1436. as an assignment to the \key{rax} register and let the procedure
  1437. conclusion handle the transfer of control back to the calling
  1438. procedure.
  1439. \begin{exercise}
  1440. \normalfont
  1441. Implement the \key{select-instructions} pass and test it on all of the
  1442. example programs that you created for the previous passes and create
  1443. three new example programs that are designed to exercise all of the
  1444. interesting code in this pass. Use the \key{interp-tests} function
  1445. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1446. your passes on the example programs.
  1447. \end{exercise}
  1448. \section{Assign Homes}
  1449. \label{sec:assign-s0}
  1450. As discussed in Section~\ref{sec:plan-s0-x86}, the
  1451. \key{assign-homes} pass places all of the variables on the stack.
  1452. Consider again the example $R_1$ program \code{(+ 52 (- 10))},
  1453. which after \key{select-instructions} looks like the following.
  1454. \begin{lstlisting}
  1455. (movq (int 10) (var x))
  1456. (negq (var x))
  1457. (movq (int 52) (reg rax))
  1458. (addq (var x) (reg rax))
  1459. \end{lstlisting}
  1460. The one and only variable \code{x} is assigned to stack location
  1461. \code{-8(\%rbp)}, so the \code{assign-homes} pass translates the
  1462. above to
  1463. \begin{lstlisting}
  1464. (movq (int 10) (stack -8))
  1465. (negq (stack -8))
  1466. (movq (int 52) (reg rax))
  1467. (addq (stack -8) (reg rax))
  1468. \end{lstlisting}
  1469. In the process of assigning stack locations to variables, it is
  1470. convenient to compute and store the size of the frame in the
  1471. $\itm{info}$ field of the \key{program} node which will be needed
  1472. later to generate the procedure conclusion. Some operating systems
  1473. place restrictions on the frame size. For example, Mac OS X requires
  1474. the frame size to be a multiple of 16 bytes.
  1475. \begin{exercise}
  1476. \normalfont Implement the \key{assign-homes} pass and test it on all
  1477. of the example programs that you created for the previous passes pass.
  1478. I recommend that \key{assign-homes} take an extra parameter that is a
  1479. mapping of variable names to homes (stack locations for now). Use the
  1480. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1481. \key{utilities.rkt} to test your passes on the example programs.
  1482. \end{exercise}
  1483. \section{Patch Instructions}
  1484. \label{sec:patch-s0}
  1485. The purpose of this pass is to make sure that each instruction adheres
  1486. to the restrictions regarding which arguments can be memory
  1487. references. For most instructions, the rule is that at most one
  1488. argument may be a memory reference.
  1489. Consider again the following example.
  1490. \begin{lstlisting}
  1491. (let ([a 42])
  1492. (let ([b a])
  1493. b))
  1494. \end{lstlisting}
  1495. After \key{assign-homes} pass, the above has been translated to
  1496. \begin{lstlisting}
  1497. (movq (int 42) (stack -8))
  1498. (movq (stack -8) (stack -16))
  1499. (movq (stack -16) (reg rax))
  1500. \end{lstlisting}
  1501. The second \key{movq} instruction is problematic because both arguments
  1502. are stack locations. We suggest fixing this problem by moving from the
  1503. source to \key{rax} and then from \key{rax} to the destination, as
  1504. follows.
  1505. \begin{lstlisting}
  1506. (movq (int 42) (stack -8))
  1507. (movq (stack -8) (reg rax))
  1508. (movq (reg rax) (stack -16))
  1509. (movq (stack -16) (reg rax))
  1510. \end{lstlisting}
  1511. \begin{exercise}
  1512. \normalfont
  1513. Implement the \key{patch-instructions} pass and test it on all of the
  1514. example programs that you created for the previous passes and create
  1515. three new example programs that are designed to exercise all of the
  1516. interesting code in this pass. Use the \key{interp-tests} function
  1517. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1518. your passes on the example programs.
  1519. \end{exercise}
  1520. \section{Print x86-64}
  1521. \label{sec:print-x86}
  1522. The last step of the compiler from $R_1$ to x86-64 is to convert the
  1523. x86-64 AST (defined in Figure~\ref{fig:x86-ast-a}) to the string
  1524. representation (defined in Figure~\ref{fig:x86-a}). The Racket
  1525. \key{format} and \key{string-append} functions are useful in this
  1526. regard. The main work that this step needs to perform is to create the
  1527. \key{\_main} function and the standard instructions for its prelude
  1528. and conclusion, as shown in Figure~\ref{fig:p1-x86} of
  1529. Section~\ref{sec:x86-64}. You need to know the number of
  1530. stack-allocated variables, for which it is suggest that you compute in
  1531. the \key{assign-homes} pass (Section~\ref{sec:assign-s0}) and store in
  1532. the $\itm{info}$ field of the \key{program} node.
  1533. \begin{exercise}
  1534. \normalfont Implement the \key{print-x86} pass and test it on all of
  1535. the example programs that you created for the previous passes. Use the
  1536. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  1537. \key{utilities.rkt} to test your complete compiler on the example
  1538. programs.
  1539. \end{exercise}
  1540. %% \section{Testing with Interpreters}
  1541. %% The typical way to test a compiler is to run the generated assembly
  1542. %% code on a diverse set of programs and check whether they behave as
  1543. %% expected. However, when a compiler is structured as our is, with many
  1544. %% passes, when there is an error in the generated assembly code it can
  1545. %% be hard to determine which pass contains the source of the error. A
  1546. %% good way to isolate the error is to not only test the generated
  1547. %% assembly code but to also test the output of every pass. This requires
  1548. %% having interpreters for all the intermediate languages. Indeed, the
  1549. %% file \key{interp.rkt} in the supplemental code provides interpreters
  1550. %% for all the intermediate languages described in this book, starting
  1551. %% with interpreters for $R_1$, $C_0$, and x86 (in abstract syntax).
  1552. %% The file \key{run-tests.rkt} automates the process of running the
  1553. %% interpreters on the output programs of each pass and checking their
  1554. %% result.
  1555. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1556. \chapter{Register Allocation}
  1557. \label{ch:register-allocation}
  1558. In Chapter~\ref{ch:int-exp} we simplified the generation of x86-64
  1559. assembly by placing all variables on the stack. We can improve the
  1560. performance of the generated code considerably if we instead try to
  1561. place as many variables as possible into registers. The CPU can
  1562. access a register in a single cycle, whereas accessing the stack can
  1563. take from several cycles (to go to cache) to hundreds of cycles (to go
  1564. to main memory). Figure~\ref{fig:reg-eg} shows a program with four
  1565. variables that serves as a running example. We show the source program
  1566. and also the output of instruction selection. At that point the
  1567. program is almost x86-64 assembly but not quite; it still contains
  1568. variables instead of stack locations or registers.
  1569. \begin{figure}
  1570. \begin{minipage}{0.45\textwidth}
  1571. Source program:
  1572. \begin{lstlisting}
  1573. (program
  1574. (let ([v 1])
  1575. (let ([w 46])
  1576. (let ([x (+ v 7)])
  1577. (let ([y (+ 4 x)])
  1578. (let ([z (+ x w)])
  1579. (- z y)))))))
  1580. \end{lstlisting}
  1581. \end{minipage}
  1582. \begin{minipage}{0.45\textwidth}
  1583. After instruction selection:
  1584. \begin{lstlisting}
  1585. (program (v w x y z)
  1586. (movq (int 1) (var v))
  1587. (movq (int 46) (var w))
  1588. (movq (var v) (var x))
  1589. (addq (int 7) (var x))
  1590. (movq (var x) (var y))
  1591. (addq (int 4) (var y))
  1592. (movq (var x) (var z))
  1593. (addq (var w) (var z))
  1594. (movq (var z) (reg rax))
  1595. (subq (var y) (reg rax)))
  1596. \end{lstlisting}
  1597. \end{minipage}
  1598. \caption{Running example for this chapter.}
  1599. \label{fig:reg-eg}
  1600. \end{figure}
  1601. The goal of register allocation is to fit as many variables into
  1602. registers as possible. It is often the case that we have more
  1603. variables than registers, so we cannot naively map each variable to a
  1604. register. Fortunately, it is also common for different variables to be
  1605. needed during different periods of time, and in such cases the
  1606. variables can be mapped to the same register. Consider variables
  1607. \code{x} and \code{y} in Figure~\ref{fig:reg-eg}. After the variable
  1608. \code{x} is moved to \code{z} it is no longer needed. Variable
  1609. \code{y}, on the other hand, is used only after this point, so
  1610. \code{x} and \code{y} could share the same register. The topic of the
  1611. next section is how we compute where a variable is needed.
  1612. \section{Liveness Analysis}
  1613. \label{sec:liveness-analysis}
  1614. A variable is \emph{live} if the variable is used at some later point
  1615. in the program and there is not an intervening assignment to the
  1616. variable.
  1617. %
  1618. To understand the latter condition, consider the following code
  1619. fragment in which there are two writes to \code{b}. Are \code{a} and
  1620. \code{b} both live at the same time?
  1621. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  1622. (movq (int 5) (var a))
  1623. (movq (int 30) (var b))
  1624. (movq (var a) (var c))
  1625. (movq (int 10) (var b))
  1626. (addq (var b) (var c))
  1627. \end{lstlisting}
  1628. The answer is no because the value \code{30} written to \code{b} on
  1629. line 2 is never used. The variable \code{b} is read on line 5 and
  1630. there is an intervening write to \code{b} on line 4, so the read on
  1631. line 5 receives the value written on line 4, not line 2.
  1632. The live variables can be computed by traversing the instruction
  1633. sequence back to front (i.e., backwards in execution order). Let
  1634. $I_1,\ldots, I_n$ be the instruction sequence. We write
  1635. $L_{\mathsf{after}}(k)$ for the set of live variables after
  1636. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  1637. variables before instruction $I_k$. The live variables after an
  1638. instruction are always the same as the live variables before the next
  1639. instruction.
  1640. \begin{equation*}
  1641. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  1642. \end{equation*}
  1643. To start things off, there are no live variables after the last
  1644. instruction, so
  1645. \begin{equation*}
  1646. L_{\mathsf{after}}(n) = \emptyset
  1647. \end{equation*}
  1648. We then apply the following rule repeatedly, traversing the
  1649. instruction sequence back to front.
  1650. \begin{equation*}
  1651. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  1652. \end{equation*}
  1653. where $W(k)$ are the variables written to by instruction $I_k$ and
  1654. $R(k)$ are the variables read by instruction $I_k$.
  1655. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  1656. for the running example, with each instruction aligned with its
  1657. $L_{\mathtt{after}}$ set to make the figure easy to read.
  1658. \begin{figure}[tbp]
  1659. \hspace{20pt}
  1660. \begin{minipage}{0.45\textwidth}
  1661. \begin{lstlisting}
  1662. (program (v w x y z)
  1663. (movq (int 1) (var v))
  1664. (movq (int 46) (var w))
  1665. (movq (var v) (var x))
  1666. (addq (int 7) (var x))
  1667. (movq (var x) (var y))
  1668. (addq (int 4) (var y))
  1669. (movq (var x) (var z))
  1670. (addq (var w) (var z))
  1671. (movq (var z) (reg rax))
  1672. (subq (var y) (reg rax)))
  1673. \end{lstlisting}
  1674. \end{minipage}
  1675. \vrule\hspace{10pt}
  1676. \begin{minipage}{0.45\textwidth}
  1677. \begin{lstlisting}
  1678. |$\{ v \}$|
  1679. |$\{ v, w \}$|
  1680. |$\{ w, x \}$|
  1681. |$\{ w, x \}$|
  1682. |$\{ w, x, y\}$|
  1683. |$\{ w, x, y \}$|
  1684. |$\{ w, y, z \}$|
  1685. |$\{ y, z \}$|
  1686. |$\{ y \}$|
  1687. |$\{\}$|
  1688. \end{lstlisting}
  1689. \end{minipage}
  1690. \caption{The running example and its live-after sets.}
  1691. \label{fig:live-eg}
  1692. \end{figure}
  1693. \begin{exercise}\normalfont
  1694. Implement the compiler pass named \code{uncover-live} that computes
  1695. the live-after sets. We recommend storing the live-after sets (a list
  1696. of lists of variables) in the $\itm{info}$ field of the \key{program}
  1697. node alongside the list of variables as follows.
  1698. \begin{lstlisting}
  1699. (program (|$\Var^{*}$| |$\itm{live{-}afters}$|) |$\Instr^{+}$|)
  1700. \end{lstlisting}
  1701. I recommend organizing your code to use a helper function that takes a
  1702. list of statements and an initial live-after set (typically empty) and
  1703. returns the list of statements and the list of live-after sets. For
  1704. this chapter, returning the list of statements is unnecessary, as they
  1705. will be unchanged, but in Chapter~\ref{ch:bool-types} we introduce
  1706. \key{if} statements and will need to annotate them with the live-after
  1707. sets of the two branches.
  1708. I recommend creating helper functions to 1) compute the set of
  1709. variables that appear in an argument (of an instruction), 2) compute
  1710. the variables read by an instruction which corresponds to the $R$
  1711. function discussed above, and 3) the variables written by an
  1712. instruction which corresponds to $W$.
  1713. \end{exercise}
  1714. \section{Building the Interference Graph}
  1715. Based on the liveness analysis, we know where each variable is needed.
  1716. However, during register allocation, we need to answer questions of
  1717. the specific form: are variables $u$ and $v$ live at the same time?
  1718. (And therefore cannot be assigned to the same register.) To make this
  1719. question easier to answer, we create an explicit data structure, an
  1720. \emph{interference graph}. An interference graph is an undirected
  1721. graph that has an edge between two variables if they are live at the
  1722. same time, that is, if they interfere with each other.
  1723. The most obvious way to compute the interference graph is to look at
  1724. the set of live variables between each statement in the program, and
  1725. add an edge to the graph for every pair of variables in the same set.
  1726. This approach is less than ideal for two reasons. First, it can be
  1727. rather expensive because it takes $O(n^2)$ time to look at every pair
  1728. in a set of $n$ live variables. Second, there is a special case in
  1729. which two variables that are live at the same time do not actually
  1730. interfere with each other: when they both contain the same value
  1731. because we have assigned one to the other.
  1732. A better way to compute the interference graph is given by the
  1733. following.
  1734. \begin{itemize}
  1735. \item If instruction $I_k$ is a move: (\key{movq} $s$\, $d$), then add
  1736. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  1737. d$ or $v = s$.
  1738. \item If instruction $I_k$ is not a move but some other arithmetic
  1739. instruction such as (\key{addq} $s$\, $d$), then add the edge $(d,v)$
  1740. for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  1741. \item If instruction $I_k$ is of the form (\key{callq}
  1742. $\mathit{label}$), then add an edge $(r,v)$ for every caller-save
  1743. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  1744. \end{itemize}
  1745. Working from the top to bottom of Figure~\ref{fig:live-eg}, $z$
  1746. interferes with $x$, $y$ interferes with $z$, and $w$ interferes with
  1747. $y$ and $z$. The resulting interference graph is shown in
  1748. Figure~\ref{fig:interfere}.
  1749. \begin{figure}[tbp]
  1750. \large
  1751. \[
  1752. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1753. \node (v) at (0,0) {$v$};
  1754. \node (w) at (2,0) {$w$};
  1755. \node (x) at (4,0) {$x$};
  1756. \node (y) at (2,-2) {$y$};
  1757. \node (z) at (4,-2) {$z$};
  1758. \draw (v) to (w);
  1759. \foreach \i in {w,x,y}
  1760. {
  1761. \foreach \j in {w,x,y}
  1762. {
  1763. \draw (\i) to (\j);
  1764. }
  1765. }
  1766. \draw (z) to (w);
  1767. \draw (z) to (y);
  1768. \end{tikzpicture}
  1769. \]
  1770. \caption{Interference graph for the running example.}
  1771. \label{fig:interfere}
  1772. \end{figure}
  1773. \begin{exercise}\normalfont
  1774. Implement the compiler pass named \code{build-interference} according
  1775. to the algorithm suggested above. There are several helper functions
  1776. in \code{utilities.rkt} for representing graphs: \code{make-graph},
  1777. \code{add-edge}, and \code{adjacent}
  1778. (Appendix~\ref{appendix:utilities}). The output of this pass should
  1779. replace the live-after sets with the interference $\itm{graph}$ as
  1780. follows.
  1781. \begin{lstlisting}
  1782. (program (|$\Var^{*}$| |$\itm{graph}$|) |$\Instr^{+}$|)
  1783. \end{lstlisting}
  1784. \end{exercise}
  1785. \section{Graph Coloring via Sudoku}
  1786. We now come to the main event, mapping variables to registers (or to
  1787. stack locations in the event that we run out of registers). We need
  1788. to make sure not to map two variables to the same register if the two
  1789. variables interfere with each other. In terms of the interference
  1790. graph, this means we cannot map adjacent nodes to the same register.
  1791. If we think of registers as colors, the register allocation problem
  1792. becomes the widely-studied graph coloring
  1793. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  1794. The reader may be more familiar with the graph coloring problem then he
  1795. or she realizes; the popular game of Sudoku is an instance of the
  1796. graph coloring problem. The following describes how to build a graph
  1797. out of an initial Sudoku board.
  1798. \marginpar{\scriptsize To do: create a figure with a Sudoku
  1799. board and its corresponding graph. --Jeremy}
  1800. \begin{itemize}
  1801. \item There is one node in the graph for each Sudoku square.
  1802. \item There is an edge between two nodes if the corresponding squares
  1803. are in the same row, in the same column, or if the squares are in
  1804. the same $3\times 3$ region.
  1805. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  1806. \item Based on the initial assignment of numbers to squares in the
  1807. Sudoku board, assign the corresponding colors to the corresponding
  1808. nodes in the graph.
  1809. \end{itemize}
  1810. If you can color the remaining nodes in the graph with the nine
  1811. colors, then you have also solved the corresponding game of Sudoku.
  1812. Given that Sudoku is graph coloring, one can use Sudoku strategies to
  1813. come up with an algorithm for allocating registers. For example, one
  1814. of the basic techniques for Sudoku is called Pencil Marks. The idea is
  1815. that you use a process of elimination to determine what numbers no
  1816. longer make sense for a square, and write down those numbers in the
  1817. square (writing very small). For example, if the number $1$ is
  1818. assigned to a square, then by process of elimination, you can write
  1819. the pencil mark $1$ in all the squares in the same row, column, and
  1820. region. Many Sudoku computer games provide automatic support for
  1821. Pencil Marks. This heuristic also reduces the degree of branching in
  1822. the search tree.
  1823. The Pencil Marks technique corresponds to the notion of color
  1824. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  1825. node, in Sudoku terms, is the set of colors that are no longer
  1826. available. In graph terminology, we have the following definition:
  1827. \begin{equation*}
  1828. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  1829. \text{ and } \mathrm{color}(v) = c \}
  1830. \end{equation*}
  1831. where $\mathrm{adjacent}(u)$ is the set of nodes adjacent to $u$.
  1832. Using the Pencil Marks technique leads to a simple strategy for
  1833. filling in numbers: if there is a square with only one possible number
  1834. left, then write down that number! But what if there are no squares
  1835. with only one possibility left? One brute-force approach is to just
  1836. make a guess. If that guess ultimately leads to a solution, great. If
  1837. not, backtrack to the guess and make a different guess. Of course,
  1838. backtracking can be horribly time consuming. One standard way to
  1839. reduce the amount of backtracking is to use the most-constrained-first
  1840. heuristic. That is, when making a guess, always choose a square with
  1841. the fewest possibilities left (the node with the highest saturation).
  1842. The idea is that choosing highly constrained squares earlier rather
  1843. than later is better because later there may not be any possibilities.
  1844. In some sense, register allocation is easier than Sudoku because we
  1845. can always cheat and add more numbers by mapping variables to the
  1846. stack. We say that a variable is \emph{spilled} when we decide to map
  1847. it to a stack location. We would like to minimize the time needed to
  1848. color the graph, and backtracking is expensive. Thus, it makes sense
  1849. to keep the most-constrained-first heuristic but drop the backtracking
  1850. in favor of greedy search (guess and just keep going).
  1851. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  1852. greedy algorithm for register allocation based on saturation and the
  1853. most-constrained-first heuristic, which is roughly equivalent to the
  1854. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  1855. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just
  1856. as in Sudoku, the algorithm represents colors with integers, with the
  1857. first $k$ colors corresponding to the $k$ registers in a given machine
  1858. and the rest of the integers corresponding to stack locations.
  1859. \begin{figure}[btp]
  1860. \centering
  1861. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  1862. Algorithm: DSATUR
  1863. Input: a graph |$G$|
  1864. Output: an assignment |$\mathrm{color}[v]$| for each node |$v \in G$|
  1865. |$W \gets \mathit{vertices}(G)$|
  1866. while |$W \neq \emptyset$| do
  1867. pick a node |$u$| from |$W$| with the highest saturation,
  1868. breaking ties randomly
  1869. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(v)\}$|
  1870. |$\mathrm{color}[u] \gets c$|
  1871. |$W \gets W - \{u\}$|
  1872. \end{lstlisting}
  1873. \caption{Saturation-based greedy graph coloring algorithm.}
  1874. \label{fig:satur-algo}
  1875. \end{figure}
  1876. With this algorithm in hand, let us return to the running example and
  1877. consider how to color the interference graph in
  1878. Figure~\ref{fig:interfere}. Initially, all of the nodes are not yet
  1879. colored and they are unsaturated, so we annotate each of them with a
  1880. dash for their color and an empty set for the saturation.
  1881. \[
  1882. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1883. \node (v) at (0,0) {$v:-,\{\}$};
  1884. \node (w) at (3,0) {$w:-,\{\}$};
  1885. \node (x) at (6,0) {$x:-,\{\}$};
  1886. \node (y) at (3,-1.5) {$y:-,\{\}$};
  1887. \node (z) at (6,-1.5) {$z:-,\{\}$};
  1888. \draw (v) to (w);
  1889. \foreach \i in {w,x,y}
  1890. {
  1891. \foreach \j in {w,x,y}
  1892. {
  1893. \draw (\i) to (\j);
  1894. }
  1895. }
  1896. \draw (z) to (w);
  1897. \draw (z) to (y);
  1898. \end{tikzpicture}
  1899. \]
  1900. We select a maximally saturated node and color it $0$. In this case we
  1901. have a 5-way tie, so we arbitrarily pick $y$. The then mark color $0$
  1902. as no longer available for $w$, $x$, and $z$ because they interfere
  1903. with $y$.
  1904. \[
  1905. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1906. \node (v) at (0,0) {$v:-,\{\}$};
  1907. \node (w) at (3,0) {$w:-,\{0\}$};
  1908. \node (x) at (6,0) {$x:-,\{0\}$};
  1909. \node (y) at (3,-1.5) {$y:0,\{\}$};
  1910. \node (z) at (6,-1.5) {$z:-,\{0\}$};
  1911. \draw (v) to (w);
  1912. \foreach \i in {w,x,y}
  1913. {
  1914. \foreach \j in {w,x,y}
  1915. {
  1916. \draw (\i) to (\j);
  1917. }
  1918. }
  1919. \draw (z) to (w);
  1920. \draw (z) to (y);
  1921. \end{tikzpicture}
  1922. \]
  1923. Now we repeat the process, selecting another maximally saturated node.
  1924. This time there is a three-way tie between $w$, $x$, and $z$. We color
  1925. $w$ with $1$.
  1926. \[
  1927. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1928. \node (v) at (0,0) {$v:-,\{1\}$};
  1929. \node (w) at (3,0) {$w:1,\{0\}$};
  1930. \node (x) at (6,0) {$x:-,\{0,1\}$};
  1931. \node (y) at (3,-1.5) {$y:0,\{1\}$};
  1932. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  1933. \draw (v) to (w);
  1934. \foreach \i in {w,x,y}
  1935. {
  1936. \foreach \j in {w,x,y}
  1937. {
  1938. \draw (\i) to (\j);
  1939. }
  1940. }
  1941. \draw (z) to (w);
  1942. \draw (z) to (y);
  1943. \end{tikzpicture}
  1944. \]
  1945. The most saturated nodes are now $x$ and $z$. We color $x$ with the
  1946. next available color which is $2$.
  1947. \[
  1948. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1949. \node (v) at (0,0) {$v:-,\{1\}$};
  1950. \node (w) at (3,0) {$w:1,\{0,2\}$};
  1951. \node (x) at (6,0) {$x:2,\{0,1\}$};
  1952. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  1953. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  1954. \draw (v) to (w);
  1955. \foreach \i in {w,x,y}
  1956. {
  1957. \foreach \j in {w,x,y}
  1958. {
  1959. \draw (\i) to (\j);
  1960. }
  1961. }
  1962. \draw (z) to (w);
  1963. \draw (z) to (y);
  1964. \end{tikzpicture}
  1965. \]
  1966. We have only two nodes left to color, $v$ and $z$, but $z$ is
  1967. more highly saturated, so we color $z$ with $2$.
  1968. \[
  1969. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1970. \node (v) at (0,0) {$v:-,\{1\}$};
  1971. \node (w) at (3,0) {$w:1,\{0,2\}$};
  1972. \node (x) at (6,0) {$x:2,\{0,1\}$};
  1973. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  1974. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  1975. \draw (v) to (w);
  1976. \foreach \i in {w,x,y}
  1977. {
  1978. \foreach \j in {w,x,y}
  1979. {
  1980. \draw (\i) to (\j);
  1981. }
  1982. }
  1983. \draw (z) to (w);
  1984. \draw (z) to (y);
  1985. \end{tikzpicture}
  1986. \]
  1987. The last iteration of the coloring algorithm assigns color $0$ to $v$.
  1988. \[
  1989. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1990. \node (v) at (0,0) {$v:0,\{1\}$};
  1991. \node (w) at (3,0) {$w:1,\{0,2\}$};
  1992. \node (x) at (6,0) {$x:2,\{0,1\}$};
  1993. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  1994. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  1995. \draw (v) to (w);
  1996. \foreach \i in {w,x,y}
  1997. {
  1998. \foreach \j in {w,x,y}
  1999. {
  2000. \draw (\i) to (\j);
  2001. }
  2002. }
  2003. \draw (z) to (w);
  2004. \draw (z) to (y);
  2005. \end{tikzpicture}
  2006. \]
  2007. With the coloring complete, we can finalize the assignment of
  2008. variables to registers and stack locations. Recall that if we have $k$
  2009. registers, we map the first $k$ colors to registers and the rest to
  2010. stack locations. Suppose for the moment that we just have one extra
  2011. register to use for register allocation, just \key{rbx}. Then the
  2012. following is the mapping of colors to registers and stack allocations.
  2013. \[
  2014. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  2015. \]
  2016. Putting this together with the above coloring of the variables, we
  2017. arrive at the following assignment.
  2018. \[
  2019. \{ v \mapsto \key{\%rbx}, \;
  2020. w \mapsto \key{-8(\%rbp)}, \;
  2021. x \mapsto \key{-16(\%rbp)}, \;
  2022. y \mapsto \key{\%rbx}, \;
  2023. z\mapsto \key{-16(\%rbp)} \}
  2024. \]
  2025. Applying this assignment to our running example
  2026. (Figure~\ref{fig:reg-eg}) yields the following program.
  2027. % why frame size of 32? -JGS
  2028. \begin{lstlisting}
  2029. (program 32
  2030. (movq (int 1) (reg rbx))
  2031. (movq (int 46) (stack -8))
  2032. (movq (reg rbx) (stack -16))
  2033. (addq (int 7) (stack -16))
  2034. (movq (stack 16) (reg rbx))
  2035. (addq (int 4) (reg rbx))
  2036. (movq (stack -16) (stack -16))
  2037. (addq (stack -8) (stack -16))
  2038. (movq (stack -16) (reg rax))
  2039. (subq (reg rbx) (reg rax)))
  2040. \end{lstlisting}
  2041. This program is almost an x86-64 program. The remaining step is to apply
  2042. the patch instructions pass. In this example, the trivial move of
  2043. \code{-16(\%rbp)} to itself is deleted and the addition of
  2044. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  2045. \code{rax}. The following shows the portion of the program that
  2046. changed.
  2047. \begin{lstlisting}
  2048. (addq (int 4) (reg rbx))
  2049. (movq (stack -8) (reg rax)
  2050. (addq (reg rax) (stack -16))
  2051. \end{lstlisting}
  2052. An overview of all of the passes involved in register allocation is
  2053. shown in Figure~\ref{fig:reg-alloc-passes}.
  2054. \begin{figure}[tbp]
  2055. \[
  2056. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2057. \node (1) at (-3.5,0) {$C_0$};
  2058. \node (2) at (0,0) {$\text{x86-64}^{*}$};
  2059. \node (3) at (0,-1.5) {$\text{x86-64}^{*}$};
  2060. \node (4) at (0,-3) {$\text{x86-64}^{*}$};
  2061. \node (5) at (0,-4.5) {$\text{x86-64}^{*}$};
  2062. \node (6) at (3.5,-4.5) {$\text{x86-64}$};
  2063. \path[->] (1) edge [above] node {\ttfamily\scriptsize select-instructions} (2);
  2064. \path[->] (2) edge [right] node {\ttfamily\scriptsize uncover-live} (3);
  2065. \path[->] (3) edge [right] node {\ttfamily\scriptsize build-interference} (4);
  2066. \path[->] (4) edge [left] node {\ttfamily\scriptsize allocate-registers} (5);
  2067. \path[->] (5) edge [above] node {\ttfamily\scriptsize patch-instructions} (6);
  2068. \end{tikzpicture}
  2069. \]
  2070. \caption{Diagram of the passes for register allocation.}
  2071. \label{fig:reg-alloc-passes}
  2072. \end{figure}
  2073. \begin{exercise}\normalfont
  2074. Implement the pass \code{allocate-registers} and test it by creating
  2075. new example programs that exercise all of the register allocation
  2076. algorithm, such as forcing variables to be spilled to the stack.
  2077. I recommend organizing our code by creating a helper function named
  2078. \code{allocate-homes} that takes an interference graph, a list of all
  2079. the variables in the program, and the list of statements. This
  2080. function should return a mapping of variables to their homes
  2081. (registers or stack locations) and the total size needed for the
  2082. stack. By creating this helper function, we will be able to reuse it
  2083. in Chapter~\ref{ch:functions} when we add support for functions.
  2084. Once you have obtained the mapping from \code{allocate-homes}, you can
  2085. use the \code{assign-homes} function from Section~\ref{sec:assign-s0}
  2086. to replace the variables with their homes.
  2087. \end{exercise}
  2088. \marginpar{\scriptsize To do: a challenge exercise on move biasing. \\ --Jeremy}
  2089. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2090. \chapter{Booleans, Control Flow, and Type Checking}
  2091. \label{ch:bool-types}
  2092. Up until now the input languages have only included a single kind of
  2093. value, the integers. In this Chapter we add a second kind of value,
  2094. the Booleans (true and false), together with some new operations
  2095. (\key{and}, \key{not}, \key{eq?}) and conditional expressions to create
  2096. the $R_2$ language. With the addition of conditional expressions,
  2097. programs can have non-trivial control flow which has an impact on
  2098. several parts of the compiler. Also, because we now have two kinds of
  2099. values, we need to worry about programs that apply an operation to the
  2100. wrong kind of value, such as \code{(not 1)}.
  2101. There are two language design options for such situations. One option
  2102. is to signal an error and the other is to provide a wider
  2103. interpretation of the operation. The Racket language uses a mixture of
  2104. these two options, depending on the operation and on the kind of
  2105. value. For example, the result of \code{(not 1)} in Racket is
  2106. \code{\#f} (that is, false) because Racket treats non-zero integers as
  2107. true. On the other hand, \code{(car 1)} results in a run-time error in
  2108. Racket, which states that \code{car} expects a pair.
  2109. The Typed Racket language makes similar design choices as Racket,
  2110. except much of the error detection happens at compile time instead of
  2111. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  2112. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  2113. reports a compile-time error because the type of the argument is
  2114. expected to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  2115. For the $R_2$ language we choose to be more like Typed Racket in that
  2116. we shall perform type checking during compilation. However, we shall
  2117. take a narrower interpretation of the operations, rejecting
  2118. \code{(not 1)}. Despite this difference in design,
  2119. $R_2$ is literally a subset of Typed Racket. Every $R_2$
  2120. program is a Typed Racket program.
  2121. This chapter is organized as follows. We begin by defining the syntax
  2122. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  2123. then introduce the idea of type checking and build a type checker for
  2124. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  2125. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  2126. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  2127. how our compiler passes need to change to accommodate Booleans and
  2128. conditional control flow.
  2129. \section{The $R_2$ Language}
  2130. \label{sec:r2-lang}
  2131. The syntax of the $R_2$ language is defined in
  2132. Figure~\ref{fig:r2-syntax}. It includes all of $R_1$, so we only show
  2133. the new operators and expressions. We add the Boolean literals
  2134. \code{\#t} and \code{\#f} for true and false and the conditional
  2135. expression. The operators are expanded to include the \key{and} and
  2136. \key{not} operations on Booleans and the \key{eq?} operation for
  2137. comparing two integers and for comparing two Booleans.
  2138. \begin{figure}[tbp]
  2139. \centering
  2140. \fbox{
  2141. \begin{minipage}{0.96\textwidth}
  2142. \[
  2143. \begin{array}{lcl}
  2144. \Op &::=& \ldots \mid \key{and} \mid \key{not} \mid \key{eq?} \\
  2145. \Exp &::=& \ldots \mid \key{\#t} \mid \key{\#f} \mid
  2146. \IF{\Exp}{\Exp}{\Exp} \\
  2147. R_2 &::=& (\key{program} \; \Exp)
  2148. \end{array}
  2149. \]
  2150. \end{minipage}
  2151. }
  2152. \caption{The $R_2$ language, an extension of $R_1$
  2153. (Figure~\ref{fig:r1-syntax}).}
  2154. \label{fig:r2-syntax}
  2155. \end{figure}
  2156. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  2157. the parts that are the same as the interpreter for $R_1$
  2158. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  2159. simply evaluate to themselves. The conditional expression \code{(if
  2160. cnd thn els)} evaluates the Boolean expression \code{cnd} and then
  2161. either evaluates \code{thn} or \code{els} depending on whether
  2162. \code{cnd} produced \code{\#t} or \code{\#f}. The logical operations
  2163. \code{not} and \code{and} behave as you might expect, but note that
  2164. the \code{and} operation is short-circuiting. That is, the second
  2165. expression \code{e2} is not evaluated if \code{e1} evaluates to
  2166. \code{\#f}.
  2167. \begin{figure}[tbp]
  2168. \begin{lstlisting}
  2169. (define (interp-R2 env e)
  2170. (match e
  2171. ...
  2172. [(? boolean?) e]
  2173. [`(if ,cnd ,thn ,els)
  2174. (match (interp-R2 env cnd)
  2175. [#t (interp-R2 env thn)]
  2176. [#f (interp-R2 env els)])]
  2177. [`(not ,e)
  2178. (match (interp-R2 env e) [#t #f] [#f #t])]
  2179. [`(and ,e1 ,e2)
  2180. (match (interp-R2 env e1)
  2181. [#t (match (interp-R2 env e2) [#t #t] [#f #f])]
  2182. [#f #f])]
  2183. [`(eq? ,e1 ,e2)
  2184. (let ([v1 (interp-R2 env e1)] [v2 (interp-R2 env e2)])
  2185. (cond [(and (fixnum? v1) (fixnum? v2)) (eq? v1 v2)]
  2186. [(and (boolean? v1) (boolean? v2)) (eq? v1 v2)]))]
  2187. ))
  2188. \end{lstlisting}
  2189. \caption{Interpreter for the $R_2$ language.}
  2190. \label{fig:interp-R2}
  2191. \end{figure}
  2192. \section{Type Checking $R_2$ Programs}
  2193. \label{sec:type-check-r2}
  2194. It is helpful to think about type checking into two complementary
  2195. ways. A type checker predicts the \emph{type} of value that will be
  2196. produced by each expression in the program. For $R_2$, we have just
  2197. two types, \key{Integer} and \key{Boolean}. So a type checker should
  2198. predict that
  2199. \begin{lstlisting}
  2200. (+ 10 (- (+ 12 20)))
  2201. \end{lstlisting}
  2202. produces an \key{Integer} while
  2203. \begin{lstlisting}
  2204. (and (not #f) #t)
  2205. \end{lstlisting}
  2206. produces a \key{Boolean}.
  2207. As mentioned at the beginning of this chapter, a type checker also
  2208. rejects programs that apply operators to the wrong type of value. Our
  2209. type checker for $R_2$ will signal an error for the following because,
  2210. as we have seen above, the expression \code{(+ 10 ...)} has type
  2211. \key{Integer}, and we shall require an argument of \code{not} to have
  2212. type \key{Boolean}.
  2213. \begin{lstlisting}
  2214. (not (+ 10 (- (+ 12 20))))
  2215. \end{lstlisting}
  2216. The type checker for $R_2$ is best implemented as a structurally
  2217. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  2218. many of the clauses for the \code{typecheck-R2} function. Given an
  2219. input expression \code{e}, the type checker either returns the type
  2220. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  2221. the type of an integer literal is \code{Integer} and the type of a
  2222. Boolean literal is \code{Boolean}. To handle variables, the type
  2223. checker, like the interpreter, uses an association list. However, in
  2224. this case the association list maps variables to types instead of
  2225. values. Consider the clause for \key{let}. We type check the
  2226. initializing expression to obtain its type \key{T} and then map the
  2227. variable \code{x} to \code{T}. When the type checker encounters the
  2228. use of a variable, it can lookup its type in the association list.
  2229. \begin{figure}[tbp]
  2230. \begin{lstlisting}
  2231. (define (typecheck-R2 env e)
  2232. (match e
  2233. [(? fixnum?) 'Integer]
  2234. [(? boolean?) 'Boolean]
  2235. [(? symbol?) (lookup e env)]
  2236. [`(let ([,x ,e]) ,body)
  2237. (define T (typecheck-R2 env e))
  2238. (define new-env (cons (cons x T) env))
  2239. (typecheck-R2 new-env body)]
  2240. ...
  2241. [`(not ,e)
  2242. (match (typecheck-R2 env e)
  2243. ['Boolean 'Boolean]
  2244. [else (error 'typecheck-R2 "'not' expects a Boolean" e)])]
  2245. ...
  2246. ))
  2247. \end{lstlisting}
  2248. \caption{Skeleton of a type checker for the $R_2$ language.}
  2249. \label{fig:type-check-R2}
  2250. \end{figure}
  2251. \begin{exercise}\normalfont
  2252. Complete the implementation of \code{typecheck-R2} and test it on 10
  2253. new example programs in $R_2$ that you choose based on how thoroughly
  2254. they test the type checking algorithm. Half of the example programs
  2255. should have a type error, to make sure that your type checker properly
  2256. rejects them. The other half of the example programs should not have
  2257. type errors. Your testing should check that the result of the type
  2258. checker agrees with the value returned by the interpreter, that is, if
  2259. the type checker returns \key{Integer}, then the interpreter should
  2260. return an integer. Likewise, if the type checker returns
  2261. \key{Boolean}, then the interpreter should return \code{\#t} or
  2262. \code{\#f}. Note that if your type checker does not signal an error
  2263. for a program, then interpreting that program should not encounter an
  2264. error. If it does, there is something wrong with your type checker.
  2265. \end{exercise}
  2266. \section{The $C_1$ Language}
  2267. \label{sec:c1}
  2268. The $R_2$ language adds Booleans and conditional expressions to $R_1$.
  2269. As with $R_1$, we shall compile to a C-like intermediate language, but
  2270. we need to grow that intermediate language to handle the new features
  2271. in $R_2$. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$;
  2272. we add the new logic and comparison operators to the $\Op$
  2273. non-terminal, the literals \key{\#t} and \key{\#f} to the $\Arg$
  2274. non-terminal, and we add an \key{if} statement. Unlike $R_2$, the
  2275. \key{and} operation is not short-circuiting; it evaluates both
  2276. arguments unconditionally.
  2277. \begin{figure}[tbp]
  2278. \fbox{
  2279. \begin{minipage}{0.96\textwidth}
  2280. \[
  2281. \begin{array}{lcl}
  2282. \Op &::=& \ldots \mid \key{and} \mid \key{not} \mid \key{eq?} \\
  2283. \Arg &::=& \ldots \mid \key{\#t} \mid \key{\#f} \\
  2284. \Stmt &::=& \ldots \mid \IF{\Exp}{\Stmt^{*}}{\Stmt^{*}} \\
  2285. C_1 & ::= & (\key{program}\;(\Var^{*})\;\Stmt^{+})
  2286. \end{array}
  2287. \]
  2288. \end{minipage}
  2289. }
  2290. \caption{The $C_1$ intermediate language, an extension of $C_0$
  2291. (Figure~\ref{fig:c0-syntax}).}
  2292. \label{fig:c1-syntax}
  2293. \end{figure}
  2294. \section{Flatten Expressions}
  2295. \label{sec:flatten-r2}
  2296. The \code{flatten} pass needs to be expanded to handle the Boolean
  2297. literals \key{\#t} and \key{\#f}, the new logic and comparison
  2298. operations, and \key{if} expressions. We shall start with a simple
  2299. example of translating a \key{if} expression, shown below on the
  2300. left. \\
  2301. \begin{tabular}{lll}
  2302. \begin{minipage}{0.4\textwidth}
  2303. \begin{lstlisting}
  2304. (program (if #f 0 42))
  2305. \end{lstlisting}
  2306. \end{minipage}
  2307. &
  2308. $\Rightarrow$
  2309. &
  2310. \begin{minipage}{0.4\textwidth}
  2311. \begin{lstlisting}
  2312. (program (if.1)
  2313. (if #f
  2314. ((assign if.1 0))
  2315. ((assign if.1 42)))
  2316. (return if.1))
  2317. \end{lstlisting}
  2318. \end{minipage}
  2319. \end{tabular} \\
  2320. The value of the \key{if} expression is the value of the branch that
  2321. is selected. Recall that in the \code{flatten} pass we need to replace
  2322. complex expressions with simple expressions (variables or
  2323. literals). In the translation above, on the right, we have translated
  2324. the \key{if} expression into a new variable \key{if.1} and we have
  2325. produced code that will assign the appropriate value to \key{if.1}.
  2326. For $R_1$, the \code{flatten} pass returned a list of assignment
  2327. statements. Here, for $R_2$, we return a list of statements that can
  2328. include both \key{if} statements and assignment statements.
  2329. The next example is a bit more involved, showing what happens when
  2330. there are complex expressions in the condition and branch expressions
  2331. of an \key{if}, including nested \key{if} expressions.
  2332. \begin{tabular}{lll}
  2333. \begin{minipage}{0.4\textwidth}
  2334. \begin{lstlisting}
  2335. (program
  2336. (if (eq? (read) 0)
  2337. 777
  2338. (+ 2 (if (eq? (read) 0)
  2339. 40
  2340. 444))))
  2341. \end{lstlisting}
  2342. \end{minipage}
  2343. &
  2344. $\Rightarrow$
  2345. &
  2346. \begin{minipage}{0.4\textwidth}
  2347. \begin{lstlisting}
  2348. (program (t.1 t.2 if.1 t.3
  2349. t.4 if.2 t.5)
  2350. (assign t.1 (read))
  2351. (assign t.2 (eq? t.1 0))
  2352. (if t.2
  2353. ((assign if.1 777))
  2354. ((assign t.3 (read))
  2355. (assign t.4 (eq? t.3 0))
  2356. (if t.4
  2357. ((assign if.2 40))
  2358. ((assign if.2 444)))
  2359. (assign t.5 (+ 2 if.2))
  2360. (assign if.1 t.5)))
  2361. (return if.1))
  2362. \end{lstlisting}
  2363. \end{minipage}
  2364. \end{tabular} \\
  2365. The \code{flatten} clauses for the Boolean literals and the operations
  2366. \key{not} and \key{eq?} are straightforward. However, the
  2367. \code{flatten} clause for \key{and} requires some care to properly
  2368. imitate the order of evaluation of the interpreter for $R_2$
  2369. (Figure~\ref{fig:interp-R2}). Recall that the \key{and} operator of
  2370. $C_1$ does not perform short circuiting, but evaluates both arguments
  2371. unconditionally. We recommend using an \key{if} statement in the code
  2372. you generate for \key{and}.
  2373. \begin{exercise}\normalfont
  2374. Expand your \code{flatten} pass to handle $R_2$, that is, handle the
  2375. Boolean literals, the new logic and comparison operations, and the
  2376. \key{if} expressions. Create 4 more test cases that expose whether
  2377. your flattening code is correct. Test your \code{flatten} pass by
  2378. running the output programs with \code{interp-C}
  2379. (Appendix~\ref{appendix:interp}).
  2380. \end{exercise}
  2381. \section{More x86-64}
  2382. \label{sec:x86-1}
  2383. To implement the new logical operations, the comparison \key{eq?}, and
  2384. the \key{if} statement, we need to delve further into the x86-64
  2385. language. Figure~\ref{fig:x86-ast-b} defines the abstract syntax for a
  2386. larger subset of x86-64 that includes instructions for logical
  2387. operations, comparisons, and jumps. The logical instructions
  2388. (\key{andq} and \key{notq}) are quite similar to the arithmetic
  2389. instructions, so we focus on the comparison and jump instructions.
  2390. \begin{figure}[tbp]
  2391. \fbox{
  2392. \begin{minipage}{0.96\textwidth}
  2393. \[
  2394. \begin{array}{lcl}
  2395. \Arg &::=& \ldots \mid (\key{byte-reg}\; \itm{register}) \\
  2396. \Instr &::=& \ldots \mid (\key{andq} \; \Arg\; \Arg) \mid (\key{notq} \; \Arg)\\
  2397. &\mid& (\key{cmpq} \; \Arg\; \Arg) \mid (\key{sete} \; \Arg)
  2398. \mid (\key{movzbq}\;\Arg\;\Arg) \\
  2399. &\mid& (\key{jmp} \; \itm{label}) \mid (\key{je} \; \itm{label}) \mid
  2400. (\key{label} \; \itm{label}) \\
  2401. x86_1 &::= & (\key{program} \;\itm{info} \; \Instr^{+})
  2402. \end{array}
  2403. \]
  2404. \end{minipage}
  2405. }
  2406. \caption{The x86$_1$ language (extends x86$^{*}_0$ of Figure~\ref{fig:x86-ast-a}).}
  2407. \label{fig:x86-ast-b}
  2408. \end{figure}
  2409. The \key{cmpq} instruction is somewhat unusual in that its arguments
  2410. are the two things to be compared and the result (less than, greater
  2411. than, equal, not equal, etc.) is placed in the special EFLAGS
  2412. register. This register cannot be accessed directly but it can be
  2413. queried by a number of instructions, including the \key{sete}
  2414. instruction. The \key{sete} instruction puts a \key{1} or \key{0} into
  2415. its destination depending on whether the comparison came out as equal
  2416. or not, respectively. The \key{sete} instruction has an annoying quirk
  2417. in that its destination argument must be single byte register, such as
  2418. \code{al}, which is part of the \code{rax} register. Thankfully, the
  2419. \key{movzbq} instruction can then be used to move from a single byte
  2420. register to a normal 64-bit register.
  2421. The \key{jmp} instruction jumps to the instruction after the indicated
  2422. label. The \key{je} instruction jumps to the instruction after the
  2423. indicated label if the result in the EFLAGS register is equal, whereas
  2424. the \key{je} instruction falls through to the next instruction if
  2425. EFLAGS is not equal.
  2426. \section{Select Instructions}
  2427. \label{sec:select-r2}
  2428. The \code{select-instructions} pass needs to lower from $C_1$ to an
  2429. intermediate representation suitable for conducting register
  2430. allocation, i.e., close to x86$_1$. We can take the usual approach of
  2431. encoding Booleans as integers, with true as 1 and false as 0.
  2432. \[
  2433. \key{\#t} \Rightarrow \key{1}
  2434. \qquad
  2435. \key{\#f} \Rightarrow \key{0}
  2436. \]
  2437. Translating the \code{eq?} operation to x86 is slightly involved due
  2438. to the unusual nature of the \key{cmpq} instruction discussed above.
  2439. We recommend translating an assignment from \code{eq?} into the
  2440. following sequence of three instructions. \\
  2441. \begin{tabular}{lll}
  2442. \begin{minipage}{0.4\textwidth}
  2443. \begin{lstlisting}
  2444. (assign |$\itm{lhs}$| (eq? |$\Arg_1$| |$\Arg_2$|))
  2445. \end{lstlisting}
  2446. \end{minipage}
  2447. &
  2448. $\Rightarrow$
  2449. &
  2450. \begin{minipage}{0.4\textwidth}
  2451. \begin{lstlisting}
  2452. (cmpq |$\Arg_1$| |$\Arg_2$|)
  2453. (sete (byte-reg al))
  2454. (movzbq (byte-reg al) |$\itm{lhs}$|)
  2455. \end{lstlisting}
  2456. \end{minipage}
  2457. \end{tabular} \\
  2458. One further caveat is that the arguments of the \key{cmpq} instruction
  2459. may not both be immediate values. In that case you must insert another
  2460. \key{movq} instruction to put one of the immediate values in
  2461. \key{rax}.
  2462. Regarding \key{if} statements, we recommend that you not lower them in
  2463. \code{select-instructions} but instead lower them in
  2464. \code{patch-instructions}. The reason is that for purposes of
  2465. liveness analysis, \key{if} statements are easier to deal with than
  2466. jump instructions.
  2467. \begin{exercise}\normalfont
  2468. Expand your \code{select-instructions} pass to handle the new features
  2469. of the $R_2$ language. Test the pass on all the examples you have
  2470. created and make sure that you have some test programs that use the
  2471. \code{eq?} operator, creating some if necessary. Test the output of
  2472. \code{select-instructions} using the \code{interp-x86} interpreter
  2473. (Appendix~\ref{appendix:interp}).
  2474. \end{exercise}
  2475. \section{Register Allocation}
  2476. \label{sec:register-allocation-r2}
  2477. The changes required for $R_2$ affect the liveness analysis, building
  2478. the interference graph, and assigning homes, but the graph coloring
  2479. algorithm itself should not need to change.
  2480. \subsection{Liveness Analysis}
  2481. \label{sec:liveness-analysis-r2}
  2482. The addition of \key{if} statements brings up an interesting issue in
  2483. liveness analysis. Recall that liveness analysis works backwards
  2484. through the program, for each instruction computing the variables that
  2485. are live before the instruction based on which variables are live
  2486. after the instruction. Now consider the situation for \code{(\key{if}
  2487. $\itm{cnd}$ $\itm{thns}$ $\itm{elss}$)}, where we know the
  2488. $L_{\mathsf{after}}$ set and need to produce the $L_{\mathsf{before}}$
  2489. set. We can recursively perform liveness analysis on the $\itm{thns}$
  2490. and $\itm{elss}$ branches, using $L_{\mathsf{after}}$ as the starting
  2491. point, to obtain $L^{\mathsf{thns}}_{\mathsf{before}}$ and
  2492. $L^{\mathsf{elss}}_{\mathsf{before}}$ respectively. However, we do not
  2493. know, during compilation, which way the branch will go, so we do not
  2494. know whether to use $L^{\mathsf{thns}}_{\mathsf{before}}$ or
  2495. $L^{\mathsf{elss}}_{\mathsf{before}}$ as the $L_{\mathsf{before}}$ for
  2496. the entire \key{if} statement. The solution comes from the observation
  2497. that there is no harm in identifying more variables as live than
  2498. absolutely necessary. Thus, we can take the union of the live
  2499. variables from the two branches to be the live set for the whole
  2500. \key{if}, as shown below. Of course, we also need to include the
  2501. variables that are read in the $\itm{cnd}$ argument.
  2502. \[
  2503. L_{\mathsf{before}} = L^{\mathsf{thns}}_{\mathsf{before}} \cup
  2504. L^{\mathsf{elss}}_{\mathsf{before}} \cup \mathit{Vars}(\itm{cnd})
  2505. \]
  2506. We need the live-after sets for all the instructions in both branches
  2507. of the \key{if} when we build the interference graph, so I recommend
  2508. storing that data in the \key{if} statement AST as follows:
  2509. \begin{lstlisting}
  2510. (if |$\itm{cnd}$| |$\itm{thns}$| |$\itm{thn{-}lives}$| |$\itm{elss}$| |$\itm{els{-}lives}$|)
  2511. \end{lstlisting}
  2512. If you wrote helper functions for computing the variables in an
  2513. argument and the variables read-from ($R$) or written-to ($W$) by an
  2514. instruction, you need to be update them to handle the new kinds of
  2515. arguments and instructions in x86$_1$.
  2516. \subsection{Build Interference}
  2517. \label{sec:build-interference-r2}
  2518. Many of the new instructions, such as the logical operations, can be
  2519. handled in the same way as the arithmetic instructions. Thus, if your
  2520. code was already quite general, it will not need to be changed to
  2521. handle the logical operations. If not, I recommend that you change
  2522. your code to be more general. The \key{movzbq} instruction should be
  2523. handled like the \key{movq} instruction. The \key{if} statement is
  2524. straightforward to handle because we stored the live-after sets for the
  2525. two branches in the AST node as described above. Here we just need to
  2526. recursively process the two branches. The output of this pass can
  2527. discard the live after sets, as they are no longer needed.
  2528. \subsection{Assign Homes}
  2529. \label{sec:assign-homes-r2}
  2530. The \code{assign-homes} function (Section~\ref{sec:assign-s0}) needs
  2531. to be updated to handle the \key{if} statement, simply by recursively
  2532. processing the child nodes. Hopefully your code already handles the
  2533. other new instructions, but if not, you can generalize your code.
  2534. \begin{exercise}\normalfont
  2535. Implement the additions to the \code{register-allocation} pass so that
  2536. it works for $R_2$ and test your compiler using your previously
  2537. created programs on the \code{interp-x86} interpreter
  2538. (Appendix~\ref{appendix:interp}).
  2539. \end{exercise}
  2540. \section{Patch Instructions}
  2541. \label{sec:patch-instructions-r2}
  2542. In the \code{select-instructions} pass we decided to procrastinate in
  2543. the lowering of the \key{if} statement (thereby making liveness
  2544. analysis easier). Now we need to make up for that and turn the
  2545. \key{if} statement into the appropriate instruction sequence. The
  2546. following translation gives the general idea. If the condition
  2547. $\itm{cnd}$ is false then we need to execute the $\itm{elss}$
  2548. branch. So we compare $\itm{cnd}$ with $0$ and do a conditional jump
  2549. to the $\itm{elselabel}$ (which we can generate with \code{gensym}).
  2550. Otherwise we fall through to the $\itm{thns}$ branch. At the end of
  2551. the $\itm{thns}$ branch we need to take care to not fall through to
  2552. the $\itm{elss}$ branch. So we jump to the $\itm{endlabel}$ (also
  2553. generated with \code{gensym}).
  2554. \begin{tabular}{lll}
  2555. \begin{minipage}{0.3\textwidth}
  2556. \begin{lstlisting}
  2557. (if |$\itm{cnd}$| |$\itm{thns}$| |$\itm{elss}$|)
  2558. \end{lstlisting}
  2559. \end{minipage}
  2560. &
  2561. $\Rightarrow$
  2562. &
  2563. \begin{minipage}{0.4\textwidth}
  2564. \begin{lstlisting}
  2565. (cmpq (int 0) |$\itm{cnd}$|)
  2566. (je |$\itm{elselabel}$|)
  2567. |$\itm{thns}$|
  2568. (jmp |$\itm{endlabel}$|)
  2569. (label |$\itm{elselabel}$|)
  2570. |$\itm{elss}$|
  2571. (label |$\itm{endlabel}$|)
  2572. \end{lstlisting}
  2573. \end{minipage}
  2574. \end{tabular}
  2575. \begin{exercise}\normalfont
  2576. Update your \code{patch-instruction} pass to handle $R_2$ and test
  2577. your compiler using your previously created programs on the
  2578. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  2579. \end{exercise}
  2580. \section{An Example Translation}
  2581. Figure~\ref{fig:if-example-x86} shows a simple example program in
  2582. $R_2$ translated to x86-64, showing the results of \code{flatten},
  2583. \code{select-instructions}, \code{allocate-registers}, and the final
  2584. x86-64 assembly.
  2585. \begin{figure}[tbp]
  2586. \begin{tabular}{lll}
  2587. \begin{minipage}{0.5\textwidth}
  2588. \begin{lstlisting}
  2589. (program
  2590. (if (eq? (read) 1) 42 0))
  2591. \end{lstlisting}
  2592. $\Downarrow$
  2593. \begin{lstlisting}
  2594. (program (t.1 t.2 if.1)
  2595. (assign t.1 (read))
  2596. (assign t.2 (eq? t.1 1))
  2597. (if t.2
  2598. ((assign if.1 42))
  2599. ((assign if.1 0)))
  2600. (return if.1))
  2601. \end{lstlisting}
  2602. $\Downarrow$
  2603. \begin{lstlisting}
  2604. (program (t.1 t.2 if.1)
  2605. (callq _read_int)
  2606. (movq (reg rax) (var t.1))
  2607. (cmpq (int 1) (var t.1))
  2608. (sete (byte-reg al))
  2609. (movzbq (byte-reg al) (var t.2))
  2610. (if (var t.2)
  2611. ((movq (int 42) (var if.1)))
  2612. ((movq (int 0) (var if.1))))
  2613. (movq (var if.1) (reg rax)))
  2614. \end{lstlisting}
  2615. \end{minipage}
  2616. &
  2617. \begin{minipage}{0.4\textwidth}
  2618. $\Downarrow$
  2619. \begin{lstlisting}
  2620. (program 16
  2621. (callq _read_int)
  2622. (movq (reg rax) (reg rcx))
  2623. (cmpq (int 1) (reg rcx))
  2624. (sete (byte-reg al))
  2625. (movzbq (byte-reg al) (reg rcx))
  2626. (if (reg rcx)
  2627. ((movq (int 42)
  2628. (reg rbx)))
  2629. ((movq (int 0) (reg rbx))))
  2630. (movq (reg rbx) (reg rax)))
  2631. \end{lstlisting}
  2632. $\Downarrow$
  2633. \begin{lstlisting}
  2634. .globl _main
  2635. _main:
  2636. pushq %rbp
  2637. movq %rsp, %rbp
  2638. subq $16, %rsp
  2639. callq _read_int
  2640. movq %rax, %rcx
  2641. cmpq $1, %rcx
  2642. sete %al
  2643. movzbq %al, %rcx
  2644. cmpq $0, %rcx
  2645. je else1326
  2646. movq $42, %rbx
  2647. jmp if_end1327
  2648. else1326:
  2649. movq $0, %rbx
  2650. if_end1327:
  2651. movq %rbx, %rax
  2652. addq $16, %rsp
  2653. popq %rbp
  2654. retq
  2655. \end{lstlisting}
  2656. \end{minipage}
  2657. \end{tabular}
  2658. \caption{Example compilation of an \key{if} expression to x86-64.}
  2659. \label{fig:if-example-x86}
  2660. \end{figure}
  2661. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2662. \chapter{Tuples and Garbage Collection}
  2663. \label{ch:tuples}
  2664. In this chapter we study the compilation of mutable tuples (called
  2665. vectors in Racket). Figure~\ref{fig:r3-syntax} defines the syntax for
  2666. $R_3$, which includes three new forms for creating a tuple, reading an
  2667. element of a tuple, and writing an element into a tuple. The following
  2668. program shows the usage of tuples in Racket. We create a 3-tuple
  2669. \code{t} and a 1-tuple. The 1-tuple is stored at index $2$ of the
  2670. 3-tuple, showing that tuples are first-class values. The element at
  2671. index $1$ of \code{t} is \code{\#t}, so the ``then'' branch is taken.
  2672. The element at index $0$ of \code{t} is $40$, to which we add the $2$,
  2673. the element at index $0$ of the 1-tuple.
  2674. \begin{lstlisting}
  2675. (program
  2676. (let ([t (vector 40 #t (vector 2))])
  2677. (if (vector-ref t 1)
  2678. (+ (vector-ref t 0)
  2679. (vector-ref (vector-ref t 2) 0))
  2680. 44)))
  2681. \end{lstlisting}
  2682. \marginpar{\scriptsize To do: interpreter for $R_3$ \\ --Jeremy}
  2683. \begin{figure}[tbp]
  2684. \centering
  2685. \fbox{
  2686. \begin{minipage}{0.96\textwidth}
  2687. \[
  2688. \begin{array}{lcl}
  2689. \Exp &::=& \ldots \mid (\key{vector}\;\Exp^{+}) \mid
  2690. (\key{vector-ref}\;\Exp\;\Exp) \\
  2691. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp)\\
  2692. R_3 &::=& (\key{program} \; \Exp)
  2693. \end{array}
  2694. \]
  2695. \end{minipage}
  2696. }
  2697. \caption{The $R_3$ language, an extension of $R_2$
  2698. (Figure~\ref{fig:r2-syntax}).}
  2699. \label{fig:r3-syntax}
  2700. \end{figure}
  2701. \[
  2702. \Type ::= \ldots \mid (\key{Vector}\;\Type^{+})
  2703. \]
  2704. \begin{figure}[tbp]
  2705. \begin{lstlisting}
  2706. (define primitives (set '+ '- 'eq? 'not 'read
  2707. 'vector 'vector-ref 'vector-set!))
  2708. (define (interp-op op)
  2709. (match op
  2710. ['+ fx+]
  2711. ['- (lambda (n) (fx- 0 n))]
  2712. ['eq? (lambda (v1 v2)
  2713. (cond [(or (and (fixnum? v1) (fixnum? v2))
  2714. (and (boolean? v1) (boolean? v2))
  2715. (and (vector? v1) (vector? v2)))
  2716. (eq? v1 v2)]))]
  2717. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  2718. ['read read-fixnum]
  2719. ['vector vector] ['vector-ref vector-ref]
  2720. ['vector-set! vector-set!]
  2721. [else (error 'interp-op "unknown operator")]))
  2722. (define (interp-R3 env)
  2723. (lambda (e)
  2724. (match e
  2725. ...
  2726. [`(,op ,args ...) #:when (set-member? primitives op)
  2727. (apply (interp-op op) (map (interp-R3 env) args))]
  2728. [else (error 'interp-R3 "unrecognized expression")]
  2729. )))
  2730. \end{lstlisting}
  2731. \caption{Interpreter for the $R_3$ language.}
  2732. \label{fig:interp-R3}
  2733. \end{figure}
  2734. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2735. \chapter{Functions}
  2736. \label{ch:functions}
  2737. This chapter studies the compilation of functions (aka. procedures) as
  2738. they appear in the C language. The syntax for function definitions and
  2739. function application (aka. function call) is shown in
  2740. Figure~\ref{fig:r4-syntax}, where we define the $R_4$ language.
  2741. Programs now start with zero or more function definitions. The
  2742. function names from these definitions are in-scope for the entire
  2743. program, including all other function definitions (so the ordering of
  2744. function definitions does not matter).
  2745. Functions are first-class in the sense that a function pointer is data
  2746. and can be stored in memory or passed as a parameter to another
  2747. function. Thus, we introduce a function type, written
  2748. \begin{lstlisting}
  2749. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  2750. \end{lstlisting}
  2751. for a function whose $n$ parameters have the types $\Type_1$ through
  2752. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  2753. these functions is that they are not lexically scoped. That is, the
  2754. only external entities that can be referenced from inside a function
  2755. body are other globally-defined functions. The syntax of $R_4$
  2756. prevents functions from being nested inside each other; they can only
  2757. be defined at the top level.
  2758. \begin{figure}[tbp]
  2759. \centering
  2760. \fbox{
  2761. \begin{minipage}{0.96\textwidth}
  2762. \[
  2763. \begin{array}{lcl}
  2764. \Type &::=& \ldots \mid (\Type^{*} \; \key{->}\; \Type) \\
  2765. \Exp &::=& \ldots \mid (\Exp \; \Exp^{*}) \\
  2766. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*} \key{:} \Type \; \Exp)) \\
  2767. R_4 &::=& (\key{program} \; \Def^{*} \; \Exp)
  2768. \end{array}
  2769. \]
  2770. \end{minipage}
  2771. }
  2772. \caption{The $R_4$ language, an extension of $R_3$
  2773. (Figure~\ref{fig:r3-syntax}).}
  2774. \label{fig:r4-syntax}
  2775. \end{figure}
  2776. The program in Figure~\ref{fig:r4-function-example} shows a
  2777. representative example of definition and using functions in $R_4$. We
  2778. define a function \code{map} that applies some other function \code{f}
  2779. to both elements of a 2-tuple and returns a new 2-tuple containing the
  2780. results. We also define a function \code{add1} that does what its name
  2781. suggests. The program then applies \code{map} to \code{add1} and
  2782. \code{(vector 0 41)}. The result is \code{(vector 1 42)}, from which
  2783. we return the \code{42}.
  2784. \begin{figure}[tbp]
  2785. \begin{lstlisting}
  2786. (program
  2787. (define (map [f : (Integer -> Integer)]
  2788. [v : (Vector Integer Integer)])
  2789. : (Vector Integer Integer)
  2790. (vector (f (vector-ref v 0))
  2791. (f (vector-ref v 1))))
  2792. (define (add1 [x : Integer]) : Integer
  2793. (+ x 1))
  2794. (vector-ref (map add1 (vector 0 41)) 1)
  2795. )
  2796. \end{lstlisting}
  2797. \caption{Example of using functions in $R_4$.}
  2798. \label{fig:r4-function-example}
  2799. \end{figure}
  2800. \section{Functions in x86}
  2801. The x86 architecture provides a few features to support the
  2802. implementation of functions. We have already seen that x86 provides
  2803. labels so that one can refer to the location of an instruction, as is
  2804. needed for jump instructions. Labels can also be used to mark the
  2805. beginning of the instructions for a function. Going further, we can
  2806. obtain the address of a label by using the \key{leaq} instruction and
  2807. \key{rip}-relative addressing. For example, the following puts the
  2808. address of the \code{add1} label into the \code{rbx} register.
  2809. \begin{lstlisting}
  2810. leaq add1(%rip), %rbx
  2811. \end{lstlisting}
  2812. In Sections~\ref{sec:x86-64} and \ref{sec:select-s0} we saw the use of
  2813. the \code{callq} instruction for jumping to a function as specified by
  2814. a label. The use of the instruction changes slightly if the function
  2815. is specified by an address in a register, that is, an \emph{indirect
  2816. function call}. The x86 syntax is to give the register name prefixed
  2817. with an asterisk.
  2818. \begin{lstlisting}
  2819. callq *%rbx
  2820. \end{lstlisting}
  2821. The x86 architecture does not directly support passing arguments to
  2822. functions; instead we use a combination of registers and stack
  2823. locations for passing arguments, following the conventions used by
  2824. \code{gcc} as described by \cite{Matz:2013aa}. Up to six arguments may
  2825. be passed in registers, using the registers \code{rdi}, \code{rsi},
  2826. \code{rdx}, \code{rcx}, \code{r8}, and \code{r9}. If there are more
  2827. than six arguments, then the rest must be placed on the stack, which
  2828. we call \emph{stack arguments}, which we discuss in the following
  2829. paragraphs. Continuing on the topic of registers, each function may
  2830. need to use all the registers for storing local variables, frame base
  2831. pointers, etc. so when we make a function call, we need to figure out
  2832. how the two functions can share the same register set without getting
  2833. in each others way. The convention for x86-64 is that the caller is
  2834. responsible freeing up some registers, the \emph{caller save
  2835. registers}, prior to the function call, and the callee is
  2836. responsible for saving and restoring some other registers, the
  2837. \emph{callee save registers}, before and after using them. The
  2838. caller save registers are
  2839. \begin{lstlisting}
  2840. rdx rcx rsi rdi r8 r9 r10 r11
  2841. \end{lstlisting}
  2842. while the callee save registers are
  2843. \begin{lstlisting}
  2844. rbx r12 r13 r14 r15
  2845. \end{lstlisting}
  2846. UNDER CONSTRUCTION
  2847. Recall from Section~\ref{sec:x86-64} that the stack is also used for
  2848. local variables, and that at the beginning of a function we move the
  2849. stack pointer \code{rsp} down to make room for them. To make
  2850. additional room for passing arguments, we shall move the stack pointer
  2851. even further down. We count how many stack arguments are needed for
  2852. each function call that occurs inside the body of the function and
  2853. take their max. Adding this number to the number of local variables
  2854. gives us how much the \code{rsp} should be moved at the beginning of
  2855. the function. In preparation for a function call, we offset from
  2856. \code{rsp} to set up the stack arguments. We put the first stack
  2857. argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and so on.
  2858. Upon calling the function, the stack arguments are retrieved by the
  2859. callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  2860. is the location of the first stack argument, \code{24(\%rbp)} is the
  2861. address of the second, and so on. Figure~\ref{fig:call-frames} shows
  2862. the layout of the caller and callee frames. Notice how important it is
  2863. that we correctly compute the maximum number of arguments needed for
  2864. function calls; if that number is too small then the arguments and
  2865. local variables will overlap in memory!
  2866. \begin{figure}[tbp]
  2867. \centering
  2868. \begin{tabular}{r|r|l|l} \hline
  2869. Caller View & Callee View & Contents & Frame \\ \hline
  2870. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  2871. 0(\key{\%rbp}) & & old \key{rbp} \\
  2872. -8(\key{\%rbp}) & & variable $1$ \\
  2873. \ldots & & \ldots \\
  2874. $-8k$(\key{\%rbp}) & & variable $k$ \\
  2875. & & \\
  2876. $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  2877. & \ldots & \ldots \\
  2878. 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\ \hline
  2879. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  2880. & 0(\key{\%rbp}) & old \key{rbp} \\
  2881. & -8(\key{\%rbp}) & variable $1$ \\
  2882. & \ldots & \ldots \\
  2883. & $-8m$(\key{\%rsp}) & variable $m$\\ \hline
  2884. \end{tabular}
  2885. \caption{Memory layout of caller and callee frames.}
  2886. \label{fig:call-frames}
  2887. \end{figure}
  2888. % reveal-functions
  2889. % * differentiate variables and function names
  2890. % * differentiate primitive operations and function application
  2891. %
  2892. % flatten
  2893. % * function-ref not simple, why? have to use the leaq instruction
  2894. % to put the function label in to a register.
  2895. %
  2896. % select-instructions
  2897. % * function defs. deal with parameters
  2898. % * (assign lhs (function-ref f)) => (leaq (function-ref f) lhs)
  2899. % * (assign lhs (app f es ...))
  2900. % - pass some args in registers, rest on the stack (stack-arg)
  2901. % - need to keep track of how large the stack needs to grow across
  2902. % all the function calls in the body of a function
  2903. % - indirect-callq f; movq rax lhs
  2904. %
  2905. % uncover-live
  2906. % * free-vars: function-ref, stack-arg
  2907. % * read-vars: leaq, indirect-callq
  2908. % * write-vars: leaq, indirect-callq (all caller save!)
  2909. % * uncover-live: treat functions like the main program.
  2910. %
  2911. % build interferece:
  2912. % * treat functions like the main function
  2913. %
  2914. % assign-homes
  2915. % * add cases for: stack, stack-arg, indirect-callq, function-ref
  2916. %
  2917. % allocate-registers
  2918. % * treat functions like the main function
  2919. %
  2920. % patch-instructions
  2921. % * add cases for: function defs, indirect-callq, leaq (target must be reg.)
  2922. %
  2923. % print-x86
  2924. % * function-ref uses rip
  2925. % * indirect-callq => callq *
  2926. % * stack-arg => rsp
  2927. % * function defs: save and restore callee-save registers
  2928. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2929. \chapter{Lexically Scoped Functions}
  2930. \label{ch:lambdas}
  2931. \begin{figure}[tbp]
  2932. \centering
  2933. \fbox{
  2934. \begin{minipage}{0.96\textwidth}
  2935. \[
  2936. \begin{array}{lcl}
  2937. \Exp &::=& \ldots \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*} \key{:} \Type \; \Exp)) \\
  2938. R_5 &::=& (\key{program} \; \Def^{*} \; \Exp)
  2939. \end{array}
  2940. \]
  2941. \end{minipage}
  2942. }
  2943. \caption{The $R_5$ language, an extension of $R_4$
  2944. (Figure~\ref{fig:r4-syntax}).}
  2945. \label{fig:r5-syntax}
  2946. \end{figure}
  2947. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2948. %\chapter{Mutable Data}
  2949. %\label{ch:mutable-data}
  2950. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2951. \chapter{Dynamic Typing}
  2952. \label{ch:type-dynamic}
  2953. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2954. \chapter{Parametric Polymorphism}
  2955. \label{ch:parametric-polymorphism}
  2956. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2957. \chapter{High-level Optimization}
  2958. \label{ch:high-level-optimization}
  2959. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2960. \chapter{Appendix}
  2961. \section{Interpreters}
  2962. \label{appendix:interp}
  2963. We provide several interpreters in the \key{interp.rkt} file. The
  2964. \key{interp-scheme} function takes an AST in one of the Racket-like
  2965. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  2966. the program, returning the result value. The \key{interp-C} function
  2967. interprets an AST for a program in one of the C-like languages ($C_0,
  2968. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  2969. for an x86-64 program.
  2970. \section{Utility Functions}
  2971. \label{appendix:utilities}
  2972. The utility function described in this section can be found in the
  2973. \key{utilities.rkt} file.
  2974. The \key{assert} function displays the error message \key{msg} if the
  2975. Boolean \key{bool} is false.
  2976. \begin{lstlisting}
  2977. (define (assert msg bool) ...)
  2978. \end{lstlisting}
  2979. The \key{lookup} function ...
  2980. The \key{map2} function ...
  2981. The \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2982. functions...
  2983. The \key{interp-tests} function takes a compiler name (a string) a
  2984. description of the passes a test family name (a string), and a list of
  2985. test numbers, and runs the compiler passes and the interpreters to
  2986. check whether the passes correct. The description of the passes is a
  2987. list with one entry per pass. An entry is a list with three things: a
  2988. string giving the name of the pass, the function that implements the
  2989. pass (a translator from AST to AST), and a function that implements
  2990. the interpreter (a function from AST to result value). The
  2991. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  2992. The \key{interp-tests} function assumes that the subdirectory
  2993. \key{tests} has a bunch of Scheme programs whose names all start with
  2994. the family name, followed by an underscore and then the test number,
  2995. ending in \key{.scm}. Also, for each Scheme program there is a file
  2996. with the same number except that it ends with \key{.in} that provides
  2997. the input for the Scheme program.
  2998. \begin{lstlisting}
  2999. (define (interp-tests name passes test-family test-nums) ...
  3000. \end{lstlisting}
  3001. The compiler-tests function takes a compiler name (a string) a
  3002. description of the passes (see the comment for \key{interp-tests}) a
  3003. test family name (a string), and a list of test numbers (see the
  3004. comment for interp-tests), and runs the compiler to generate x86-64 (a
  3005. \key{.s} file) and then runs gcc to generate machine code. It runs
  3006. the machine code and checks that the output is 42.
  3007. \begin{lstlisting}
  3008. (define (compiler-tests name passes test-family test-nums) ...)
  3009. \end{lstlisting}
  3010. The compile-file function takes a description of the compiler passes
  3011. (see the comment for \key{interp-tests}) and returns a function that,
  3012. given a program file name (a string ending in \key{.scm}), applies all
  3013. of the passes and writes the output to a file whose name is the same
  3014. as the program file name but with \key{.scm} replaced with \key{.s}.
  3015. \begin{lstlisting}
  3016. (define (compile-file passes)
  3017. (lambda (prog-file-name) ...))
  3018. \end{lstlisting}
  3019. \bibliographystyle{plainnat}
  3020. \bibliography{all}
  3021. \end{document}
  3022. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  3023. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  3024. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  3025. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  3026. %% LocalWords: ast sexp Reynold's reynolds interp cond fx evaluator
  3027. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  3028. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  3029. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  3030. %% LocalWords: allocator gensym alist subdirectory scm rkt tmp lhs
  3031. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  3032. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  3033. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  3034. %% LocalWords: boolean typecheck andq notq cmpq sete movzbq jmp al
  3035. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples
  3036. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums