book.tex 136 KB

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