book.tex 139 KB

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