book.tex 150 KB

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