book.tex 537 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM!, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  12. %% * exceptions
  13. %% * self hosting
  14. %% * I/O
  15. %% * foreign function interface
  16. %% * quasi-quote and unquote
  17. %% * macros (too difficult?)
  18. %% * alternative garbage collector
  19. %% * alternative register allocator
  20. %% * type classes
  21. %% * loop optimization (fusion, etc.)
  22. %% * deforestation
  23. %% * records with subtyping
  24. %% * object-oriented features
  25. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  26. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  27. %% * multi-threading, fork join, futures, implicit parallelism
  28. %% * type analysis and specialization
  29. \documentclass[11pt]{book}
  30. \usepackage[T1]{fontenc}
  31. \usepackage[utf8]{inputenc}
  32. \usepackage{lmodern}
  33. \usepackage{hyperref}
  34. \usepackage{graphicx}
  35. \usepackage[english]{babel}
  36. \usepackage{listings}
  37. \usepackage{amsmath}
  38. \usepackage{amsthm}
  39. \usepackage{amssymb}
  40. \usepackage[numbers]{natbib}
  41. \usepackage{stmaryrd}
  42. \usepackage{xypic}
  43. \usepackage{semantic}
  44. \usepackage{wrapfig}
  45. \usepackage{tcolorbox}
  46. \usepackage{multirow}
  47. \usepackage{color}
  48. \usepackage{upquote}
  49. \usepackage{makeidx}
  50. \makeindex
  51. \definecolor{lightgray}{gray}{1}
  52. \newcommand{\black}[1]{{\color{black} #1}}
  53. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  54. \newcommand{\gray}[1]{{\color{gray} #1}}
  55. %% For pictures
  56. \usepackage{tikz}
  57. \usetikzlibrary{arrows.meta}
  58. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  59. % Computer Modern is already the default. -Jeremy
  60. %\renewcommand{\ttdefault}{cmtt}
  61. \definecolor{comment-red}{rgb}{0.8,0,0}
  62. \if01
  63. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  64. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  65. \else
  66. \newcommand{\rn}[1]{}
  67. \newcommand{\margincomment}[1]{}
  68. \fi
  69. \lstset{%
  70. language=Lisp,
  71. basicstyle=\ttfamily\small,
  72. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  73. deletekeywords={read,mapping,vector},
  74. escapechar=|,
  75. columns=flexible,
  76. moredelim=[is][\color{red}]{~}{~},
  77. showstringspaces=false
  78. }
  79. \newtheorem{theorem}{Theorem}
  80. \newtheorem{lemma}[theorem]{Lemma}
  81. \newtheorem{corollary}[theorem]{Corollary}
  82. \newtheorem{proposition}[theorem]{Proposition}
  83. \newtheorem{constraint}[theorem]{Constraint}
  84. \newtheorem{definition}[theorem]{Definition}
  85. \newtheorem{exercise}[theorem]{Exercise}
  86. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  87. % 'dedication' environment: To add a dedication paragraph at the start of book %
  88. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. \newenvironment{dedication}
  91. {
  92. \cleardoublepage
  93. \thispagestyle{empty}
  94. \vspace*{\stretch{1}}
  95. \hfill\begin{minipage}[t]{0.66\textwidth}
  96. \raggedright
  97. }
  98. {
  99. \end{minipage}
  100. \vspace*{\stretch{3}}
  101. \clearpage
  102. }
  103. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  104. % Chapter quote at the start of chapter %
  105. % Source: http://tex.stackexchange.com/a/53380 %
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. \makeatletter
  108. \renewcommand{\@chapapp}{}% Not necessary...
  109. \newenvironment{chapquote}[2][2em]
  110. {\setlength{\@tempdima}{#1}%
  111. \def\chapquote@author{#2}%
  112. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  113. \itshape}
  114. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  115. \makeatother
  116. \input{defs}
  117. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  118. \title{\Huge \textbf{Essentials of Compilation} \\
  119. \huge The Incremental, Nano-Pass Approach}
  120. \author{\textsc{Jeremy G. Siek} \\
  121. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  122. Indiana University \\
  123. \\
  124. with contributions from: \\
  125. Carl Factora \\
  126. Andre Kuhlenschmidt \\
  127. Ryan R. Newton \\
  128. Ryan Scott \\
  129. Cameron Swords \\
  130. Michael M. Vitousek \\
  131. Michael Vollmer
  132. }
  133. \begin{document}
  134. \frontmatter
  135. \maketitle
  136. \begin{dedication}
  137. This book is dedicated to the programming language wonks at Indiana
  138. University.
  139. \end{dedication}
  140. \tableofcontents
  141. \listoffigures
  142. %\listoftables
  143. \mainmatter
  144. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  145. \chapter*{Preface}
  146. There is a magical moment when a programmer presses the ``run'' button
  147. and the software begins to execute. Somehow a program written in a
  148. high-level language is running on a computer that is only capable of
  149. shuffling bits. This book reveals the wizardry that makes that moment
  150. possible. Beginning with the groundbreaking work of Backus and
  151. colleagues in the 1950s, computer scientists discovered techniques for
  152. constructing programs, called \emph{compilers}, that automatically
  153. translate high-level programs into machine code.
  154. This book guides the reader on the journey of constructing their own
  155. compiler for a small but powerful language. Along the way the reader
  156. learns the essential concepts, algorithms, and data structures that
  157. underlie modern compilers. They develop an understanding of how
  158. programs are mapped onto computer hardware which is helpful when
  159. reasoning about execution time, debugging errors across layers of the
  160. software stack, and finding security vulnerabilities.
  161. %
  162. For readers interested in a career in compiler construction, this book
  163. is a stepping-stone to advanced topics such as just-in-time
  164. compilation, program analysis, and program optimization.
  165. %
  166. For readers interested in the design of programming languages, this
  167. book connects language design choices to their impact on the compiler
  168. and generated code.
  169. A compiler is typically organized as a pipeline with a handful of
  170. passes that translate a program into ever lower levels of
  171. abstraction. We take this approach to the extreme by partitioning our
  172. compiler into a large number of \emph{nanopasses}, each of which
  173. performs a single task. This makes the compiler easier to debug,
  174. because we test the output of each pass, and it makes the compiler
  175. easier to understand, because each pass involves fewer concepts.
  176. Most books about compiler construction are structured like the
  177. compiler, with each chapter describing one pass. The problem with that
  178. structure is that it obfuscates how language features motivate design
  179. choices in the compiler. We take an \emph{incremental} approach in
  180. which we build a complete compiler in each chapter, starting with a
  181. tiny language and adding new features in subsequent chapters.
  182. Our choice of language features is designed to elicit the fundamental
  183. concepts and algorithms used in compilers for modern programming
  184. languages.
  185. \begin{itemize}
  186. \item We begin with integer arithmetic and local variables. The
  187. reader becomes acquainted with the basic tools of compiler
  188. construction, \emph{abstract syntax trees} and \emph{recursive
  189. functions}, in Chapter~\ref{ch:trees-recur} and applies them to a
  190. language with integers and variables in Chapter~\ref{ch:Rvar}. In
  191. Chapter~\ref{ch:register-allocation-Rvar} we apply \emph{graph
  192. coloring} to assign variables to registers.
  193. \item Chapter~\ref{ch:Rif} adds conditional control-flow, which
  194. motivates an elegant recursive algorithm for mapping expressions to
  195. \emph{control-flow graphs}.
  196. \item Chapter~\ref{ch:Rvec} adds heap-allocated tuples, motivating
  197. \emph{garbage collection}.
  198. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  199. but lack lexical scoping, similar to the C programming
  200. language~\citep{Kernighan:1988nx} except that we generate efficient
  201. tail calls. The reader learns about the procedure call stack,
  202. \emph{calling conventions}, and their interaction with register
  203. allocation and garbage collection.
  204. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  205. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  206. \emph{closure conversion}, in which lambdas are translated into a
  207. combination of functions and tuples.
  208. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  209. point the input languages are statically typed. The reader extends
  210. the statically typed language with an \code{Any} type which serves
  211. as a target for compiling the dynamically typed language.
  212. \item Chapter~\ref{ch:Rwhile} fleshes out support for imperative
  213. programming languages with the addition of loops and mutable
  214. variables. These additions elicit the need for \emph{dataflow
  215. analysis} in the register allocator.
  216. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  217. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  218. in which different regions of a program may be static or dynamically
  219. typed. The reader implements runtime support for \emph{proxies} that
  220. allow values to safely move between regions.
  221. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  222. leveraging the \code{Any} type and type casts developed in Chapters
  223. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  224. \end{itemize}
  225. There are many language features that we do not include. Our choices
  226. weigh the incidental complexity of a feature against the fundamental
  227. concepts that it exposes. For example, we include tuples and not
  228. records because they both elicit the study of heap allocation and
  229. garbage collection but records come with more incidental complexity.
  230. Since 2016 this book has served as the textbook for the compiler
  231. course at Indiana University, a 16-week course for upper-level
  232. undergraduates and first-year graduate students.
  233. %
  234. Prior to this course, students learn to program in both imperative and
  235. functional languages, study data structures and algorithms, and take
  236. discrete mathematics.
  237. %
  238. At the beginning of the course, students form groups of 2-4 people.
  239. The groups complete one chapter every two weeks, starting with
  240. Chapter~\ref{ch:Rvar} and finishing with Chapter~\ref{ch:Rdyn}. Many
  241. chapters include a challenge problem that we assign to the graduate
  242. students. The last two weeks of the course involve a final project in
  243. which students design and implement a compiler extension of their
  244. choosing. Chapters~\ref{ch:Rwhile}, \ref{ch:Rgrad}, and
  245. \ref{ch:Rpoly} can be used in support of these projects or they can
  246. replace some of the earlier chapters. For example, a course with an
  247. emphasis on statically-typed imperative languages would skip
  248. Chapter~\ref{ch:Rdyn} in favor of
  249. Chapter~\ref{ch:Rwhile}. Figure~\ref{fig:chapter-dependences} depicts
  250. the dependencies between chapters.
  251. This book has also been used in compiler courses at California
  252. Polytechnic State University, Rose–Hulman Institute of Technology, and
  253. University of Massachusetts Lowell.
  254. \begin{figure}[tp]
  255. \begin{tikzpicture}[baseline=(current bounding box.center)]
  256. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  257. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Rvar} Variables};
  258. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Rvar} Registers};
  259. \node (C4) at (0,0) {\small Ch.~\ref{ch:Rif} Control Flow};
  260. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  261. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  262. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  263. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  264. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  265. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual};
  266. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  267. \path[->] (C1) edge [above] node {} (C2);
  268. \path[->] (C2) edge [above] node {} (C3);
  269. \path[->] (C3) edge [above] node {} (C4);
  270. \path[->] (C4) edge [above] node {} (C5);
  271. \path[->] (C5) edge [above] node {} (C6);
  272. \path[->] (C6) edge [above] node {} (C7);
  273. \path[->] (C4) edge [above] node {} (C8);
  274. \path[->] (C4) edge [above] node {} (C9);
  275. \path[->] (C8) edge [above] node {} (C10);
  276. \path[->] (C10) edge [above] node {} (C11);
  277. \end{tikzpicture}
  278. \caption{Diagram of chapter dependencies.}
  279. \label{fig:chapter-dependences}
  280. \end{figure}
  281. We use the \href{https://racket-lang.org/}{Racket} language both for
  282. the implementation of the compiler and for the input language, so the
  283. reader should be proficient with Racket or Scheme. There are many
  284. excellent resources for learning Scheme and
  285. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. The
  286. support code for this book is in the \code{github} repository at the
  287. following URL:
  288. \begin{center}\small
  289. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  290. \end{center}
  291. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  292. is helpful but not necessary for the reader to have taken a computer
  293. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  294. of x86-64 assembly language that are needed.
  295. %
  296. We follow the System V calling
  297. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  298. that we generate works with the runtime system (written in C) when it
  299. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  300. operating systems.
  301. %
  302. On the Windows operating system, \code{gcc} uses the Microsoft x64
  303. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  304. assembly code that we generate does \emph{not} work with the runtime
  305. system on Windows. One workaround is to use a virtual machine with
  306. Linux as the guest operating system.
  307. % TODO: point to support code on github
  308. %% The tradition of compiler writing at Indiana University goes back to
  309. %% research and courses on programming languages by Professor Daniel
  310. %% Friedman in the 1970's and 1980's. Friedman conducted research on lazy
  311. %% evaluation~\citep{Friedman:1976aa} in the context of
  312. %% Lisp~\citep{McCarthy:1960dz} and then studied
  313. %% continuations~\citep{Felleisen:kx} and
  314. %% macros~\citep{Kohlbecker:1986dk} in the context of the
  315. %% Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  316. %% of those courses, Kent Dybvig, went on to build Chez
  317. %% Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  318. %% compiler for Scheme. After completing his Ph.D. at the University of
  319. %% North Carolina, he returned to teach at Indiana University.
  320. %% Throughout the 1990's and 2000's, Professor Dybvig continued
  321. %% development of Chez Scheme and taught the compiler course.
  322. %% The compiler course evolved to incorporate novel pedagogical ideas
  323. %% while also including elements of effective real-world compilers. One
  324. %% of Friedman's ideas was to split the compiler into many small
  325. %% ``passes'' so that the code for each pass would be easy to understood
  326. %% in isolation. In contrast, most compilers of the time were organized
  327. %% into only a few monolithic passes for reasons of compile-time
  328. %% efficiency. Another idea, called ``the game'', was to test the code
  329. %% generated by each pass on interpreters for each intermediate language,
  330. %% thereby helping to pinpoint errors in individual passes.
  331. %% %
  332. %% Dybvig, with later help from his students Dipanwita Sarkar and Andrew
  333. %% Keep, developed infrastructure to support this approach and evolved
  334. %% the course, first to use smaller micro-passes and then into even
  335. %% smaller nano-passes~\citep{Sarkar:2004fk,Keep:2012aa}. I was a student
  336. %% in this compiler course in the early 2000's as part of my
  337. %% Ph.D. studies at Indiana University. Needless to say, I enjoyed the
  338. %% course immensely!
  339. %% During that time, another graduate student named Abdulaziz Ghuloum
  340. %% observed that the front-to-back organization of the course made it
  341. %% difficult for students to understand the rationale for the compiler
  342. %% design. Ghuloum proposed an incremental approach in which the students
  343. %% start by implementing a complete compiler for a very small subset of
  344. %% the language. In each subsequent stage they add a feature to the
  345. %% language and then add or modify passes to handle the new
  346. %% feature~\citep{Ghuloum:2006bh}. In this way, the students see how the
  347. %% language features motivate aspects of the compiler design.
  348. %% After graduating from Indiana University in 2005, I went on to teach
  349. %% at the University of Colorado. I adapted the nano-pass and incremental
  350. %% approaches to compiling a subset of the Python
  351. %% language~\citep{Siek:2012ab}.
  352. %% %% Python and Scheme are quite different
  353. %% %% on the surface but there is a large overlap in the compiler techniques
  354. %% %% required for the two languages. Thus, I was able to teach much of the
  355. %% %% same content from the Indiana compiler course.
  356. %% I very much enjoyed teaching the course organized in this way, and
  357. %% even better, many of the students learned a lot and got excited about
  358. %% compilers.
  359. %% I returned to Indiana University in 2013. In my absence the compiler
  360. %% course had switched from the front-to-back organization to a
  361. %% back-to-front~\citep{Dybvig:2010aa}. While that organization also works
  362. %% well, I prefer the incremental approach and started porting and
  363. %% adapting the structure of the Colorado course back into the land of
  364. %% Scheme. In the meantime Indiana University had moved on from Scheme to
  365. %% Racket~\citep{plt-tr}, so the course is now about compiling a subset
  366. %% of Racket (and Typed Racket) to the x86 assembly language.
  367. %% This is the textbook for the incremental version of the compiler
  368. %% course at Indiana University (Spring 2016 - present). With this book
  369. %% I hope to make the Indiana compiler course available to people that
  370. %% have not had the chance to study compilers at Indiana University.
  371. %% %% I have captured what
  372. %% %% I think are the most important topics from \cite{Dybvig:2010aa} but
  373. %% %% have omitted topics that are less interesting conceptually. I have
  374. %% %% also made simplifications to reduce complexity. In this way, this
  375. %% %% book leans more towards pedagogy than towards the efficiency of the
  376. %% %% generated code. Also, the book differs in places where we I the
  377. %% %% opportunity to make the topics more fun, such as in relating register
  378. %% %% allocation to Sudoku (Chapter~\ref{ch:register-allocation-Rvar}).
  379. %% \section*{Prerequisites}
  380. %% The material in this book is challenging but rewarding. It is meant to
  381. %% prepare students for a lifelong career in programming languages.
  382. %% %\section*{Structure of book}
  383. %% % You might want to add short description about each chapter in this book.
  384. %% %\section*{About the companion website}
  385. %% %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  386. %% %\begin{itemize}
  387. %% % \item A link to (freely downlodable) latest version of this document.
  388. %% % \item Link to download LaTeX source for this document.
  389. %% % \item Miscellaneous material (e.g. suggested readings etc).
  390. %% %\end{itemize}
  391. \section*{Acknowledgments}
  392. The tradition of compiler construction at Indiana University goes back
  393. to research and courses on programming languages by Daniel Friedman in
  394. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  395. Chez Scheme~\citep{Dybvig:2006aa}, a production-quality, efficient
  396. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  397. the compiler course and continued the development of Chez Scheme.
  398. %
  399. The compiler course evolved to incorporate novel pedagogical ideas
  400. while also including elements of efficient real-world compilers. One
  401. of Friedman's ideas was to split the compiler into many small
  402. passes. Another idea, called ``the game'', was to test the code
  403. generated by each pass on interpreters.
  404. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  405. developed infrastructure to support this approach and evolved the
  406. course to use even smaller
  407. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  408. design decisions in this book are inspired by the assignment
  409. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  410. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  411. organization of the course made it difficult for students to
  412. understand the rationale for the compiler design. Ghuloum proposed the
  413. incremental approach~\citep{Ghuloum:2006bh}.
  414. We thank Bor-Yuh Chang, John Clements, Jay McCarthy, Nate Nystrom, and
  415. Michael Wollowski for teaching courses based on early drafts.
  416. We thank Ronald Garcia for being Jeremy's partner when they took the
  417. compiler course in the early 2000's, especially for finding the bug
  418. that was send the garbage collector on a wild goose chase!
  419. %Oscar Waddell ??
  420. \mbox{}\\
  421. \noindent Jeremy G. Siek \\
  422. Bloomington, Indiana
  423. %\noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  424. %\noindent Spring 2016
  425. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  426. \chapter{Preliminaries}
  427. \label{ch:trees-recur}
  428. In this chapter we review the basic tools that are needed to implement
  429. a compiler. Programs are typically input by a programmer as text,
  430. i.e., a sequence of characters. The program-as-text representation is
  431. called \emph{concrete syntax}. We use concrete syntax to concisely
  432. write down and talk about programs. Inside the compiler, we use
  433. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  434. that efficiently supports the operations that the compiler needs to
  435. perform.\index{concrete syntax}\index{abstract syntax}\index{abstract
  436. syntax tree}\index{AST}\index{program}\index{parse} The translation
  437. from concrete syntax to abstract syntax is a process called
  438. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  439. implementation of parsing in this book. A parser is provided in the
  440. support code for translating from concrete to abstract syntax.
  441. ASTs can be represented in many different ways inside the compiler,
  442. depending on the programming language used to write the compiler.
  443. %
  444. We use Racket's
  445. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  446. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  447. define the abstract syntax of programming languages
  448. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  449. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  450. recursive functions to construct and deconstruct ASTs
  451. (Section~\ref{sec:recursion}). This chapter provides an brief
  452. introduction to these ideas. \index{struct}
  453. \section{Abstract Syntax Trees and Racket Structures}
  454. \label{sec:ast}
  455. Compilers use abstract syntax trees to represent programs because they
  456. often need to ask questions like: for a given part of a program, what
  457. kind of language feature is it? What are its sub-parts? Consider the
  458. program on the left and its AST on the right. This program is an
  459. addition operation and it has two sub-parts, a read operation and a
  460. negation. The negation has another sub-part, the integer constant
  461. \code{8}. By using a tree to represent the program, we can easily
  462. follow the links to go from one part of a program to its sub-parts.
  463. \begin{center}
  464. \begin{minipage}{0.4\textwidth}
  465. \begin{lstlisting}
  466. (+ (read) (- 8))
  467. \end{lstlisting}
  468. \end{minipage}
  469. \begin{minipage}{0.4\textwidth}
  470. \begin{equation}
  471. \begin{tikzpicture}
  472. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  473. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  474. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  475. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  476. \draw[->] (plus) to (read);
  477. \draw[->] (plus) to (minus);
  478. \draw[->] (minus) to (8);
  479. \end{tikzpicture}
  480. \label{eq:arith-prog}
  481. \end{equation}
  482. \end{minipage}
  483. \end{center}
  484. We use the standard terminology for trees to describe ASTs: each
  485. circle above is called a \emph{node}. The arrows connect a node to its
  486. \emph{children} (which are also nodes). The top-most node is the
  487. \emph{root}. Every node except for the root has a \emph{parent} (the
  488. node it is the child of). If a node has no children, it is a
  489. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  490. \index{node}
  491. \index{children}
  492. \index{root}
  493. \index{parent}
  494. \index{leaf}
  495. \index{internal node}
  496. %% Recall that an \emph{symbolic expression} (S-expression) is either
  497. %% \begin{enumerate}
  498. %% \item an atom, or
  499. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  500. %% where $e_1$ and $e_2$ are each an S-expression.
  501. %% \end{enumerate}
  502. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  503. %% null value \code{'()}, etc. We can create an S-expression in Racket
  504. %% simply by writing a backquote (called a quasi-quote in Racket)
  505. %% followed by the textual representation of the S-expression. It is
  506. %% quite common to use S-expressions to represent a list, such as $a, b
  507. %% ,c$ in the following way:
  508. %% \begin{lstlisting}
  509. %% `(a . (b . (c . ())))
  510. %% \end{lstlisting}
  511. %% Each element of the list is in the first slot of a pair, and the
  512. %% second slot is either the rest of the list or the null value, to mark
  513. %% the end of the list. Such lists are so common that Racket provides
  514. %% special notation for them that removes the need for the periods
  515. %% and so many parenthesis:
  516. %% \begin{lstlisting}
  517. %% `(a b c)
  518. %% \end{lstlisting}
  519. %% The following expression creates an S-expression that represents AST
  520. %% \eqref{eq:arith-prog}.
  521. %% \begin{lstlisting}
  522. %% `(+ (read) (- 8))
  523. %% \end{lstlisting}
  524. %% When using S-expressions to represent ASTs, the convention is to
  525. %% represent each AST node as a list and to put the operation symbol at
  526. %% the front of the list. The rest of the list contains the children. So
  527. %% in the above case, the root AST node has operation \code{`+} and its
  528. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  529. %% diagram \eqref{eq:arith-prog}.
  530. %% To build larger S-expressions one often needs to splice together
  531. %% several smaller S-expressions. Racket provides the comma operator to
  532. %% splice an S-expression into a larger one. For example, instead of
  533. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  534. %% we could have first created an S-expression for AST
  535. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  536. %% S-expression.
  537. %% \begin{lstlisting}
  538. %% (define ast1.4 `(- 8))
  539. %% (define ast1.1 `(+ (read) ,ast1.4))
  540. %% \end{lstlisting}
  541. %% In general, the Racket expression that follows the comma (splice)
  542. %% can be any expression that produces an S-expression.
  543. We define a Racket \code{struct} for each kind of node. For this
  544. chapter we require just two kinds of nodes: one for integer constants
  545. and one for primitive operations. The following is the \code{struct}
  546. definition for integer constants.
  547. \begin{lstlisting}
  548. (struct Int (value))
  549. \end{lstlisting}
  550. An integer node includes just one thing: the integer value.
  551. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  552. \begin{lstlisting}
  553. (define eight (Int 8))
  554. \end{lstlisting}
  555. We say that the value created by \code{(Int 8)} is an
  556. \emph{instance} of the \code{Int} structure.
  557. The following is the \code{struct} definition for primitives operations.
  558. \begin{lstlisting}
  559. (struct Prim (op args))
  560. \end{lstlisting}
  561. A primitive operation node includes an operator symbol \code{op}
  562. and a list of children \code{args}. For example, to create
  563. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  564. \begin{lstlisting}
  565. (define neg-eight (Prim '- (list eight)))
  566. \end{lstlisting}
  567. Primitive operations may have zero or more children. The \code{read}
  568. operator has zero children:
  569. \begin{lstlisting}
  570. (define rd (Prim 'read '()))
  571. \end{lstlisting}
  572. whereas the addition operator has two children:
  573. \begin{lstlisting}
  574. (define ast1.1 (Prim '+ (list rd neg-eight)))
  575. \end{lstlisting}
  576. We have made a design choice regarding the \code{Prim} structure.
  577. Instead of using one structure for many different operations
  578. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  579. structure for each operation, as follows.
  580. \begin{lstlisting}
  581. (struct Read ())
  582. (struct Add (left right))
  583. (struct Neg (value))
  584. \end{lstlisting}
  585. The reason we choose to use just one structure is that in many parts
  586. of the compiler the code for the different primitive operators is the
  587. same, so we might as well just write that code once, which is enabled
  588. by using a single structure.
  589. When compiling a program such as \eqref{eq:arith-prog}, we need to
  590. know that the operation associated with the root node is addition and
  591. we need to be able to access its two children. Racket provides pattern
  592. matching to support these kinds of queries, as we see in
  593. Section~\ref{sec:pattern-matching}.
  594. In this book, we often write down the concrete syntax of a program
  595. even when we really have in mind the AST because the concrete syntax
  596. is more concise. We recommend that, in your mind, you always think of
  597. programs as abstract syntax trees.
  598. \section{Grammars}
  599. \label{sec:grammar}
  600. \index{integer}
  601. \index{literal}
  602. \index{constant}
  603. A programming language can be thought of as a \emph{set} of programs.
  604. The set is typically infinite (one can always create larger and larger
  605. programs), so one cannot simply describe a language by listing all of
  606. the programs in the language. Instead we write down a set of rules, a
  607. \emph{grammar}, for building programs. Grammars are often used to
  608. define the concrete syntax of a language, but they can also be used to
  609. describe the abstract syntax. We write our rules in a variant of
  610. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  611. \index{Backus-Naur Form}\index{BNF}
  612. As an example, we describe a small language, named \LangInt{}, that consists of
  613. integers and arithmetic operations.
  614. \index{grammar}
  615. The first grammar rule for the abstract syntax of \LangInt{} says that an
  616. instance of the \code{Int} structure is an expression:
  617. \begin{equation}
  618. \Exp ::= \INT{\Int} \label{eq:arith-int}
  619. \end{equation}
  620. %
  621. Each rule has a left-hand-side and a right-hand-side. The way to read
  622. a rule is that if you have an AST node that matches the
  623. right-hand-side, then you can categorize it according to the
  624. left-hand-side.
  625. %
  626. A name such as $\Exp$ that is defined by the grammar rules is a
  627. \emph{non-terminal}. \index{non-terminal}
  628. %
  629. The name $\Int$ is a also a non-terminal, but instead of defining it
  630. with a grammar rule, we define it with the following explanation. We
  631. make the simplifying design decision that all of the languages in this
  632. book only handle machine-representable integers. On most modern
  633. machines this corresponds to integers represented with 64-bits, i.e.,
  634. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  635. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  636. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  637. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  638. that the sequence of decimals represent an integer in range $-2^{62}$
  639. to $2^{62}-1$.
  640. The second grammar rule is the \texttt{read} operation that receives
  641. an input integer from the user of the program.
  642. \begin{equation}
  643. \Exp ::= \READ{} \label{eq:arith-read}
  644. \end{equation}
  645. The third rule says that, given an $\Exp$ node, the negation of that
  646. node is also an $\Exp$.
  647. \begin{equation}
  648. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  649. \end{equation}
  650. Symbols in typewriter font such as \key{-} and \key{read} are
  651. \emph{terminal} symbols and must literally appear in the program for
  652. the rule to be applicable.
  653. \index{terminal}
  654. We can apply these rules to categorize the ASTs that are in the
  655. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  656. \texttt{(Int 8)} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  657. following AST is an $\Exp$.
  658. \begin{center}
  659. \begin{minipage}{0.4\textwidth}
  660. \begin{lstlisting}
  661. (Prim '- (list (Int 8)))
  662. \end{lstlisting}
  663. \end{minipage}
  664. \begin{minipage}{0.25\textwidth}
  665. \begin{equation}
  666. \begin{tikzpicture}
  667. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  668. \node[draw, circle] (8) at (0, -1.2) {$8$};
  669. \draw[->] (minus) to (8);
  670. \end{tikzpicture}
  671. \label{eq:arith-neg8}
  672. \end{equation}
  673. \end{minipage}
  674. \end{center}
  675. The next grammar rule is for addition expressions:
  676. \begin{equation}
  677. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  678. \end{equation}
  679. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  680. \LangInt{}. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  681. \eqref{eq:arith-read} and we have already categorized \code{(Prim '-
  682. (list (Int 8)))} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  683. to show that
  684. \begin{lstlisting}
  685. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  686. \end{lstlisting}
  687. is an $\Exp$ in the \LangInt{} language.
  688. If you have an AST for which the above rules do not apply, then the
  689. AST is not in \LangInt{}. For example, the program \code{(- (read) (+ 8))}
  690. is not in \LangInt{} because there are no rules for \code{+} with only one
  691. argument, nor for \key{-} with two arguments. Whenever we define a
  692. language with a grammar, the language only includes those programs
  693. that are justified by the rules.
  694. The last grammar rule for \LangInt{} states that there is a \code{Program}
  695. node to mark the top of the whole program:
  696. \[
  697. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  698. \]
  699. The \code{Program} structure is defined as follows
  700. \begin{lstlisting}
  701. (struct Program (info body))
  702. \end{lstlisting}
  703. where \code{body} is an expression. In later chapters, the \code{info}
  704. part will be used to store auxiliary information but for now it is
  705. just the empty list.
  706. It is common to have many grammar rules with the same left-hand side
  707. but different right-hand sides, such as the rules for $\Exp$ in the
  708. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  709. combine several right-hand-sides into a single rule.
  710. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  711. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  712. defined in Figure~\ref{fig:r0-concrete-syntax}.
  713. The \code{read-program} function provided in \code{utilities.rkt} of
  714. the support code reads a program in from a file (the sequence of
  715. characters in the concrete syntax of Racket) and parses it into an
  716. abstract syntax tree. See the description of \code{read-program} in
  717. Appendix~\ref{appendix:utilities} for more details.
  718. \begin{figure}[tp]
  719. \fbox{
  720. \begin{minipage}{0.96\textwidth}
  721. \[
  722. \begin{array}{rcl}
  723. \begin{array}{rcl}
  724. \Exp &::=& \Int \mid \LP\key{read}\RP \mid \LP\key{-}\;\Exp\RP \mid \LP\key{+} \; \Exp\;\Exp\RP\\
  725. \LangInt{} &::=& \Exp
  726. \end{array}
  727. \end{array}
  728. \]
  729. \end{minipage}
  730. }
  731. \caption{The concrete syntax of \LangInt{}.}
  732. \label{fig:r0-concrete-syntax}
  733. \end{figure}
  734. \begin{figure}[tp]
  735. \fbox{
  736. \begin{minipage}{0.96\textwidth}
  737. \[
  738. \begin{array}{rcl}
  739. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  740. &\mid& \ADD{\Exp}{\Exp} \\
  741. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  742. \end{array}
  743. \]
  744. \end{minipage}
  745. }
  746. \caption{The abstract syntax of \LangInt{}.}
  747. \label{fig:r0-syntax}
  748. \end{figure}
  749. \section{Pattern Matching}
  750. \label{sec:pattern-matching}
  751. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  752. the parts of an AST node. Racket provides the \texttt{match} form to
  753. access the parts of a structure. Consider the following example and
  754. the output on the right. \index{match} \index{pattern matching}
  755. \begin{center}
  756. \begin{minipage}{0.5\textwidth}
  757. \begin{lstlisting}
  758. (match ast1.1
  759. [(Prim op (list child1 child2))
  760. (print op)])
  761. \end{lstlisting}
  762. \end{minipage}
  763. \vrule
  764. \begin{minipage}{0.25\textwidth}
  765. \begin{lstlisting}
  766. '+
  767. \end{lstlisting}
  768. \end{minipage}
  769. \end{center}
  770. In the above example, the \texttt{match} form takes an AST
  771. \eqref{eq:arith-prog} and binds its parts to the three pattern
  772. variables \texttt{op}, \texttt{child1}, and \texttt{child2}, and then
  773. prints out the operator. In general, a match clause consists of a
  774. \emph{pattern} and a \emph{body}.\index{pattern} Patterns are
  775. recursively defined to be either a pattern variable, a structure name
  776. followed by a pattern for each of the structure's arguments, or an
  777. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  778. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  779. and Chapter 9 of The Racket
  780. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  781. for a complete description of \code{match}.)
  782. %
  783. The body of a match clause may contain arbitrary Racket code. The
  784. pattern variables can be used in the scope of the body, such as
  785. \code{op} in \code{(print op)}.
  786. A \code{match} form may contain several clauses, as in the following
  787. function \code{leaf?} that recognizes when an \LangInt{} node is a leaf in
  788. the AST. The \code{match} proceeds through the clauses in order,
  789. checking whether the pattern can match the input AST. The body of the
  790. first clause that matches is executed. The output of \code{leaf?} for
  791. several ASTs is shown on the right.
  792. \begin{center}
  793. \begin{minipage}{0.6\textwidth}
  794. \begin{lstlisting}
  795. (define (leaf? arith)
  796. (match arith
  797. [(Int n) #t]
  798. [(Prim 'read '()) #t]
  799. [(Prim '- (list e1)) #f]
  800. [(Prim '+ (list e1 e2)) #f]))
  801. (leaf? (Prim 'read '()))
  802. (leaf? (Prim '- (list (Int 8))))
  803. (leaf? (Int 8))
  804. \end{lstlisting}
  805. \end{minipage}
  806. \vrule
  807. \begin{minipage}{0.25\textwidth}
  808. \begin{lstlisting}
  809. #t
  810. #f
  811. #t
  812. \end{lstlisting}
  813. \end{minipage}
  814. \end{center}
  815. When writing a \code{match}, we refer to the grammar definition to
  816. identify which non-terminal we are expecting to match against, then we
  817. make sure that 1) we have one clause for each alternative of that
  818. non-terminal and 2) that the pattern in each clause corresponds to the
  819. corresponding right-hand side of a grammar rule. For the \code{match}
  820. in the \code{leaf?} function, we refer to the grammar for \LangInt{} in
  821. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  822. alternatives, so the \code{match} has 4 clauses. The pattern in each
  823. clause corresponds to the right-hand side of a grammar rule. For
  824. example, the pattern \code{(Prim '+ (list e1 e2))} corresponds to the
  825. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  826. patterns, replace non-terminals such as $\Exp$ with pattern variables
  827. of your choice (e.g. \code{e1} and \code{e2}).
  828. \section{Recursive Functions}
  829. \label{sec:recursion}
  830. \index{recursive function}
  831. Programs are inherently recursive. For example, an \LangInt{} expression is
  832. often made of smaller expressions. Thus, the natural way to process an
  833. entire program is with a recursive function. As a first example of
  834. such a recursive function, we define \texttt{exp?} below, which takes
  835. an arbitrary value and determines whether or not it is an \LangInt{}
  836. expression.
  837. %
  838. We say that a function is defined by \emph{structural recursion} when
  839. it is defined using a sequence of match clauses that correspond to a
  840. grammar, and the body of each clause makes a recursive call on each
  841. child node.\footnote{This principle of structuring code according to
  842. the data definition is advocated in the book \emph{How to Design
  843. Programs} \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}.
  844. Below we also define a second function, named \code{Rint?}, that
  845. determines whether an AST is an \LangInt{} program. In general we can
  846. expect to write one recursive function to handle each non-terminal in
  847. a grammar.\index{structural recursion}
  848. %
  849. \begin{center}
  850. \begin{minipage}{0.7\textwidth}
  851. \begin{lstlisting}
  852. (define (exp? ast)
  853. (match ast
  854. [(Int n) #t]
  855. [(Prim 'read '()) #t]
  856. [(Prim '- (list e)) (exp? e)]
  857. [(Prim '+ (list e1 e2))
  858. (and (exp? e1) (exp? e2))]
  859. [else #f]))
  860. (define (Rint? ast)
  861. (match ast
  862. [(Program '() e) (exp? e)]
  863. [else #f]))
  864. (Rint? (Program '() ast1.1)
  865. (Rint? (Program '()
  866. (Prim '- (list (Prim 'read '())
  867. (Prim '+ (list (Num 8)))))))
  868. \end{lstlisting}
  869. \end{minipage}
  870. \vrule
  871. \begin{minipage}{0.25\textwidth}
  872. \begin{lstlisting}
  873. #t
  874. #f
  875. \end{lstlisting}
  876. \end{minipage}
  877. \end{center}
  878. You may be tempted to merge the two functions into one, like this:
  879. \begin{center}
  880. \begin{minipage}{0.5\textwidth}
  881. \begin{lstlisting}
  882. (define (Rint? ast)
  883. (match ast
  884. [(Int n) #t]
  885. [(Prim 'read '()) #t]
  886. [(Prim '- (list e)) (Rint? e)]
  887. [(Prim '+ (list e1 e2)) (and (Rint? e1) (Rint? e2))]
  888. [(Program '() e) (Rint? e)]
  889. [else #f]))
  890. \end{lstlisting}
  891. \end{minipage}
  892. \end{center}
  893. %
  894. Sometimes such a trick will save a few lines of code, especially when
  895. it comes to the \code{Program} wrapper. Yet this style is generally
  896. \emph{not} recommended because it can get you into trouble.
  897. %
  898. For example, the above function is subtly wrong:
  899. \lstinline{(Rint? (Program '() (Program '() (Int 3))))}
  900. returns true when it should return false.
  901. \section{Interpreters}
  902. \label{sec:interp-Rint}
  903. \index{interpreter}
  904. In general, the intended behavior of a program is defined by the
  905. specification of the language. For example, the Scheme language is
  906. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  907. defined in its reference manual~\citep{plt-tr}. In this book we use
  908. interpreters to specify each language that we consider. An interpreter
  909. that is designated as the definition of a language is called a
  910. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  911. \index{definitional interpreter} We warm up by creating a definitional
  912. interpreter for the \LangInt{} language, which serves as a second example
  913. of structural recursion. The \texttt{interp-Rint} function is defined in
  914. Figure~\ref{fig:interp-Rint}. The body of the function is a match on the
  915. input program followed by a call to the \lstinline{interp-exp} helper
  916. function, which in turn has one match clause per grammar rule for
  917. \LangInt{} expressions.
  918. \begin{figure}[tp]
  919. \begin{lstlisting}
  920. (define (interp-exp e)
  921. (match e
  922. [(Int n) n]
  923. [(Prim 'read '())
  924. (define r (read))
  925. (cond [(fixnum? r) r]
  926. [else (error 'interp-exp "read expected an integer" r)])]
  927. [(Prim '- (list e))
  928. (define v (interp-exp e))
  929. (fx- 0 v)]
  930. [(Prim '+ (list e1 e2))
  931. (define v1 (interp-exp e1))
  932. (define v2 (interp-exp e2))
  933. (fx+ v1 v2)]))
  934. (define (interp-Rint p)
  935. (match p
  936. [(Program '() e) (interp-exp e)]))
  937. \end{lstlisting}
  938. \caption{Interpreter for the \LangInt{} language.}
  939. \label{fig:interp-Rint}
  940. \end{figure}
  941. Let us consider the result of interpreting a few \LangInt{} programs. The
  942. following program adds two integers.
  943. \begin{lstlisting}
  944. (+ 10 32)
  945. \end{lstlisting}
  946. The result is \key{42}, the answer to life, the universe, and
  947. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  948. Galaxy} by Douglas Adams.}.
  949. %
  950. We wrote the above program in concrete syntax whereas the parsed
  951. abstract syntax is:
  952. \begin{lstlisting}
  953. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  954. \end{lstlisting}
  955. The next example demonstrates that expressions may be nested within
  956. each other, in this case nesting several additions and negations.
  957. \begin{lstlisting}
  958. (+ 10 (- (+ 12 20)))
  959. \end{lstlisting}
  960. What is the result of the above program?
  961. As mentioned previously, the \LangInt{} language does not support
  962. arbitrarily-large integers, but only $63$-bit integers, so we
  963. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  964. in Racket.
  965. Suppose
  966. \[
  967. n = 999999999999999999
  968. \]
  969. which indeed fits in $63$-bits. What happens when we run the
  970. following program in our interpreter?
  971. \begin{lstlisting}
  972. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  973. \end{lstlisting}
  974. It produces an error:
  975. \begin{lstlisting}
  976. fx+: result is not a fixnum
  977. \end{lstlisting}
  978. We establish the convention that if running the definitional
  979. interpreter on a program produces an error then the meaning of that
  980. program is \emph{unspecified}\index{unspecified behavior}, unless the
  981. error is a \code{trapped-error}. A compiler for the language is under
  982. no obligations regarding programs with unspecified behavior; it does
  983. not have to produce an executable, and if it does, that executable can
  984. do anything. On the other hand, if the error is a
  985. \code{trapped-error}, then the compiler must produce an executable and
  986. it is required to report that an error occurred. To signal an error,
  987. exit with a return code of \code{255}. The interpreters in chapters
  988. \ref{ch:type-dynamic} and \ref{ch:Rgrad} use
  989. \code{trapped-error}.
  990. %% This convention applies to the languages defined in this
  991. %% book, as a way to simplify the student's task of implementing them,
  992. %% but this convention is not applicable to all programming languages.
  993. %%
  994. Moving on to the last feature of the \LangInt{} language, the \key{read}
  995. operation prompts the user of the program for an integer. Recall that
  996. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  997. \code{8}. So if we run
  998. \begin{lstlisting}
  999. (interp-Rint (Program '() ast1.1))
  1000. \end{lstlisting}
  1001. and if the input is \code{50}, the result is \code{42}.
  1002. We include the \key{read} operation in \LangInt{} so a clever student
  1003. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1004. during compilation to obtain the output and then generates the trivial
  1005. code to produce the output. (Yes, a clever student did this in the
  1006. first instance of this course.)
  1007. The job of a compiler is to translate a program in one language into a
  1008. program in another language so that the output program behaves the
  1009. same way as the input program does. This idea is depicted in the
  1010. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1011. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1012. Given a compiler that translates from language $\mathcal{L}_1$ to
  1013. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1014. compiler must translate it into some program $P_2$ such that
  1015. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1016. same input $i$ yields the same output $o$.
  1017. \begin{equation} \label{eq:compile-correct}
  1018. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1019. \node (p1) at (0, 0) {$P_1$};
  1020. \node (p2) at (3, 0) {$P_2$};
  1021. \node (o) at (3, -2.5) {$o$};
  1022. \path[->] (p1) edge [above] node {compile} (p2);
  1023. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  1024. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  1025. \end{tikzpicture}
  1026. \end{equation}
  1027. In the next section we see our first example of a compiler.
  1028. \section{Example Compiler: a Partial Evaluator}
  1029. \label{sec:partial-evaluation}
  1030. In this section we consider a compiler that translates \LangInt{} programs
  1031. into \LangInt{} programs that may be more efficient, that is, this compiler
  1032. is an optimizer. This optimizer eagerly computes the parts of the
  1033. program that do not depend on any inputs, a process known as
  1034. \emph{partial evaluation}~\citep{Jones:1993uq}.
  1035. \index{partial evaluation}
  1036. For example, given the following program
  1037. \begin{lstlisting}
  1038. (+ (read) (- (+ 5 3)))
  1039. \end{lstlisting}
  1040. our compiler will translate it into the program
  1041. \begin{lstlisting}
  1042. (+ (read) -8)
  1043. \end{lstlisting}
  1044. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1045. evaluator for the \LangInt{} language. The output of the partial evaluator
  1046. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  1047. recursion over $\Exp$ is captured in the \code{pe-exp} function
  1048. whereas the code for partially evaluating the negation and addition
  1049. operations is factored into two separate helper functions:
  1050. \code{pe-neg} and \code{pe-add}. The input to these helper
  1051. functions is the output of partially evaluating the children.
  1052. \begin{figure}[tp]
  1053. \begin{lstlisting}
  1054. (define (pe-neg r)
  1055. (match r
  1056. [(Int n) (Int (fx- 0 n))]
  1057. [else (Prim '- (list r))]))
  1058. (define (pe-add r1 r2)
  1059. (match* (r1 r2)
  1060. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1061. [(_ _) (Prim '+ (list r1 r2))]))
  1062. (define (pe-exp e)
  1063. (match e
  1064. [(Int n) (Int n)]
  1065. [(Prim 'read '()) (Prim 'read '())]
  1066. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  1067. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]))
  1068. (define (pe-Rint p)
  1069. (match p
  1070. [(Program '() e) (Program '() (pe-exp e))]))
  1071. \end{lstlisting}
  1072. \caption{A partial evaluator for \LangInt{}.}
  1073. \label{fig:pe-arith}
  1074. \end{figure}
  1075. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  1076. arguments are integers and if they are, perform the appropriate
  1077. arithmetic. Otherwise, they create an AST node for the arithmetic
  1078. operation.
  1079. To gain some confidence that the partial evaluator is correct, we can
  1080. test whether it produces programs that get the same result as the
  1081. input programs. That is, we can test whether it satisfies Diagram
  1082. \ref{eq:compile-correct}. The following code runs the partial
  1083. evaluator on several examples and tests the output program. The
  1084. \texttt{parse-program} and \texttt{assert} functions are defined in
  1085. Appendix~\ref{appendix:utilities}.\\
  1086. \begin{minipage}{1.0\textwidth}
  1087. \begin{lstlisting}
  1088. (define (test-pe p)
  1089. (assert "testing pe-Rint"
  1090. (equal? (interp-Rint p) (interp-Rint (pe-Rint p)))))
  1091. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1092. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1093. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  1094. \end{lstlisting}
  1095. \end{minipage}
  1096. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1097. \chapter{Integers and Variables}
  1098. \label{ch:Rvar}
  1099. This chapter is about compiling a subset of Racket to x86-64 assembly
  1100. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1101. integer arithmetic and local variable binding. We often refer to
  1102. x86-64 simply as x86. The chapter begins with a description of the
  1103. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1104. to of x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  1105. is large so we discuss only the instructions needed for compiling
  1106. \LangVar{}. We introduce more x86 instructions in later chapters.
  1107. After introducing \LangVar{} and x86, we reflect on their differences
  1108. and come up with a plan to break down the translation from \LangVar{}
  1109. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1110. rest of the sections in this chapter give detailed hints regarding
  1111. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  1112. We hope to give enough hints that the well-prepared reader, together
  1113. with a few friends, can implement a compiler from \LangVar{} to x86 in
  1114. a couple weeks. To give the reader a feeling for the scale of this
  1115. first compiler, the instructor solution for the \LangVar{} compiler is
  1116. approximately 500 lines of code.
  1117. \section{The \LangVar{} Language}
  1118. \label{sec:s0}
  1119. \index{variable}
  1120. The \LangVar{} language extends the \LangInt{} language with variable
  1121. definitions. The concrete syntax of the \LangVar{} language is defined by
  1122. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  1123. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  1124. \Var{} may be any Racket identifier. As in \LangInt{}, \key{read} is a
  1125. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  1126. operator. Similar to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1127. \key{Program} struct to mark the top of the program.
  1128. %% The $\itm{info}$
  1129. %% field of the \key{Program} structure contains an \emph{association
  1130. %% list} (a list of key-value pairs) that is used to communicate
  1131. %% auxiliary data from one compiler pass the next.
  1132. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1133. exhibit several compilation techniques.
  1134. \begin{figure}[tp]
  1135. \centering
  1136. \fbox{
  1137. \begin{minipage}{0.96\textwidth}
  1138. \[
  1139. \begin{array}{rcl}
  1140. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  1141. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  1142. \LangVar{} &::=& \Exp
  1143. \end{array}
  1144. \]
  1145. \end{minipage}
  1146. }
  1147. \caption{The concrete syntax of \LangVar{}.}
  1148. \label{fig:r1-concrete-syntax}
  1149. \end{figure}
  1150. \begin{figure}[tp]
  1151. \centering
  1152. \fbox{
  1153. \begin{minipage}{0.96\textwidth}
  1154. \[
  1155. \begin{array}{rcl}
  1156. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1157. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1158. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1159. \LangVar{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1160. \end{array}
  1161. \]
  1162. \end{minipage}
  1163. }
  1164. \caption{The abstract syntax of \LangVar{}.}
  1165. \label{fig:r1-syntax}
  1166. \end{figure}
  1167. Let us dive further into the syntax and semantics of the \LangVar{}
  1168. language. The \key{let} feature defines a variable for use within its
  1169. body and initializes the variable with the value of an expression.
  1170. The abstract syntax for \key{let} is defined in
  1171. Figure~\ref{fig:r1-syntax}. The concrete syntax for \key{let} is
  1172. \begin{lstlisting}
  1173. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1174. \end{lstlisting}
  1175. For example, the following program initializes \code{x} to $32$ and then
  1176. evaluates the body \code{(+ 10 x)}, producing $42$.
  1177. \begin{lstlisting}
  1178. (let ([x (+ 12 20)]) (+ 10 x))
  1179. \end{lstlisting}
  1180. When there are multiple \key{let}'s for the same variable, the closest
  1181. enclosing \key{let} is used. That is, variable definitions overshadow
  1182. prior definitions. Consider the following program with two \key{let}'s
  1183. that define variables named \code{x}. Can you figure out the result?
  1184. \begin{lstlisting}
  1185. (let ([x 32]) (+ (let ([x 10]) x) x))
  1186. \end{lstlisting}
  1187. For the purposes of depicting which variable uses correspond to which
  1188. definitions, the following shows the \code{x}'s annotated with
  1189. subscripts to distinguish them. Double check that your answer for the
  1190. above is the same as your answer for this annotated version of the
  1191. program.
  1192. \begin{lstlisting}
  1193. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1194. \end{lstlisting}
  1195. The initializing expression is always evaluated before the body of the
  1196. \key{let}, so in the following, the \key{read} for \code{x} is
  1197. performed before the \key{read} for \code{y}. Given the input
  1198. $52$ then $10$, the following produces $42$ (not $-42$).
  1199. \begin{lstlisting}
  1200. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1201. \end{lstlisting}
  1202. \subsection{Extensible Interpreters via Method Overriding}
  1203. \label{sec:extensible-interp}
  1204. To prepare for discussing the interpreter for \LangVar{}, we need to
  1205. explain why we choose to implement the interpreter using
  1206. object-oriented programming, that is, as a collection of methods
  1207. inside of a class. Throughout this book we define many interpreters,
  1208. one for each of the languages that we study. Because each language
  1209. builds on the prior one, there is a lot of commonality between their
  1210. interpreters. We want to write down those common parts just once
  1211. instead of many times. A naive approach would be to have, for example,
  1212. the interpreter for \LangIf{} handle all of the new features in that
  1213. language and then have a default case that dispatches to the
  1214. interpreter for \LangVar{}. The following code sketches this idea.
  1215. \begin{center}
  1216. \begin{minipage}{0.45\textwidth}
  1217. \begin{lstlisting}
  1218. (define (interp-Rvar e)
  1219. (match e
  1220. [(Prim '- (list e))
  1221. (fx- 0 (interp-Rvar e))]
  1222. ...))
  1223. \end{lstlisting}
  1224. \end{minipage}
  1225. \begin{minipage}{0.45\textwidth}
  1226. \begin{lstlisting}
  1227. (define (interp-Rif e)
  1228. (match e
  1229. [(If cnd thn els)
  1230. (match (interp-Rif cnd)
  1231. [#t (interp-Rif thn)]
  1232. [#f (interp-Rif els)])]
  1233. ...
  1234. [else (interp-Rvar e)]))
  1235. \end{lstlisting}
  1236. \end{minipage}
  1237. \end{center}
  1238. The problem with this approach is that it does not handle situations
  1239. in which an \LangIf{} feature, like \code{If}, is nested inside an \LangVar{}
  1240. feature, like the \code{-} operator, as in the following program.
  1241. \begin{lstlisting}
  1242. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1243. \end{lstlisting}
  1244. If we invoke \code{interp-Rif} on this program, it dispatches to
  1245. \code{interp-Rvar} to handle the \code{-} operator, but then it
  1246. recurisvely calls \code{interp-Rvar} again on the argument of \code{-},
  1247. which is an \code{If}. But there is no case for \code{If} in
  1248. \code{interp-Rvar}, so we get an error!
  1249. To make our interpreters extensible we need something called
  1250. \emph{open recursion}\index{open recursion}, where the tying of the
  1251. recursive knot is delayed to when the functions are
  1252. composed. Object-oriented languages provide open recursion with the
  1253. late-binding of overridden methods\index{method overriding}. The
  1254. following code sketches this idea for interpreting \LangVar{} and
  1255. \LangIf{} using the
  1256. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1257. \index{class} feature of Racket. We define one class for each
  1258. language and define a method for interpreting expressions inside each
  1259. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1260. and the method \code{interp-exp} in \LangIf{} overrides the
  1261. \code{interp-exp} in \LangVar{}. Note that the default case of
  1262. \code{interp-exp} in \LangIf{} uses \code{super} to invoke
  1263. \code{interp-exp}, and because \LangIf{} inherits from \LangVar{},
  1264. that dispatches to the \code{interp-exp} in \LangVar{}.
  1265. \begin{center}
  1266. \begin{minipage}{0.45\textwidth}
  1267. \begin{lstlisting}
  1268. (define interp-Rvar-class
  1269. (class object%
  1270. (define/public (interp-exp e)
  1271. (match e
  1272. [(Prim '- (list e))
  1273. (fx- 0 (interp-exp e))]
  1274. ...))
  1275. ...))
  1276. \end{lstlisting}
  1277. \end{minipage}
  1278. \begin{minipage}{0.45\textwidth}
  1279. \begin{lstlisting}
  1280. (define interp-Rif-class
  1281. (class interp-Rvar-class
  1282. (define/override (interp-exp e)
  1283. (match e
  1284. [(If cnd thn els)
  1285. (match (interp-exp cnd)
  1286. [#t (interp-exp thn)]
  1287. [#f (interp-exp els)])]
  1288. ...
  1289. [else (super interp-exp e)]))
  1290. ...
  1291. ))
  1292. \end{lstlisting}
  1293. \end{minipage}
  1294. \end{center}
  1295. Getting back to the troublesome example, repeated here:
  1296. \begin{lstlisting}
  1297. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1298. \end{lstlisting}
  1299. We can invoke the \code{interp-exp} method for \LangIf{} on this
  1300. expression by creating an object of the \LangIf{} class and sending it the
  1301. \code{interp-exp} method with the argument \code{e0}.
  1302. \begin{lstlisting}
  1303. (send (new interp-Rif-class) interp-exp e0)
  1304. \end{lstlisting}
  1305. The default case of \code{interp-exp} in \LangIf{} handles it by
  1306. dispatching to the \code{interp-exp} method in \LangVar{}, which
  1307. handles the \code{-} operator. But then for the recursive method call,
  1308. it dispatches back to \code{interp-exp} in \LangIf{}, where the
  1309. \code{If} is handled correctly. Thus, method overriding gives us the
  1310. open recursion that we need to implement our interpreters in an
  1311. extensible way.
  1312. \newpage
  1313. \subsection{Definitional Interpreter for \LangVar{}}
  1314. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  1315. \small
  1316. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1317. An \emph{association list} (alist) is a list of key-value pairs.
  1318. For example, we can map people to their ages with an alist.
  1319. \index{alist}\index{association list}
  1320. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1321. (define ages
  1322. '((jane . 25) (sam . 24) (kate . 45)))
  1323. \end{lstlisting}
  1324. The \emph{dictionary} interface is for mapping keys to values.
  1325. Every alist implements this interface. \index{dictionary} The package
  1326. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1327. provides many functions for working with dictionaries. Here
  1328. are a few of them:
  1329. \begin{description}
  1330. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1331. returns the value associated with the given $\itm{key}$.
  1332. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1333. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1334. but otherwise is the same as $\itm{dict}$.
  1335. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1336. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1337. of keys and values in $\itm{dict}$. For example, the following
  1338. creates a new alist in which the ages are incremented.
  1339. \end{description}
  1340. \vspace{-10pt}
  1341. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1342. (for/list ([(k v) (in-dict ages)])
  1343. (cons k (add1 v)))
  1344. \end{lstlisting}
  1345. \end{tcolorbox}
  1346. \end{wrapfigure}
  1347. Having justified the use of classes and methods to implement
  1348. interpreters, we turn to the definitional interpreter for \LangVar{}
  1349. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1350. \LangInt{} but adds two new \key{match} cases for variables and
  1351. \key{let}. For \key{let} we need a way to communicate the value bound
  1352. to a variable to all the uses of the variable. To accomplish this, we
  1353. maintain a mapping from variables to values. Throughout the compiler
  1354. we often need to map variables to information about them. We refer to
  1355. these mappings as
  1356. \emph{environments}\index{environment}.\footnote{Another common term
  1357. for environment in the compiler literature is \emph{symbol
  1358. table}\index{symbol table}.}
  1359. %
  1360. For simplicity, we use an association list (alist) to represent the
  1361. environment. The sidebar to the right gives a brief introduction to
  1362. alists and the \code{racket/dict} package. The \code{interp-exp}
  1363. function takes the current environment, \code{env}, as an extra
  1364. parameter. When the interpreter encounters a variable, it finds the
  1365. corresponding value using the \code{dict-ref} function. When the
  1366. interpreter encounters a \key{Let}, it evaluates the initializing
  1367. expression, extends the environment with the result value bound to the
  1368. variable, using \code{dict-set}, then evaluates the body of the
  1369. \key{Let}.
  1370. \begin{figure}[tp]
  1371. \begin{lstlisting}
  1372. (define interp-Rvar-class
  1373. (class object%
  1374. (super-new)
  1375. (define/public ((interp-exp env) e)
  1376. (match e
  1377. [(Int n) n]
  1378. [(Prim 'read '())
  1379. (define r (read))
  1380. (cond [(fixnum? r) r]
  1381. [else (error 'interp-exp "expected an integer" r)])]
  1382. [(Prim '- (list e)) (fx- 0 ((interp-exp env) e))]
  1383. [(Prim '+ (list e1 e2))
  1384. (fx+ ((interp-exp env) e1) ((interp-exp env) e2))]
  1385. [(Var x) (dict-ref env x)]
  1386. [(Let x e body)
  1387. (define new-env (dict-set env x ((interp-exp env) e)))
  1388. ((interp-exp new-env) body)]))
  1389. (define/public (interp-program p)
  1390. (match p
  1391. [(Program '() e) ((interp-exp '()) e)]))
  1392. ))
  1393. (define (interp-Rvar p)
  1394. (send (new interp-Rvar-class) interp-program p))
  1395. \end{lstlisting}
  1396. \caption{Interpreter for the \LangVar{} language.}
  1397. \label{fig:interp-Rvar}
  1398. \end{figure}
  1399. The goal for this chapter is to implement a compiler that translates
  1400. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1401. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1402. computer as the $P_1$ program interpreted by \code{interp-Rvar}. That
  1403. is, they output the same integer $n$. We depict this correctness
  1404. criteria in the following diagram.
  1405. \[
  1406. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1407. \node (p1) at (0, 0) {$P_1$};
  1408. \node (p2) at (4, 0) {$P_2$};
  1409. \node (o) at (4, -2) {$n$};
  1410. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1411. \path[->] (p1) edge [left] node {\footnotesize\code{interp-Rvar}} (o);
  1412. \path[->] (p2) edge [right] node {\footnotesize\code{interp-x86int}} (o);
  1413. \end{tikzpicture}
  1414. \]
  1415. In the next section we introduce the \LangXInt{} subset of x86 that
  1416. suffices for compiling \LangVar{}.
  1417. \section{The \LangXInt{} Assembly Language}
  1418. \label{sec:x86}
  1419. \index{x86}
  1420. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1421. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1422. assembler.
  1423. %
  1424. A program begins with a \code{main} label followed by a sequence of
  1425. instructions. The \key{globl} directive says that the \key{main}
  1426. procedure is externally visible, which is necessary so that the
  1427. operating system can call it. In the grammar, ellipses such as
  1428. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1429. \ldots$ is a sequence of instructions.\index{instruction}
  1430. %
  1431. An x86 program is stored in the computer's memory. For our purposes,
  1432. the computer's memory is as a mapping of 64-bit addresses to 64-bit
  1433. values. The computer has a \emph{program counter} (PC)\index{program
  1434. counter}\index{PC} stored in the \code{rip} register that points to
  1435. the address of the next instruction to be executed. For most
  1436. instructions, the program counter is incremented after the instruction
  1437. is executed, so it points to the next instruction in memory. Most x86
  1438. instructions take two operands, where each operand is either an
  1439. integer constant (called \emph{immediate value}\index{immediate
  1440. value}), a \emph{register}\index{register}, or a memory location.
  1441. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1442. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1443. && \key{r8} \mid \key{r9} \mid \key{r10}
  1444. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1445. \mid \key{r14} \mid \key{r15}}
  1446. \begin{figure}[tp]
  1447. \fbox{
  1448. \begin{minipage}{0.96\textwidth}
  1449. \[
  1450. \begin{array}{lcl}
  1451. \Reg &::=& \allregisters{} \\
  1452. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1453. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1454. \key{subq} \; \Arg\key{,} \Arg \mid
  1455. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1456. && \key{callq} \; \mathit{label} \mid
  1457. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1458. && \itm{label}\key{:}\; \Instr \\
  1459. \LangXInt{} &::= & \key{.globl main}\\
  1460. & & \key{main:} \; \Instr\ldots
  1461. \end{array}
  1462. \]
  1463. \end{minipage}
  1464. }
  1465. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  1466. \label{fig:x86-int-concrete}
  1467. \end{figure}
  1468. A register is a special kind of variable. Each one holds a 64-bit
  1469. value; there are 16 general-purpose registers in the computer and
  1470. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1471. is written with a \key{\%} followed by the register name, such as
  1472. \key{\%rax}.
  1473. An immediate value is written using the notation \key{\$}$n$ where $n$
  1474. is an integer.
  1475. %
  1476. %
  1477. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1478. which obtains the address stored in register $r$ and then adds $n$
  1479. bytes to the address. The resulting address is used to load or store
  1480. to memory depending on whether it occurs as a source or destination
  1481. argument of an instruction.
  1482. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1483. source $s$ and destination $d$, applies the arithmetic operation, then
  1484. writes the result back to the destination $d$.
  1485. %
  1486. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1487. stores the result in $d$.
  1488. %
  1489. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1490. specified by the label and $\key{retq}$ returns from a procedure to
  1491. its caller.
  1492. %
  1493. We discuss procedure calls in more detail later in this chapter and in
  1494. Chapter~\ref{ch:Rfun}. The instruction $\key{jmp}\,\itm{label}$
  1495. updates the program counter to the address of the instruction after
  1496. the specified label.
  1497. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1498. all of the x86 instructions used in this book.
  1499. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent to
  1500. \code{(+ 10 32)}. The instruction \lstinline{movq $10, %rax}
  1501. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1502. adds $32$ to the $10$ in \key{rax} and
  1503. puts the result, $42$, back into \key{rax}.
  1504. %
  1505. The last instruction, \key{retq}, finishes the \key{main} function by
  1506. returning the integer in \key{rax} to the operating system. The
  1507. operating system interprets this integer as the program's exit
  1508. code. By convention, an exit code of 0 indicates that a program
  1509. completed successfully, and all other exit codes indicate various
  1510. errors. Nevertheless, in this book we return the result of the program
  1511. as the exit code.
  1512. \begin{figure}[tbp]
  1513. \begin{lstlisting}
  1514. .globl main
  1515. main:
  1516. movq $10, %rax
  1517. addq $32, %rax
  1518. retq
  1519. \end{lstlisting}
  1520. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1521. \label{fig:p0-x86}
  1522. \end{figure}
  1523. The x86 assembly language varies in a couple ways depending on what
  1524. operating system it is assembled in. The code examples shown here are
  1525. correct on Linux and most Unix-like platforms, but when assembled on
  1526. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1527. as in \key{\_main}.
  1528. We exhibit the use of memory for storing intermediate results in the
  1529. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1530. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1531. memory called the \emph{procedure call stack} (or \emph{stack} for
  1532. short). \index{stack}\index{procedure call stack} The stack consists
  1533. of a separate \emph{frame}\index{frame} for each procedure call. The
  1534. memory layout for an individual frame is shown in
  1535. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1536. \emph{stack pointer}\index{stack pointer} and points to the item at
  1537. the top of the stack. The stack grows downward in memory, so we
  1538. increase the size of the stack by subtracting from the stack pointer.
  1539. In the context of a procedure call, the \emph{return
  1540. address}\index{return address} is the instruction after the call
  1541. instruction on the caller side. The function call instruction,
  1542. \code{callq}, pushes the return address onto the stack prior to
  1543. jumping to the procedure. The register \key{rbp} is the \emph{base
  1544. pointer}\index{base pointer} and is used to access variables that
  1545. are stored in the frame of the current procedure call. The base
  1546. pointer of the caller is pushed onto the stack after the return
  1547. address and then the base pointer is set to the location of the old
  1548. base pointer. In Figure~\ref{fig:frame} we number the variables from
  1549. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  1550. variable $2$ at $-16\key{(\%rbp)}$, etc.
  1551. \begin{figure}[tbp]
  1552. \begin{lstlisting}
  1553. start:
  1554. movq $10, -8(%rbp)
  1555. negq -8(%rbp)
  1556. movq -8(%rbp), %rax
  1557. addq $52, %rax
  1558. jmp conclusion
  1559. .globl main
  1560. main:
  1561. pushq %rbp
  1562. movq %rsp, %rbp
  1563. subq $16, %rsp
  1564. jmp start
  1565. conclusion:
  1566. addq $16, %rsp
  1567. popq %rbp
  1568. retq
  1569. \end{lstlisting}
  1570. \caption{An x86 program equivalent to \code{(+ 52 (- 10))}.}
  1571. \label{fig:p1-x86}
  1572. \end{figure}
  1573. \begin{figure}[tbp]
  1574. \centering
  1575. \begin{tabular}{|r|l|} \hline
  1576. Position & Contents \\ \hline
  1577. 8(\key{\%rbp}) & return address \\
  1578. 0(\key{\%rbp}) & old \key{rbp} \\
  1579. -8(\key{\%rbp}) & variable $1$ \\
  1580. -16(\key{\%rbp}) & variable $2$ \\
  1581. \ldots & \ldots \\
  1582. 0(\key{\%rsp}) & variable $n$\\ \hline
  1583. \end{tabular}
  1584. \caption{Memory layout of a frame.}
  1585. \label{fig:frame}
  1586. \end{figure}
  1587. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1588. control is transferred from the operating system to the \code{main}
  1589. function. The operating system issues a \code{callq main} instruction
  1590. which pushes its return address on the stack and then jumps to
  1591. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1592. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1593. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1594. alignment (because the \code{callq} pushed the return address). The
  1595. first three instructions are the typical \emph{prelude}\index{prelude}
  1596. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1597. pointer for the caller onto the stack and subtracts $8$ from the stack
  1598. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  1599. base pointer so that it points the location of the old base
  1600. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1601. pointer down to make enough room for storing variables. This program
  1602. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  1603. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  1604. functions. The last instruction of the prelude is \code{jmp start},
  1605. which transfers control to the instructions that were generated from
  1606. the Racket expression \code{(+ 52 (- 10))}.
  1607. The first instruction under the \code{start} label is
  1608. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  1609. %
  1610. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1611. %
  1612. The next instruction moves the $-10$ from variable $1$ into the
  1613. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1614. the value in \code{rax}, updating its contents to $42$.
  1615. The three instructions under the label \code{conclusion} are the
  1616. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1617. two instructions restore the \code{rsp} and \code{rbp} registers to
  1618. the state they were in at the beginning of the procedure. The
  1619. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  1620. point at the old base pointer. Then \key{popq \%rbp} returns the old
  1621. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1622. instruction, \key{retq}, jumps back to the procedure that called this
  1623. one and adds $8$ to the stack pointer.
  1624. The compiler needs a convenient representation for manipulating x86
  1625. programs, so we define an abstract syntax for x86 in
  1626. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  1627. \LangXInt{}. The main difference compared to the concrete syntax of
  1628. \LangXInt{} (Figure~\ref{fig:x86-int-concrete}) is that labels are not
  1629. allowed in front of every instructions. Instead instructions are
  1630. grouped into \emph{blocks}\index{block}\index{basic block} with a
  1631. label associated with every block, which is why the \key{X86Program}
  1632. struct includes an alist mapping labels to blocks. The reason for this
  1633. organization becomes apparent in Chapter~\ref{ch:Rif} when we
  1634. introduce conditional branching. The \code{Block} structure includes
  1635. an $\itm{info}$ field that is not needed for this chapter, but becomes
  1636. useful in Chapter~\ref{ch:register-allocation-Rvar}. For now, the
  1637. $\itm{info}$ field should contain an empty list. Also, regarding the
  1638. abstract syntax for \code{callq}, the \code{Callq} struct includes an
  1639. integer for representing the arity of the function, i.e., the number
  1640. of arguments, which is helpful to know during register allocation
  1641. (Chapter~\ref{ch:register-allocation-Rvar}).
  1642. \begin{figure}[tp]
  1643. \fbox{
  1644. \begin{minipage}{0.98\textwidth}
  1645. \small
  1646. \[
  1647. \begin{array}{lcl}
  1648. \Reg &::=& \allregisters{} \\
  1649. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1650. \mid \DEREF{\Reg}{\Int} \\
  1651. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  1652. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  1653. &\mid& \BININSTR{\code{movq}}{\Arg}{\Arg}
  1654. \mid \UNIINSTR{\code{negq}}{\Arg}\\
  1655. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1656. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1657. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  1658. \LangXInt{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  1659. \end{array}
  1660. \]
  1661. \end{minipage}
  1662. }
  1663. \caption{The abstract syntax of \LangXInt{} assembly.}
  1664. \label{fig:x86-int-ast}
  1665. \end{figure}
  1666. \section{Planning the trip to x86 via the \LangCVar{} language}
  1667. \label{sec:plan-s0-x86}
  1668. To compile one language to another it helps to focus on the
  1669. differences between the two languages because the compiler will need
  1670. to bridge those differences. What are the differences between \LangVar{}
  1671. and x86 assembly? Here are some of the most important ones:
  1672. \begin{enumerate}
  1673. \item[(a)] x86 arithmetic instructions typically have two arguments
  1674. and update the second argument in place. In contrast, \LangVar{}
  1675. arithmetic operations take two arguments and produce a new value.
  1676. An x86 instruction may have at most one memory-accessing argument.
  1677. Furthermore, some instructions place special restrictions on their
  1678. arguments.
  1679. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  1680. expression, whereas x86 instructions restrict their arguments to be
  1681. integers constants, registers, and memory locations.
  1682. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1683. sequence of instructions and jumps to labeled positions, whereas in
  1684. \LangVar{} the order of evaluation is a left-to-right depth-first
  1685. traversal of the abstract syntax tree.
  1686. \item[(d)] A program in \LangVar{} can have any number of variables
  1687. whereas x86 has 16 registers and the procedure calls stack.
  1688. \item[(e)] Variables in \LangVar{} can overshadow other variables with the
  1689. same name. In x86, registers have unique names and memory locations
  1690. have unique addresses.
  1691. \end{enumerate}
  1692. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  1693. the problem into several steps, dealing with the above differences one
  1694. at a time. Each of these steps is called a \emph{pass} of the
  1695. compiler.\index{pass}\index{compiler pass}
  1696. %
  1697. This terminology comes from the way each step passes over the AST of
  1698. the program.
  1699. %
  1700. We begin by sketching how we might implement each pass, and give them
  1701. names. We then figure out an ordering of the passes and the
  1702. input/output language for each pass. The very first pass has
  1703. \LangVar{} as its input language and the last pass has \LangXInt{} as
  1704. its output language. In between we can choose whichever language is
  1705. most convenient for expressing the output of each pass, whether that
  1706. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  1707. our own design. Finally, to implement each pass we write one
  1708. recursive function per non-terminal in the grammar of the input
  1709. language of the pass. \index{intermediate language}
  1710. \begin{description}
  1711. \item[\key{select-instructions}] handles the difference between
  1712. \LangVar{} operations and x86 instructions. This pass converts each
  1713. \LangVar{} operation to a short sequence of instructions that
  1714. accomplishes the same task.
  1715. \item[\key{remove-complex-opera*}] ensures that each subexpression of
  1716. a primitive operation is a variable or integer, that is, an
  1717. \emph{atomic} expression. We refer to non-atomic expressions as
  1718. \emph{complex}. This pass introduces temporary variables to hold
  1719. the results of complex subexpressions.\index{atomic
  1720. expression}\index{complex expression}%
  1721. \footnote{The subexpressions of an operation are often called
  1722. operators and operands which explains the presence of
  1723. \code{opera*} in the name of this pass.}
  1724. \item[\key{explicate-control}] makes the execution order of the
  1725. program explicit. It convert the abstract syntax tree representation
  1726. into a control-flow graph in which each node contains a sequence of
  1727. statements and the edges between nodes say which nodes contain jumps
  1728. to other nodes.
  1729. \item[\key{assign-homes}] replaces the variables in \LangVar{} with
  1730. registers or stack locations in x86.
  1731. \item[\key{uniquify}] deals with the shadowing of variables by
  1732. renaming every variable to a unique name.
  1733. \end{description}
  1734. The next question is: in what order should we apply these passes? This
  1735. question can be challenging because it is difficult to know ahead of
  1736. time which orderings will be better (easier to implement, produce more
  1737. efficient code, etc.) so oftentimes trial-and-error is
  1738. involved. Nevertheless, we can try to plan ahead and make educated
  1739. choices regarding the ordering.
  1740. What should be the ordering of \key{explicate-control} with respect to
  1741. \key{uniquify}? The \key{uniquify} pass should come first because
  1742. \key{explicate-control} changes all the \key{let}-bound variables to
  1743. become local variables whose scope is the entire program, which would
  1744. confuse variables with the same name.
  1745. %
  1746. We place \key{remove-complex-opera*} before \key{explicate-control}
  1747. because the later removes the \key{let} form, but it is convenient to
  1748. use \key{let} in the output of \key{remove-complex-opera*}.
  1749. %
  1750. The ordering of \key{uniquify} with respect to
  1751. \key{remove-complex-opera*} does not matter so we arbitrarily choose
  1752. \key{uniquify} to come first.
  1753. Last, we consider \key{select-instructions} and \key{assign-homes}.
  1754. These two passes are intertwined. In Chapter~\ref{ch:Rfun} we
  1755. learn that, in x86, registers are used for passing arguments to
  1756. functions and it is preferable to assign parameters to their
  1757. corresponding registers. On the other hand, by selecting instructions
  1758. first we may run into a dead end in \key{assign-homes}. Recall that
  1759. only one argument of an x86 instruction may be a memory access but
  1760. \key{assign-homes} might fail to assign even one of them to a
  1761. register.
  1762. %
  1763. A sophisticated approach is to iteratively repeat the two passes until
  1764. a solution is found. However, to reduce implementation complexity we
  1765. recommend a simpler approach in which \key{select-instructions} comes
  1766. first, followed by the \key{assign-homes}, then a third pass named
  1767. \key{patch-instructions} that uses a reserved register to fix
  1768. outstanding problems.
  1769. \begin{figure}[tbp]
  1770. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1771. \node (Rvar) at (0,2) {\large \LangVar{}};
  1772. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  1773. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  1774. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  1775. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  1776. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  1777. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  1778. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  1779. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  1780. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  1781. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  1782. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-2);
  1783. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1784. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1785. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1786. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1787. \end{tikzpicture}
  1788. \caption{Diagram of the passes for compiling \LangVar{}. }
  1789. \label{fig:Rvar-passes}
  1790. \end{figure}
  1791. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  1792. passes and identifies the input and output language of each pass. The
  1793. last pass, \key{print-x86}, converts from the abstract syntax of
  1794. \LangXInt{} to the concrete syntax. In the following two sections
  1795. we discuss the \LangCVar{} intermediate language and the \LangXVar{}
  1796. dialect of x86. The remainder of this chapter gives hints regarding
  1797. the implementation of each of the compiler passes in
  1798. Figure~\ref{fig:Rvar-passes}.
  1799. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  1800. %% are programs that are still in the \LangVar{} language, though the
  1801. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  1802. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  1803. %% %
  1804. %% The output of \key{explicate-control} is in an intermediate language
  1805. %% \LangCVar{} designed to make the order of evaluation explicit in its
  1806. %% syntax, which we introduce in the next section. The
  1807. %% \key{select-instruction} pass translates from \LangCVar{} to
  1808. %% \LangXVar{}. The \key{assign-homes} and
  1809. %% \key{patch-instructions}
  1810. %% passes input and output variants of x86 assembly.
  1811. \subsection{The \LangCVar{} Intermediate Language}
  1812. The output of \key{explicate-control} is similar to the $C$
  1813. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1814. categories for expressions and statements, so we name it \LangCVar{}. The
  1815. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  1816. (The concrete syntax for \LangCVar{} is in the Appendix,
  1817. Figure~\ref{fig:c0-concrete-syntax}.)
  1818. %
  1819. The \LangCVar{} language supports the same operators as \LangVar{} but
  1820. the arguments of operators are restricted to atomic
  1821. expressions. Instead of \key{let} expressions, \LangCVar{} has
  1822. assignment statements which can be executed in sequence using the
  1823. \key{Seq} form. A sequence of statements always ends with
  1824. \key{Return}, a guarantee that is baked into the grammar rules for
  1825. \itm{tail}. The naming of this non-terminal comes from the term
  1826. \emph{tail position}\index{tail position}, which refers to an
  1827. expression that is the last one to execute within a function.
  1828. A \LangCVar{} program consists of a control-flow graph represented as
  1829. an alist mapping labels to tails. This is more general than necessary
  1830. for the present chapter, as we do not yet introduce \key{goto} for
  1831. jumping to labels, but it saves us from having to change the syntax in
  1832. Chapter~\ref{ch:Rif}. For now there will be just one label,
  1833. \key{start}, and the whole program is its tail.
  1834. %
  1835. The $\itm{info}$ field of the \key{CProgram} form, after the
  1836. \key{explicate-control} pass, contains a mapping from the symbol
  1837. \key{locals} to a list of variables, that is, a list of all the
  1838. variables used in the program. At the start of the program, these
  1839. variables are uninitialized; they become initialized on their first
  1840. assignment.
  1841. \begin{figure}[tbp]
  1842. \fbox{
  1843. \begin{minipage}{0.96\textwidth}
  1844. \[
  1845. \begin{array}{lcl}
  1846. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1847. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1848. &\mid& \ADD{\Atm}{\Atm}\\
  1849. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1850. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1851. \LangCVar{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  1852. \end{array}
  1853. \]
  1854. \end{minipage}
  1855. }
  1856. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  1857. \label{fig:c0-syntax}
  1858. \end{figure}
  1859. The definitional interpreter for \LangCVar{} is in the support code,
  1860. in the file \code{interp-Cvar.rkt}.
  1861. \subsection{The \LangXVar{} dialect}
  1862. The \LangXVar{} language is the output of the pass
  1863. \key{select-instructions}. It extends \LangXInt{} with an unbounded
  1864. number of program-scope variables and removes the restrictions
  1865. regarding instruction arguments.
  1866. \section{Uniquify Variables}
  1867. \label{sec:uniquify-Rvar}
  1868. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  1869. programs in which every \key{let} binds a unique variable name. For
  1870. example, the \code{uniquify} pass should translate the program on the
  1871. left into the program on the right. \\
  1872. \begin{tabular}{lll}
  1873. \begin{minipage}{0.4\textwidth}
  1874. \begin{lstlisting}
  1875. (let ([x 32])
  1876. (+ (let ([x 10]) x) x))
  1877. \end{lstlisting}
  1878. \end{minipage}
  1879. &
  1880. $\Rightarrow$
  1881. &
  1882. \begin{minipage}{0.4\textwidth}
  1883. \begin{lstlisting}
  1884. (let ([x.1 32])
  1885. (+ (let ([x.2 10]) x.2) x.1))
  1886. \end{lstlisting}
  1887. \end{minipage}
  1888. \end{tabular} \\
  1889. %
  1890. The following is another example translation, this time of a program
  1891. with a \key{let} nested inside the initializing expression of another
  1892. \key{let}.\\
  1893. \begin{tabular}{lll}
  1894. \begin{minipage}{0.4\textwidth}
  1895. \begin{lstlisting}
  1896. (let ([x (let ([x 4])
  1897. (+ x 1))])
  1898. (+ x 2))
  1899. \end{lstlisting}
  1900. \end{minipage}
  1901. &
  1902. $\Rightarrow$
  1903. &
  1904. \begin{minipage}{0.4\textwidth}
  1905. \begin{lstlisting}
  1906. (let ([x.2 (let ([x.1 4])
  1907. (+ x.1 1))])
  1908. (+ x.2 2))
  1909. \end{lstlisting}
  1910. \end{minipage}
  1911. \end{tabular}
  1912. We recommend implementing \code{uniquify} by creating a structurally
  1913. recursive function named \code{uniquify-exp} that mostly just copies
  1914. an expression. However, when encountering a \key{let}, it should
  1915. generate a unique name for the variable and associate the old name
  1916. with the new name in an alist.\footnote{The Racket function
  1917. \code{gensym} is handy for generating unique variable names.} The
  1918. \code{uniquify-exp} function needs to access this alist when it gets
  1919. to a variable reference, so we add a parameter to \code{uniquify-exp}
  1920. for the alist.
  1921. The skeleton of the \code{uniquify-exp} function is shown in
  1922. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  1923. convenient to partially apply it to an alist and then apply it to
  1924. different expressions, as in the last case for primitive operations in
  1925. Figure~\ref{fig:uniquify-Rvar}. The
  1926. %
  1927. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1928. %
  1929. form of Racket is useful for transforming each element of a list to
  1930. produce a new list.\index{for/list}
  1931. \begin{exercise}
  1932. \normalfont % I don't like the italics for exercises. -Jeremy
  1933. Complete the \code{uniquify} pass by filling in the blanks in
  1934. Figure~\ref{fig:uniquify-Rvar}, that is, implement the cases for
  1935. variables and for the \key{let} form in the file \code{compiler.rkt}
  1936. in the support code.
  1937. \end{exercise}
  1938. \begin{figure}[tbp]
  1939. \begin{lstlisting}
  1940. (define (uniquify-exp env)
  1941. (lambda (e)
  1942. (match e
  1943. [(Var x) ___]
  1944. [(Int n) (Int n)]
  1945. [(Let x e body) ___]
  1946. [(Prim op es)
  1947. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  1948. (define (uniquify p)
  1949. (match p
  1950. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  1951. \end{lstlisting}
  1952. \caption{Skeleton for the \key{uniquify} pass.}
  1953. \label{fig:uniquify-Rvar}
  1954. \end{figure}
  1955. \begin{exercise}
  1956. \normalfont % I don't like the italics for exercises. -Jeremy
  1957. Create five \LangVar{} programs that exercise the most interesting
  1958. parts of the \key{uniquify} pass, that is, the programs should include
  1959. \key{let} forms, variables, and variables that overshadow each other.
  1960. The five programs should be placed in the subdirectory named
  1961. \key{tests} and the file names should start with \code{var\_test\_}
  1962. followed by a unique integer and end with the file extension
  1963. \key{.rkt}.
  1964. %
  1965. The \key{run-tests.rkt} script in the support code checks whether the
  1966. output programs produce the same result as the input programs. The
  1967. script uses the \key{interp-tests} function
  1968. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1969. your \key{uniquify} pass on the example programs. The \code{passes}
  1970. parameter of \key{interp-tests} is a list that should have one entry
  1971. for each pass in your compiler. For now, define \code{passes} to
  1972. contain just one entry for \code{uniquify} as follows.
  1973. \begin{lstlisting}
  1974. (define passes
  1975. (list (list "uniquify" uniquify interp-Rvar type-check-Rvar)))
  1976. \end{lstlisting}
  1977. Run the \key{run-tests.rkt} script in the support code to check
  1978. whether the output programs produce the same result as the input
  1979. programs.
  1980. \end{exercise}
  1981. \section{Remove Complex Operands}
  1982. \label{sec:remove-complex-opera-Rvar}
  1983. The \code{remove-complex-opera*} pass compiles \LangVar{} programs into
  1984. \LangVar{} programs in which the arguments of operations are atomic
  1985. expressions. Put another way, this pass removes complex
  1986. operands\index{complex operand}, such as the expression \code{(- 10)}
  1987. in the program below. This is accomplished by introducing a new
  1988. \key{let}-bound variable, binding the complex operand to the new
  1989. variable, and then using the new variable in place of the complex
  1990. operand, as shown in the output of \code{remove-complex-opera*} on the
  1991. right.\\
  1992. \begin{tabular}{lll}
  1993. \begin{minipage}{0.4\textwidth}
  1994. % var_test_19.rkt
  1995. \begin{lstlisting}
  1996. (+ 52 (- 10))
  1997. \end{lstlisting}
  1998. \end{minipage}
  1999. &
  2000. $\Rightarrow$
  2001. &
  2002. \begin{minipage}{0.4\textwidth}
  2003. \begin{lstlisting}
  2004. (let ([tmp.1 (- 10)])
  2005. (+ 52 tmp.1))
  2006. \end{lstlisting}
  2007. \end{minipage}
  2008. \end{tabular}
  2009. \begin{figure}[tp]
  2010. \centering
  2011. \fbox{
  2012. \begin{minipage}{0.96\textwidth}
  2013. \[
  2014. \begin{array}{rcl}
  2015. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  2016. \Exp &::=& \Atm \mid \READ{} \\
  2017. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  2018. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  2019. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  2020. \end{array}
  2021. \]
  2022. \end{minipage}
  2023. }
  2024. \caption{\LangVarANF{} is \LangVar{} in administrative normal form (ANF).}
  2025. \label{fig:r1-anf-syntax}
  2026. \end{figure}
  2027. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  2028. this pass, the language \LangVarANF{}. The only difference is that
  2029. operator arguments are required to be atomic expressions. In the
  2030. literature, this is called \emph{administrative normal form}, or ANF
  2031. for short~\citep{Danvy:1991fk,Flanagan:1993cg}. \index{administrative
  2032. normal form} \index{ANF}
  2033. We recommend implementing this pass with two mutually recursive
  2034. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  2035. \code{rco-atom} to subexpressions that are required to be atomic and
  2036. to apply \code{rco-exp} to subexpressions that can be atomic or
  2037. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  2038. \LangVar{} expression as input. The \code{rco-exp} function returns an
  2039. expression. The \code{rco-atom} function returns two things: an
  2040. atomic expression and alist mapping temporary variables to complex
  2041. subexpressions. You can return multiple things from a function using
  2042. Racket's \key{values} form and you can receive multiple things from a
  2043. function call using the \key{define-values} form. If you are not
  2044. familiar with these features, review the Racket documentation. Also,
  2045. the \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2046. form is useful for applying a function to each
  2047. element of a list, in the case where the function returns multiple
  2048. values.
  2049. \index{for/lists}
  2050. The following shows the output of \code{rco-atom} on the expression
  2051. \code{(- 10)} (using concrete syntax to be concise).
  2052. \begin{tabular}{lll}
  2053. \begin{minipage}{0.4\textwidth}
  2054. \begin{lstlisting}
  2055. (- 10)
  2056. \end{lstlisting}
  2057. \end{minipage}
  2058. &
  2059. $\Rightarrow$
  2060. &
  2061. \begin{minipage}{0.4\textwidth}
  2062. \begin{lstlisting}
  2063. tmp.1
  2064. ((tmp.1 . (- 10)))
  2065. \end{lstlisting}
  2066. \end{minipage}
  2067. \end{tabular}
  2068. Take special care of programs such as the following one that binds a
  2069. variable to an atomic expression. You should leave such variable
  2070. bindings unchanged, as shown in to the program on the right \\
  2071. \begin{tabular}{lll}
  2072. \begin{minipage}{0.4\textwidth}
  2073. % var_test_20.rkt
  2074. \begin{lstlisting}
  2075. (let ([a 42])
  2076. (let ([b a])
  2077. b))
  2078. \end{lstlisting}
  2079. \end{minipage}
  2080. &
  2081. $\Rightarrow$
  2082. &
  2083. \begin{minipage}{0.4\textwidth}
  2084. \begin{lstlisting}
  2085. (let ([a 42])
  2086. (let ([b a])
  2087. b))
  2088. \end{lstlisting}
  2089. \end{minipage}
  2090. \end{tabular} \\
  2091. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  2092. produce the following output with unnecessary temporary variables.\\
  2093. \begin{minipage}{0.4\textwidth}
  2094. \begin{lstlisting}
  2095. (let ([tmp.1 42])
  2096. (let ([a tmp.1])
  2097. (let ([tmp.2 a])
  2098. (let ([b tmp.2])
  2099. b))))
  2100. \end{lstlisting}
  2101. \end{minipage}
  2102. \begin{exercise}\normalfont
  2103. %
  2104. Implement the \code{remove-complex-opera*} function in
  2105. \code{compiler.rkt}.
  2106. %
  2107. Create three new \LangInt{} programs that exercise the interesting
  2108. code in the \code{remove-complex-opera*} pass (Following the same file
  2109. name guidelines as before.).
  2110. %
  2111. In the \code{run-tests.rkt} script, add the following entry to the
  2112. list of \code{passes} and then run the script to test your compiler.
  2113. \begin{lstlisting}
  2114. (list "remove-complex" remove-complex-opera* interp-Rvar type-check-Rvar)
  2115. \end{lstlisting}
  2116. While debugging your compiler, it is often useful to see the
  2117. intermediate programs that are output from each pass. To print the
  2118. intermeidate programs, place the following before the call to
  2119. \code{interp-tests} in \code{run-tests.rkt}.
  2120. \begin{lstlisting}
  2121. (debug-level 1)
  2122. \end{lstlisting}
  2123. \end{exercise}
  2124. \section{Explicate Control}
  2125. \label{sec:explicate-control-Rvar}
  2126. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  2127. programs that make the order of execution explicit in their
  2128. syntax. For now this amounts to flattening \key{let} constructs into a
  2129. sequence of assignment statements. For example, consider the following
  2130. \LangVar{} program.\\
  2131. % var_test_11.rkt
  2132. \begin{minipage}{0.96\textwidth}
  2133. \begin{lstlisting}
  2134. (let ([y (let ([x 20])
  2135. (+ x (let ([x 22]) x)))])
  2136. y)
  2137. \end{lstlisting}
  2138. \end{minipage}\\
  2139. %
  2140. The output of the previous pass and of \code{explicate-control} is
  2141. shown below. Recall that the right-hand-side of a \key{let} executes
  2142. before its body, so the order of evaluation for this program is to
  2143. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2144. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2145. output of \code{explicate-control} makes this ordering explicit.\\
  2146. \begin{tabular}{lll}
  2147. \begin{minipage}{0.4\textwidth}
  2148. \begin{lstlisting}
  2149. (let ([y (let ([x.1 20])
  2150. (let ([x.2 22])
  2151. (+ x.1 x.2)))])
  2152. y)
  2153. \end{lstlisting}
  2154. \end{minipage}
  2155. &
  2156. $\Rightarrow$
  2157. &
  2158. \begin{minipage}{0.4\textwidth}
  2159. \begin{lstlisting}[language=C]
  2160. start:
  2161. x.1 = 20;
  2162. x.2 = 22;
  2163. y = (+ x.1 x.2);
  2164. return y;
  2165. \end{lstlisting}
  2166. \end{minipage}
  2167. \end{tabular}
  2168. \begin{figure}[tbp]
  2169. \begin{lstlisting}
  2170. (define (explicate-tail e)
  2171. (match e
  2172. [(Var x) ___]
  2173. [(Int n) (Return (Int n))]
  2174. [(Let x rhs body) ___]
  2175. [(Prim op es) ___]
  2176. [else (error "explicate-tail unhandled case" e)]))
  2177. (define (explicate-assign e x cont)
  2178. (match e
  2179. [(Var x) ___]
  2180. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2181. [(Let y rhs body) ___]
  2182. [(Prim op es) ___]
  2183. [else (error "explicate-assign unhandled case" e)]))
  2184. (define (explicate-control p)
  2185. (match p
  2186. [(Program info body) ___]))
  2187. \end{lstlisting}
  2188. \caption{Skeleton for the \key{explicate-control} pass.}
  2189. \label{fig:explicate-control-Rvar}
  2190. \end{figure}
  2191. The organization of this pass depends on the notion of tail position
  2192. that we have alluded to earlier. Formally, \emph{tail
  2193. position}\index{tail position} in the context of \LangVar{} is
  2194. defined recursively by the following two rules.
  2195. \begin{enumerate}
  2196. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2197. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2198. \end{enumerate}
  2199. We recommend implementing \code{explicate-control} using two mutually
  2200. recursive functions, \code{explicate-tail} and
  2201. \code{explicate-assign}, as suggested in the skeleton code in
  2202. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2203. function should be applied to expressions in tail position whereas the
  2204. \code{explicate-assign} should be applied to expressions that occur on
  2205. the right-hand-side of a \key{let}.
  2206. %
  2207. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2208. input and produces a \Tail{} in \LangCVar{} (see
  2209. Figure~\ref{fig:c0-syntax}).
  2210. %
  2211. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2212. the variable that it is to be assigned to, and a \Tail{} in
  2213. \LangCVar{} for the code that will come after the assignment. The
  2214. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2215. The \code{explicate-assign} function is in accumulator-passing style
  2216. in that the \code{cont} parameter is used for accumulating the
  2217. output. The reader might be tempted to instead organize
  2218. \code{explicate-assign} in a more direct fashion, without the
  2219. \code{cont} parameter and perhaps using \code{append} to combine
  2220. statements. We warn against that alternative because the
  2221. accumulator-passing style is key to how we generate high-quality code
  2222. for conditional expressions in Chapter~\ref{ch:Rif}.
  2223. \begin{exercise}\normalfont
  2224. %
  2225. Implement the \code{explicate-control} function in
  2226. \code{compiler.rkt}. Create three new \LangInt{} programs that
  2227. exercise the code in \code{explicate-control}.
  2228. %
  2229. In the \code{run-tests.rkt} script, add the following entry to the
  2230. list of \code{passes} and then run the script to test your compiler.
  2231. \begin{lstlisting}
  2232. (list "explicate control" explicate-control interp-Cvar type-check-Cvar)
  2233. \end{lstlisting}
  2234. \end{exercise}
  2235. \section{Select Instructions}
  2236. \label{sec:select-Rvar}
  2237. \index{instruction selection}
  2238. In the \code{select-instructions} pass we begin the work of
  2239. translating from \LangCVar{} to \LangXVar{}. The target language of
  2240. this pass is a variant of x86 that still uses variables, so we add an
  2241. AST node of the form $\VAR{\itm{var}}$ to the \Arg{} non-terminal of
  2242. the \LangXInt{} abstract syntax (Figure~\ref{fig:x86-int-ast}). We
  2243. recommend implementing the \code{select-instructions} with
  2244. three auxiliary functions, one for each of the non-terminals of
  2245. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.
  2246. The cases for $\Atm$ are straightforward, variables stay
  2247. the same and integer constants are changed to immediates:
  2248. $\INT{n}$ changes to $\IMM{n}$.
  2249. Next we consider the cases for $\Stmt$, starting with arithmetic
  2250. operations. For example, consider the addition operation. We can use
  2251. the \key{addq} instruction, but it performs an in-place update. So we
  2252. could move $\itm{arg}_1$ into the left-hand side \itm{var} and then
  2253. add $\itm{arg}_2$ to \itm{var}. \\
  2254. \begin{tabular}{lll}
  2255. \begin{minipage}{0.4\textwidth}
  2256. \begin{lstlisting}
  2257. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2258. \end{lstlisting}
  2259. \end{minipage}
  2260. &
  2261. $\Rightarrow$
  2262. &
  2263. \begin{minipage}{0.4\textwidth}
  2264. \begin{lstlisting}
  2265. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2266. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2267. \end{lstlisting}
  2268. \end{minipage}
  2269. \end{tabular} \\
  2270. %
  2271. There are also cases that require special care to avoid generating
  2272. needlessly complicated code. For example, if one of the arguments of
  2273. the addition is the same variable as the left-hand side of the
  2274. assignment, then there is no need for the extra move instruction. The
  2275. assignment statement can be translated into a single \key{addq}
  2276. instruction as follows.\\
  2277. \begin{tabular}{lll}
  2278. \begin{minipage}{0.4\textwidth}
  2279. \begin{lstlisting}
  2280. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2281. \end{lstlisting}
  2282. \end{minipage}
  2283. &
  2284. $\Rightarrow$
  2285. &
  2286. \begin{minipage}{0.4\textwidth}
  2287. \begin{lstlisting}
  2288. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2289. \end{lstlisting}
  2290. \end{minipage}
  2291. \end{tabular}
  2292. The \key{read} operation does not have a direct counterpart in x86
  2293. assembly, so we provide this functionality with the function
  2294. \code{read\_int} in the file \code{runtime.c}, written in
  2295. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2296. functionality in this file as the \emph{runtime system}\index{runtime
  2297. system}, or simply the \emph{runtime} for short. When compiling your
  2298. generated x86 assembly code, you need to compile \code{runtime.c} to
  2299. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2300. \code{-c}) and link it into the executable. For our purposes of code
  2301. generation, all you need to do is translate an assignment of
  2302. \key{read} into a call to the \code{read\_int} function followed by a
  2303. move from \code{rax} to the left-hand-side variable. (Recall that the
  2304. return value of a function goes into \code{rax}.) \\
  2305. \begin{tabular}{lll}
  2306. \begin{minipage}{0.3\textwidth}
  2307. \begin{lstlisting}
  2308. |$\itm{var}$| = (read);
  2309. \end{lstlisting}
  2310. \end{minipage}
  2311. &
  2312. $\Rightarrow$
  2313. &
  2314. \begin{minipage}{0.3\textwidth}
  2315. \begin{lstlisting}
  2316. callq read_int
  2317. movq %rax, |$\itm{var}$|
  2318. \end{lstlisting}
  2319. \end{minipage}
  2320. \end{tabular}
  2321. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2322. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2323. assignment to the \key{rax} register followed by a jump to the
  2324. conclusion of the program (so the conclusion needs to be labeled).
  2325. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2326. recursively and then append the resulting instructions.
  2327. \begin{exercise}
  2328. \normalfont Implement the \key{select-instructions} pass in
  2329. \code{compiler.rkt}. Create three new example programs that are
  2330. designed to exercise all of the interesting cases in this pass.
  2331. %
  2332. In the \code{run-tests.rkt} script, add the following entry to the
  2333. list of \code{passes} and then run the script to test your compiler.
  2334. \begin{lstlisting}
  2335. (list "instruction selection" select-instructions interp-pseudo-x86-0)
  2336. \end{lstlisting}
  2337. \end{exercise}
  2338. \section{Assign Homes}
  2339. \label{sec:assign-Rvar}
  2340. The \key{assign-homes} pass compiles \LangXVar{} programs to
  2341. \LangXVar{} programs that no longer use program variables.
  2342. Thus, the \key{assign-homes} pass is responsible for placing all of
  2343. the program variables in registers or on the stack. For runtime
  2344. efficiency, it is better to place variables in registers, but as there
  2345. are only 16 registers, some programs must necessarily resort to
  2346. placing some variables on the stack. In this chapter we focus on the
  2347. mechanics of placing variables on the stack. We study an algorithm for
  2348. placing variables in registers in
  2349. Chapter~\ref{ch:register-allocation-Rvar}.
  2350. Consider again the following \LangVar{} program from
  2351. Section~\ref{sec:remove-complex-opera-Rvar}.
  2352. % var_test_20.rkt
  2353. \begin{lstlisting}
  2354. (let ([a 42])
  2355. (let ([b a])
  2356. b))
  2357. \end{lstlisting}
  2358. The output of \code{select-instructions} is shown on the left and the
  2359. output of \code{assign-homes} on the right. In this example, we
  2360. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  2361. variable \code{b} to location \code{-16(\%rbp)}.\\
  2362. \begin{tabular}{l}
  2363. \begin{minipage}{0.4\textwidth}
  2364. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2365. locals-types:
  2366. a : Integer, b : Integer
  2367. start:
  2368. movq $42, a
  2369. movq a, b
  2370. movq b, %rax
  2371. jmp conclusion
  2372. \end{lstlisting}
  2373. \end{minipage}
  2374. {$\Rightarrow$}
  2375. \begin{minipage}{0.4\textwidth}
  2376. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2377. stack-space: 16
  2378. start:
  2379. movq $42, -8(%rbp)
  2380. movq -8(%rbp), -16(%rbp)
  2381. movq -16(%rbp), %rax
  2382. jmp conclusion
  2383. \end{lstlisting}
  2384. \end{minipage}
  2385. \end{tabular}
  2386. The \code{locals-types} entry in the $\itm{info}$ of the
  2387. \code{X86Program} node is an alist mapping all the variables in the
  2388. program to their types (for now just \code{Integer}). The
  2389. \code{assign-homes} pass should replace all uses of those variables
  2390. with stack locations. As an aside, the \code{locals-types} entry is
  2391. computed by \code{type-check-Cvar} in the support code, which installs
  2392. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  2393. be propagated to the \code{X86Program} node.
  2394. In the process of assigning variables to stack locations, it is
  2395. convenient for you to compute and store the size of the frame (in
  2396. bytes) in the $\itm{info}$ field of the \key{X86Program} node, with
  2397. the key \code{stack-space}, which is needed later to generate the
  2398. conclusion of the \code{main} procedure. The x86-64 standard requires
  2399. the frame size to be a multiple of 16 bytes.\index{frame}
  2400. \begin{exercise}\normalfont
  2401. Implement the \key{assign-homes} pass in \code{compiler.rkt}, defining
  2402. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  2403. \Block{}. We recommend that the auxiliary functions take an extra
  2404. parameter that is an alist mapping variable names to homes (stack
  2405. locations for now).
  2406. %
  2407. In the \code{run-tests.rkt} script, add the following entry to the
  2408. list of \code{passes} and then run the script to test your compiler.
  2409. \begin{lstlisting}
  2410. (list "assign homes" assign-homes interp-x86-0)
  2411. \end{lstlisting}
  2412. \end{exercise}
  2413. \section{Patch Instructions}
  2414. \label{sec:patch-s0}
  2415. The \code{patch-instructions} pass compiles from \LangXVar{} to
  2416. \LangXInt{} by making sure that each instruction adheres to the
  2417. restriction that at most one argument of an instruction may be a
  2418. memory reference.
  2419. We return to the following example.
  2420. % var_test_20.rkt
  2421. \begin{lstlisting}
  2422. (let ([a 42])
  2423. (let ([b a])
  2424. b))
  2425. \end{lstlisting}
  2426. The \key{assign-homes} pass produces the following output
  2427. for this program. \\
  2428. \begin{minipage}{0.5\textwidth}
  2429. \begin{lstlisting}
  2430. stack-space: 16
  2431. start:
  2432. movq $42, -8(%rbp)
  2433. movq -8(%rbp), -16(%rbp)
  2434. movq -16(%rbp), %rax
  2435. jmp conclusion
  2436. \end{lstlisting}
  2437. \end{minipage}\\
  2438. The second \key{movq} instruction is problematic because both
  2439. arguments are stack locations. We suggest fixing this problem by
  2440. moving from the source location to the register \key{rax} and then
  2441. from \key{rax} to the destination location, as follows.
  2442. \begin{lstlisting}
  2443. movq -8(%rbp), %rax
  2444. movq %rax, -16(%rbp)
  2445. \end{lstlisting}
  2446. \begin{exercise}
  2447. \normalfont Implement the \key{patch-instructions} pass in
  2448. \code{compiler.rkt}. Create three new example programs that are
  2449. designed to exercise all of the interesting cases in this pass.
  2450. %
  2451. In the \code{run-tests.rkt} script, add the following entry to the
  2452. list of \code{passes} and then run the script to test your compiler.
  2453. \begin{lstlisting}
  2454. (list "patch instructions" patch-instructions interp-x86-0)
  2455. \end{lstlisting}
  2456. \end{exercise}
  2457. \section{Print x86}
  2458. \label{sec:print-x86}
  2459. The last step of the compiler from \LangVar{} to x86 is to convert the
  2460. \LangXInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  2461. string representation (defined in
  2462. Figure~\ref{fig:x86-int-concrete}). The Racket \key{format} and
  2463. \key{string-append} functions are useful in this regard. The main work
  2464. that this step needs to perform is to create the \key{main} function
  2465. and the standard instructions for its prelude and conclusion, as shown
  2466. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  2467. know the amount of space needed for the stack frame, which you can
  2468. obtain from the \code{stack-space} entry in the $\itm{info}$ field of
  2469. the \key{X86Program} node.
  2470. When running on Mac OS X, you compiler should prefix an underscore to
  2471. labels like \key{main}. The Racket call \code{(system-type 'os)} is
  2472. useful for determining which operating system the compiler is running
  2473. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.
  2474. \begin{exercise}\normalfont
  2475. %
  2476. Implement the \key{print-x86} pass in \code{compiler.rkt}.
  2477. %
  2478. In the \code{run-tests.rkt} script, add the following entry to the
  2479. list of \code{passes} and then run the script to test your compiler.
  2480. \begin{lstlisting}
  2481. (list "print x86" print-x86 #f)
  2482. \end{lstlisting}
  2483. %
  2484. Uncomment the call to the \key{compiler-tests} function
  2485. (Appendix~\ref{appendix:utilities}), which tests your complete
  2486. compiler by executing the generated x86 code. Compile the provided
  2487. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  2488. script to test your compiler.
  2489. \end{exercise}
  2490. \section{Challenge: Partial Evaluator for \LangVar{}}
  2491. \label{sec:pe-Rvar}
  2492. \index{partial evaluation}
  2493. This section describes optional challenge exercises that involve
  2494. adapting and improving the partial evaluator for \LangInt{} that was
  2495. introduced in Section~\ref{sec:partial-evaluation}.
  2496. \begin{exercise}\label{ex:pe-Rvar}
  2497. \normalfont
  2498. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2499. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  2500. instead of \LangInt{} programs. Recall that \LangVar{} adds \key{let} binding
  2501. and variables to the \LangInt{} language, so you will need to add cases for
  2502. them in the \code{pe-exp} function. Once complete, add the partial
  2503. evaluation pass to the front of your compiler and make sure that your
  2504. compiler still passes all of the tests.
  2505. \end{exercise}
  2506. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  2507. \begin{exercise}
  2508. \normalfont
  2509. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2510. \code{pe-add} auxiliary functions with functions that know more about
  2511. arithmetic. For example, your partial evaluator should translate
  2512. \[
  2513. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  2514. \code{(+ 2 (read))}
  2515. \]
  2516. To accomplish this, the \code{pe-exp} function should produce output
  2517. in the form of the $\itm{residual}$ non-terminal of the following
  2518. grammar. The idea is that when processing an addition expression, we
  2519. can always produce either 1) an integer constant, 2) and addition
  2520. expression with an integer constant on the left-hand side but not the
  2521. right-hand side, or 3) or an addition expression in which neither
  2522. subexpression is a constant.
  2523. \[
  2524. \begin{array}{lcl}
  2525. \itm{inert} &::=& \Var \mid \LP\key{read}\RP \mid \LP\key{-} \;\Var\RP
  2526. \mid \LP\key{-} \;\LP\key{read}\RP\RP
  2527. \mid \LP\key{+} \; \itm{inert} \; \itm{inert}\RP\\
  2528. &\mid& \LP\key{let}~\LP\LS\Var~\itm{inert}\RS\RP~ \itm{inert} \RP \\
  2529. \itm{residual} &::=& \Int \mid \LP\key{+}\; \Int\; \itm{inert}\RP \mid \itm{inert}
  2530. \end{array}
  2531. \]
  2532. The \code{pe-add} and \code{pe-neg} functions may assume that their
  2533. inputs are $\itm{residual}$ expressions and they should return
  2534. $\itm{residual}$ expressions. Once the improvements are complete,
  2535. make sure that your compiler still passes all of the tests. After
  2536. all, fast code is useless if it produces incorrect results!
  2537. \end{exercise}
  2538. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2539. \chapter{Register Allocation}
  2540. \label{ch:register-allocation-Rvar}
  2541. \index{register allocation}
  2542. In Chapter~\ref{ch:Rvar} we learned how to store variables on the
  2543. stack. In this Chapter we learn how to improve the performance of the
  2544. generated code by placing some variables into registers. The CPU can
  2545. access a register in a single cycle, whereas accessing the stack can
  2546. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  2547. serves as a running example. The source program is on the left and the
  2548. output of instruction selection is on the right. The program is almost
  2549. in the x86 assembly language but it still uses variables.
  2550. \begin{figure}
  2551. \begin{minipage}{0.45\textwidth}
  2552. Example \LangVar{} program:
  2553. % var_test_28.rkt
  2554. \begin{lstlisting}
  2555. (let ([v 1])
  2556. (let ([w 42])
  2557. (let ([x (+ v 7)])
  2558. (let ([y x])
  2559. (let ([z (+ x w)])
  2560. (+ z (- y)))))))
  2561. \end{lstlisting}
  2562. \end{minipage}
  2563. \begin{minipage}{0.45\textwidth}
  2564. After instruction selection:
  2565. \begin{lstlisting}
  2566. locals-types:
  2567. x : Integer, y : Integer,
  2568. z : Integer, t : Integer,
  2569. v : Integer, w : Integer
  2570. start:
  2571. movq $1, v
  2572. movq $42, w
  2573. movq v, x
  2574. addq $7, x
  2575. movq x, y
  2576. movq x, z
  2577. addq w, z
  2578. movq y, t
  2579. negq t
  2580. movq z, %rax
  2581. addq t, %rax
  2582. jmp conclusion
  2583. \end{lstlisting}
  2584. \end{minipage}
  2585. \caption{A running example for register allocation.}
  2586. \label{fig:reg-eg}
  2587. \end{figure}
  2588. The goal of register allocation is to fit as many variables into
  2589. registers as possible. Some programs have more variables than
  2590. registers so we cannot always map each variable to a different
  2591. register. Fortunately, it is common for different variables to be
  2592. needed during different periods of time during program execution, and
  2593. in such cases several variables can be mapped to the same register.
  2594. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  2595. After the variable \code{x} is moved to \code{z} it is no longer
  2596. needed. Variable \code{z}, on the other hand, is used only after this
  2597. point, so \code{x} and \code{z} could share the same register. The
  2598. topic of Section~\ref{sec:liveness-analysis-Rvar} is how to compute
  2599. where a variable is needed. Once we have that information, we compute
  2600. which variables are needed at the same time, i.e., which ones
  2601. \emph{interfere} with each other, and represent this relation as an
  2602. undirected graph whose vertices are variables and edges indicate when
  2603. two variables interfere (Section~\ref{sec:build-interference}). We
  2604. then model register allocation as a graph coloring problem
  2605. (Section~\ref{sec:graph-coloring}).
  2606. If we run out of registers despite these efforts, we place the
  2607. remaining variables on the stack, similar to what we did in
  2608. Chapter~\ref{ch:Rvar}. It is common to use the verb \emph{spill}
  2609. for assigning a variable to a stack location. The decision to spill a
  2610. variable is handled as part of the graph coloring process
  2611. (Section~\ref{sec:graph-coloring}).
  2612. We make the simplifying assumption that each variable is assigned to
  2613. one location (a register or stack address). A more sophisticated
  2614. approach is to assign a variable to one or more locations in different
  2615. regions of the program. For example, if a variable is used many times
  2616. in short sequence and then only used again after many other
  2617. instructions, it could be more efficient to assign the variable to a
  2618. register during the initial sequence and then move it to the stack for
  2619. the rest of its lifetime. We refer the interested reader to
  2620. \citet{Cooper:2011aa} for more information about that approach.
  2621. % discuss prioritizing variables based on how much they are used.
  2622. \section{Registers and Calling Conventions}
  2623. \label{sec:calling-conventions}
  2624. \index{calling conventions}
  2625. As we perform register allocation, we need to be aware of the
  2626. \emph{calling conventions} \index{calling conventions} that govern how
  2627. functions calls are performed in x86.
  2628. %
  2629. Even though \LangVar{} does not include programmer-defined functions,
  2630. our generated code includes a \code{main} function that is called by
  2631. the operating system and our generated code contains calls to the
  2632. \code{read\_int} function.
  2633. Function calls require coordination between two pieces of code that
  2634. may be written by different programmers or generated by different
  2635. compilers. Here we follow the System V calling conventions that are
  2636. used by the GNU C compiler on Linux and
  2637. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2638. %
  2639. The calling conventions include rules about how functions share the
  2640. use of registers. In particular, the caller is responsible for freeing
  2641. up some registers prior to the function call for use by the callee.
  2642. These are called the \emph{caller-saved registers}
  2643. \index{caller-saved registers}
  2644. and they are
  2645. \begin{lstlisting}
  2646. rax rcx rdx rsi rdi r8 r9 r10 r11
  2647. \end{lstlisting}
  2648. On the other hand, the callee is responsible for preserving the values
  2649. of the \emph{callee-saved registers}, \index{callee-saved registers}
  2650. which are
  2651. \begin{lstlisting}
  2652. rsp rbp rbx r12 r13 r14 r15
  2653. \end{lstlisting}
  2654. We can think about this caller/callee convention from two points of
  2655. view, the caller view and the callee view:
  2656. \begin{itemize}
  2657. \item The caller should assume that all the caller-saved registers get
  2658. overwritten with arbitrary values by the callee. On the other hand,
  2659. the caller can safely assume that all the callee-saved registers
  2660. contain the same values after the call that they did before the
  2661. call.
  2662. \item The callee can freely use any of the caller-saved registers.
  2663. However, if the callee wants to use a callee-saved register, the
  2664. callee must arrange to put the original value back in the register
  2665. prior to returning to the caller. This can be accomplished by saving
  2666. the value to the stack in the prelude of the function and restoring
  2667. the value in the conclusion of the function.
  2668. \end{itemize}
  2669. In x86, registers are also used for passing arguments to a function
  2670. and for the return value. In particular, the first six arguments to a
  2671. function are passed in the following six registers, in this order.
  2672. \begin{lstlisting}
  2673. rdi rsi rdx rcx r8 r9
  2674. \end{lstlisting}
  2675. If there are more than six arguments, then the convention is to use
  2676. space on the frame of the caller for the rest of the
  2677. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  2678. need more than six arguments. For now, the only function we care about
  2679. is \code{read\_int} and it takes zero arguments.
  2680. %
  2681. The register \code{rax} is used for the return value of a function.
  2682. The next question is how these calling conventions impact register
  2683. allocation. Consider the \LangVar{} program in
  2684. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2685. example from the caller point of view and then from the callee point
  2686. of view.
  2687. The program makes two calls to the \code{read} function. Also, the
  2688. variable \code{x} is in use during the second call to \code{read}, so
  2689. we need to make sure that the value in \code{x} does not get
  2690. accidentally wiped out by the call to \code{read}. One obvious
  2691. approach is to save all the values in caller-saved registers to the
  2692. stack prior to each function call, and restore them after each
  2693. call. That way, if the register allocator chooses to assign \code{x}
  2694. to a caller-saved register, its value will be preserved across the
  2695. call to \code{read}. However, saving and restoring to the stack is
  2696. relatively slow. If \code{x} is not used many times, it may be better
  2697. to assign \code{x} to a stack location in the first place. Or better
  2698. yet, if we can arrange for \code{x} to be placed in a callee-saved
  2699. register, then it won't need to be saved and restored during function
  2700. calls.
  2701. The approach that we recommend for variables that are in use during a
  2702. function call is to either assign them to callee-saved registers or to
  2703. spill them to the stack. On the other hand, for variables that are not
  2704. in use during a function call, we try the following alternatives in
  2705. order 1) look for an available caller-saved register (to leave room
  2706. for other variables in the callee-saved register), 2) look for a
  2707. callee-saved register, and 3) spill the variable to the stack.
  2708. It is straightforward to implement this approach in a graph coloring
  2709. register allocator. First, we know which variables are in use during
  2710. every function call because we compute that information for every
  2711. instruction (Section~\ref{sec:liveness-analysis-Rvar}). Second, when we
  2712. build the interference graph (Section~\ref{sec:build-interference}),
  2713. we can place an edge between each of these variables and the
  2714. caller-saved registers in the interference graph. This will prevent
  2715. the graph coloring algorithm from assigning those variables to
  2716. caller-saved registers.
  2717. Returning to the example in
  2718. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2719. generated x86 code on the right-hand side, focusing on the
  2720. \code{start} block. Notice that variable \code{x} is assigned to
  2721. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2722. place during the second call to \code{read\_int}. Next, notice that
  2723. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2724. because there are no function calls in the remainder of the block.
  2725. Next we analyze the example from the callee point of view, focusing on
  2726. the prelude and conclusion of the \code{main} function. As usual the
  2727. prelude begins with saving the \code{rbp} register to the stack and
  2728. setting the \code{rbp} to the current stack pointer. We now know why
  2729. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2730. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2731. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  2732. (\code{x}). The other callee-saved registers are not saved in the
  2733. prelude because they are not used. The prelude subtracts 8 bytes from
  2734. the \code{rsp} to make it 16-byte aligned and then jumps to the
  2735. \code{start} block. Shifting attention to the \code{conclusion}, we
  2736. see that \code{rbx} is restored from the stack with a \code{popq}
  2737. instruction. \index{prelude}\index{conclusion}
  2738. \begin{figure}[tp]
  2739. \begin{minipage}{0.45\textwidth}
  2740. Example \LangVar{} program:
  2741. %var_test_14.rkt
  2742. \begin{lstlisting}
  2743. (let ([x (read)])
  2744. (let ([y (read)])
  2745. (+ (+ x y) 42)))
  2746. \end{lstlisting}
  2747. \end{minipage}
  2748. \begin{minipage}{0.45\textwidth}
  2749. Generated x86 assembly:
  2750. \begin{lstlisting}
  2751. start:
  2752. callq read_int
  2753. movq %rax, %rbx
  2754. callq read_int
  2755. movq %rax, %rcx
  2756. addq %rcx, %rbx
  2757. movq %rbx, %rax
  2758. addq $42, %rax
  2759. jmp _conclusion
  2760. .globl main
  2761. main:
  2762. pushq %rbp
  2763. movq %rsp, %rbp
  2764. pushq %rbx
  2765. subq $8, %rsp
  2766. jmp start
  2767. conclusion:
  2768. addq $8, %rsp
  2769. popq %rbx
  2770. popq %rbp
  2771. retq
  2772. \end{lstlisting}
  2773. \end{minipage}
  2774. \caption{An example with function calls.}
  2775. \label{fig:example-calling-conventions}
  2776. \end{figure}
  2777. \clearpage
  2778. \section{Liveness Analysis}
  2779. \label{sec:liveness-analysis-Rvar}
  2780. \index{liveness analysis}
  2781. The \code{uncover-live} pass performs \emph{liveness analysis}, that
  2782. is, it discovers which variables are in-use in different regions of a
  2783. program.
  2784. %
  2785. A variable or register is \emph{live} at a program point if its
  2786. current value is used at some later point in the program. We
  2787. refer to variables and registers collectively as \emph{locations}.
  2788. %
  2789. Consider the following code fragment in which there are two writes to
  2790. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2791. \begin{center}
  2792. \begin{minipage}{0.96\textwidth}
  2793. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2794. movq $5, a
  2795. movq $30, b
  2796. movq a, c
  2797. movq $10, b
  2798. addq b, c
  2799. \end{lstlisting}
  2800. \end{minipage}
  2801. \end{center}
  2802. The answer is no because \code{a} is live from line 1 to 3 and
  2803. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  2804. line 2 is never used because it is overwritten (line 4) before the
  2805. next read (line 5).
  2806. \begin{wrapfigure}[19]{l}[1.0in]{0.6\textwidth}
  2807. \small
  2808. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2809. A \emph{set} is an unordered collection of elements without duplicates.
  2810. \index{set}
  2811. \begin{description}
  2812. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2813. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2814. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2815. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2816. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2817. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2818. \end{description}
  2819. \end{tcolorbox}
  2820. \end{wrapfigure}
  2821. The live locations can be computed by traversing the instruction
  2822. sequence back to front (i.e., backwards in execution order). Let
  2823. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2824. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2825. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2826. locations before instruction $I_k$. The live locations after an
  2827. instruction are always the same as the live locations before the next
  2828. instruction. \index{live-after} \index{live-before}
  2829. \begin{equation} \label{eq:live-after-before-next}
  2830. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2831. \end{equation}
  2832. To start things off, there are no live locations after the last
  2833. instruction, so
  2834. \begin{equation}\label{eq:live-last-empty}
  2835. L_{\mathsf{after}}(n) = \emptyset
  2836. \end{equation}
  2837. We then apply the following rule repeatedly, traversing the
  2838. instruction sequence back to front.
  2839. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2840. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2841. \end{equation}
  2842. where $W(k)$ are the locations written to by instruction $I_k$ and
  2843. $R(k)$ are the locations read by instruction $I_k$.
  2844. There is a special case for \code{jmp} instructions. The locations
  2845. that are live before a \code{jmp} should be the locations in
  2846. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  2847. maintaining an alist named \code{label->live} that maps each label to
  2848. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  2849. now the only \code{jmp} in a \LangXVar{} program is the one at the
  2850. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  2851. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  2852. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  2853. Let us walk through the above example, applying these formulas
  2854. starting with the instruction on line 5. We collect the answers in
  2855. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  2856. \code{addq b, c} instruction is $\emptyset$ because it is the last
  2857. instruction (formula~\ref{eq:live-last-empty}). The
  2858. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  2859. because it reads from variables \code{b} and \code{c}
  2860. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2861. \[
  2862. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2863. \]
  2864. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2865. the live-before set from line 5 to be the live-after set for this
  2866. instruction (formula~\ref{eq:live-after-before-next}).
  2867. \[
  2868. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2869. \]
  2870. This move instruction writes to \code{b} and does not read from any
  2871. variables, so we have the following live-before set
  2872. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2873. \[
  2874. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2875. \]
  2876. The live-before for instruction \code{movq a, c}
  2877. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2878. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2879. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2880. variable that is not live and does not read from a variable.
  2881. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2882. because it writes to variable \code{a}.
  2883. \begin{figure}[tbp]
  2884. \begin{minipage}{0.45\textwidth}
  2885. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2886. movq $5, a
  2887. movq $30, b
  2888. movq a, c
  2889. movq $10, b
  2890. addq b, c
  2891. \end{lstlisting}
  2892. \end{minipage}
  2893. \vrule\hspace{10pt}
  2894. \begin{minipage}{0.45\textwidth}
  2895. \begin{align*}
  2896. L_{\mathsf{before}}(1)= \emptyset,
  2897. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2898. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2899. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2900. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2901. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2902. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2903. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2904. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2905. L_{\mathsf{after}}(5)= \emptyset
  2906. \end{align*}
  2907. \end{minipage}
  2908. \caption{Example output of liveness analysis on a short example.}
  2909. \label{fig:liveness-example-0}
  2910. \end{figure}
  2911. \begin{exercise}\normalfont
  2912. Perform liveness analysis on the running example in
  2913. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  2914. sets for each instruction. Compare your answers to the solution
  2915. shown in Figure~\ref{fig:live-eg}.
  2916. \end{exercise}
  2917. \begin{figure}[tp]
  2918. \hspace{20pt}
  2919. \begin{minipage}{0.45\textwidth}
  2920. \begin{lstlisting}
  2921. |$\{\ttm{rsp}\}$|
  2922. movq $1, v
  2923. |$\{\ttm{v},\ttm{rsp}\}$|
  2924. movq $42, w
  2925. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  2926. movq v, x
  2927. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2928. addq $7, x
  2929. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2930. movq x, y
  2931. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  2932. movq x, z
  2933. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2934. addq w, z
  2935. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2936. movq y, t
  2937. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2938. negq t
  2939. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2940. movq z, %rax
  2941. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  2942. addq t, %rax
  2943. |$\{\ttm{rax},\ttm{rsp}\}$|
  2944. jmp conclusion
  2945. \end{lstlisting}
  2946. \end{minipage}
  2947. \caption{The running example annotated with live-after sets.}
  2948. \label{fig:live-eg}
  2949. \end{figure}
  2950. \begin{exercise}\normalfont
  2951. Implement the \code{uncover-live} pass. Store the sequence of
  2952. live-after sets in the $\itm{info}$ field of the \code{Block}
  2953. structure.
  2954. %
  2955. We recommend creating an auxiliary function that takes a list of
  2956. instructions and an initial live-after set (typically empty) and
  2957. returns the list of live-after sets.
  2958. %
  2959. We also recommend creating auxiliary functions to 1) compute the set
  2960. of locations that appear in an \Arg{}, 2) compute the locations read
  2961. by an instruction (the $R$ function), and 3) the locations written by
  2962. an instruction (the $W$ function). The \code{callq} instruction should
  2963. include all of the caller-saved registers in its write-set $W$ because
  2964. the calling convention says that those registers may be written to
  2965. during the function call. Likewise, the \code{callq} instruction
  2966. should include the appropriate argument-passing registers in its
  2967. read-set $R$, depending on the arity of the function being
  2968. called. (This is why the abstract syntax for \code{callq} includes the
  2969. arity.)
  2970. \end{exercise}
  2971. \clearpage
  2972. \section{Build the Interference Graph}
  2973. \label{sec:build-interference}
  2974. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  2975. \small
  2976. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2977. A \emph{graph} is a collection of vertices and edges where each
  2978. edge connects two vertices. A graph is \emph{directed} if each
  2979. edge points from a source to a target. Otherwise the graph is
  2980. \emph{undirected}.
  2981. \index{graph}\index{directed graph}\index{undirected graph}
  2982. \begin{description}
  2983. %% We currently don't use directed graphs. We instead use
  2984. %% directed multi-graphs. -Jeremy
  2985. %% \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2986. %% directed graph from a list of edges. Each edge is a list
  2987. %% containing the source and target vertex.
  2988. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2989. undirected graph from a list of edges. Each edge is represented by
  2990. a list containing two vertices.
  2991. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2992. inserts a vertex into the graph.
  2993. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2994. inserts an edge between the two vertices into the graph.
  2995. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2996. returns a sequence of all the neighbors of the given vertex.
  2997. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2998. returns a sequence of all the vertices in the graph.
  2999. \end{description}
  3000. \end{tcolorbox}
  3001. \end{wrapfigure}
  3002. Based on the liveness analysis, we know where each location is live.
  3003. However, during register allocation, we need to answer questions of
  3004. the specific form: are locations $u$ and $v$ live at the same time?
  3005. (And therefore cannot be assigned to the same register.) To make this
  3006. question more efficient to answer, we create an explicit data
  3007. structure, an \emph{interference graph}\index{interference graph}. An
  3008. interference graph is an undirected graph that has an edge between two
  3009. locations if they are live at the same time, that is, if they
  3010. interfere with each other.
  3011. An obvious way to compute the interference graph is to look at the set
  3012. of live locations between each instruction and the next and add an edge to the graph
  3013. for every pair of variables in the same set. This approach is less
  3014. than ideal for two reasons. First, it can be expensive because it
  3015. takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  3016. locations. Second, in the special case where two locations hold the
  3017. same value (because one was assigned to the other), they can be live
  3018. at the same time without interfering with each other.
  3019. A better way to compute the interference graph is to focus on
  3020. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  3021. must not overwrite something in a live location. So for each
  3022. instruction, we create an edge between the locations being written to
  3023. and the live locations. (Except that one should not create self
  3024. edges.) Note that for the \key{callq} instruction, we consider all of
  3025. the caller-saved registers as being written to, so an edge is added
  3026. between every live variable and every caller-saved register. For
  3027. \key{movq}, we deal with the above-mentioned special case by not
  3028. adding an edge between a live variable $v$ and the destination if $v$
  3029. matches the source. So we have the following two rules.
  3030. \begin{enumerate}
  3031. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  3032. $d$, then add the edge $(d,v)$ for every $v \in
  3033. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  3034. \item For any other instruction $I_k$, for every $d \in W(k)$
  3035. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  3036. %% \item If instruction $I_k$ is an arithmetic instruction such as
  3037. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  3038. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  3039. %% \item If instruction $I_k$ is of the form \key{callq}
  3040. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  3041. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  3042. \end{enumerate}
  3043. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  3044. the above rules to each instruction. We highlight a few of the
  3045. instructions. The first instruction is \lstinline{movq $1, v} and the
  3046. live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies, so \code{v}
  3047. interferes with \code{rsp}.
  3048. %
  3049. The fourth instruction is \lstinline{addq $7, x} and the live-after
  3050. set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so $\ttm{x}$
  3051. interferes with \ttm{w} and \ttm{rsp}.
  3052. %
  3053. The next instruction is \lstinline{movq x, y} and the live-after set
  3054. is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1 applies, so \ttm{y}
  3055. interferes with \ttm{w} and \ttm{rsp} but not \ttm{x} because \ttm{x}
  3056. is the source of the move and therefore \ttm{x} and \ttm{y} hold the
  3057. same value. Figure~\ref{fig:interference-results} lists the
  3058. interference results for all of the instructions and the resulting
  3059. interference graph is shown in Figure~\ref{fig:interfere}.
  3060. \begin{figure}[tbp]
  3061. \begin{quote}
  3062. \begin{tabular}{ll}
  3063. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  3064. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  3065. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3066. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3067. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  3068. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  3069. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  3070. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3071. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3072. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  3073. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  3074. \lstinline!jmp conclusion!& no interference.
  3075. \end{tabular}
  3076. \end{quote}
  3077. \caption{Interference results for the running example.}
  3078. \label{fig:interference-results}
  3079. \end{figure}
  3080. \begin{figure}[tbp]
  3081. \large
  3082. \[
  3083. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3084. \node (rax) at (0,0) {$\ttm{rax}$};
  3085. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3086. \node (t1) at (0,2) {$\ttm{t}$};
  3087. \node (z) at (3,2) {$\ttm{z}$};
  3088. \node (x) at (6,2) {$\ttm{x}$};
  3089. \node (y) at (3,0) {$\ttm{y}$};
  3090. \node (w) at (6,0) {$\ttm{w}$};
  3091. \node (v) at (9,0) {$\ttm{v}$};
  3092. \draw (t1) to (rax);
  3093. \draw (t1) to (z);
  3094. \draw (z) to (y);
  3095. \draw (z) to (w);
  3096. \draw (x) to (w);
  3097. \draw (y) to (w);
  3098. \draw (v) to (w);
  3099. \draw (v) to (rsp);
  3100. \draw (w) to (rsp);
  3101. \draw (x) to (rsp);
  3102. \draw (y) to (rsp);
  3103. \path[-.,bend left=15] (z) edge node {} (rsp);
  3104. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3105. \draw (rax) to (rsp);
  3106. \end{tikzpicture}
  3107. \]
  3108. \caption{The interference graph of the example program.}
  3109. \label{fig:interfere}
  3110. \end{figure}
  3111. %% Our next concern is to choose a data structure for representing the
  3112. %% interference graph. There are many choices for how to represent a
  3113. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  3114. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  3115. %% data structure is to study the algorithm that uses the data structure,
  3116. %% determine what operations need to be performed, and then choose the
  3117. %% data structure that provide the most efficient implementations of
  3118. %% those operations. Often times the choice of data structure can have an
  3119. %% effect on the time complexity of the algorithm, as it does here. If
  3120. %% you skim the next section, you will see that the register allocation
  3121. %% algorithm needs to ask the graph for all of its vertices and, given a
  3122. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  3123. %% correct choice of graph representation is that of an adjacency
  3124. %% list. There are helper functions in \code{utilities.rkt} for
  3125. %% representing graphs using the adjacency list representation:
  3126. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  3127. %% (Appendix~\ref{appendix:utilities}).
  3128. %% %
  3129. %% \margincomment{\footnotesize To do: change to use the
  3130. %% Racket graph library. \\ --Jeremy}
  3131. %% %
  3132. %% In particular, those functions use a hash table to map each vertex to
  3133. %% the set of adjacent vertices, and the sets are represented using
  3134. %% Racket's \key{set}, which is also a hash table.
  3135. \begin{exercise}\normalfont
  3136. Implement the compiler pass named \code{build-interference} according
  3137. to the algorithm suggested above. We recommend using the \code{graph}
  3138. package to create and inspect the interference graph. The output
  3139. graph of this pass should be stored in the $\itm{info}$ field of the
  3140. program, under the key \code{conflicts}.
  3141. \end{exercise}
  3142. \section{Graph Coloring via Sudoku}
  3143. \label{sec:graph-coloring}
  3144. \index{graph coloring}
  3145. \index{Sudoku}
  3146. \index{color}
  3147. We come to the main event, mapping variables to registers and stack
  3148. locations. Variables that interfere with each other must be mapped to
  3149. different locations. In terms of the interference graph, this means
  3150. that adjacent vertices must be mapped to different locations. If we
  3151. think of locations as colors, the register allocation problem becomes
  3152. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  3153. The reader may be more familiar with the graph coloring problem than he
  3154. or she realizes; the popular game of Sudoku is an instance of the
  3155. graph coloring problem. The following describes how to build a graph
  3156. out of an initial Sudoku board.
  3157. \begin{itemize}
  3158. \item There is one vertex in the graph for each Sudoku square.
  3159. \item There is an edge between two vertices if the corresponding squares
  3160. are in the same row, in the same column, or if the squares are in
  3161. the same $3\times 3$ region.
  3162. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  3163. \item Based on the initial assignment of numbers to squares in the
  3164. Sudoku board, assign the corresponding colors to the corresponding
  3165. vertices in the graph.
  3166. \end{itemize}
  3167. If you can color the remaining vertices in the graph with the nine
  3168. colors, then you have also solved the corresponding game of Sudoku.
  3169. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  3170. the corresponding graph with colored vertices. We map the Sudoku
  3171. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  3172. sampling of the vertices (the colored ones) because showing edges for
  3173. all of the vertices would make the graph unreadable.
  3174. \begin{figure}[tbp]
  3175. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  3176. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  3177. \caption{A Sudoku game board and the corresponding colored graph.}
  3178. \label{fig:sudoku-graph}
  3179. \end{figure}
  3180. It turns out that some techniques for playing Sudoku correspond to
  3181. heuristics used in graph coloring algorithms. For example, one of the
  3182. basic techniques for Sudoku is called Pencil Marks. The idea is to use
  3183. a process of elimination to determine what numbers are no longer
  3184. available for a square and write down those numbers in the square
  3185. (writing very small). For example, if the number $1$ is assigned to a
  3186. square, then write the pencil mark $1$ in all the squares in the same
  3187. row, column, and region.
  3188. %
  3189. The Pencil Marks technique corresponds to the notion of
  3190. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}. The
  3191. saturation of a vertex, in Sudoku terms, is the set of numbers that
  3192. are no longer available. In graph terminology, we have the following
  3193. definition:
  3194. \begin{equation*}
  3195. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  3196. \text{ and } \mathrm{color}(v) = c \}
  3197. \end{equation*}
  3198. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  3199. edge with $u$.
  3200. Using the Pencil Marks technique leads to a simple strategy for
  3201. filling in numbers: if there is a square with only one possible number
  3202. left, then choose that number! But what if there are no squares with
  3203. only one possibility left? One brute-force approach is to try them
  3204. all: choose the first one and if it ultimately leads to a solution,
  3205. great. If not, backtrack and choose the next possibility. One good
  3206. thing about Pencil Marks is that it reduces the degree of branching in
  3207. the search tree. Nevertheless, backtracking can be horribly time
  3208. consuming. One way to reduce the amount of backtracking is to use the
  3209. most-constrained-first heuristic. That is, when choosing a square,
  3210. always choose one with the fewest possibilities left (the vertex with
  3211. the highest saturation). The idea is that choosing highly constrained
  3212. squares earlier rather than later is better because later on there may
  3213. not be any possibilities left in the highly saturated squares.
  3214. However, register allocation is easier than Sudoku because the
  3215. register allocator can map variables to stack locations when the
  3216. registers run out. Thus, it makes sense to replace backtracking with
  3217. greedy search: make the best choice at the time and keep going. We
  3218. still wish to minimize the number of colors needed, so we use the
  3219. most-constrained-first heuristic in the greedy search.
  3220. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3221. algorithm for register allocation based on saturation and the
  3222. most-constrained-first heuristic. It is roughly equivalent to the
  3223. DSATUR
  3224. algorithm~\citep{Brelaz:1979eu,Gebremedhin:1999fk,Omari:2006uq}. Just
  3225. as in Sudoku, the algorithm represents colors with integers. The
  3226. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  3227. for register allocation. The integers $k$ and larger correspond to
  3228. stack locations. The registers that are not used for register
  3229. allocation, such as \code{rax}, are assigned to negative integers. In
  3230. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3231. %% One might wonder why we include registers at all in the liveness
  3232. %% analysis and interference graph. For example, we never allocate a
  3233. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  3234. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  3235. %% to use register for passing arguments to functions, it will be
  3236. %% necessary for those registers to appear in the interference graph
  3237. %% because those registers will also be assigned to variables, and we
  3238. %% don't want those two uses to encroach on each other. Regarding
  3239. %% registers such as \code{rax} and \code{rsp} that are not used for
  3240. %% variables, we could omit them from the interference graph but that
  3241. %% would require adding special cases to our algorithm, which would
  3242. %% complicate the logic for little gain.
  3243. \begin{figure}[btp]
  3244. \centering
  3245. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3246. Algorithm: DSATUR
  3247. Input: a graph |$G$|
  3248. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3249. |$W \gets \mathrm{vertices}(G)$|
  3250. while |$W \neq \emptyset$| do
  3251. pick a vertex |$u$| from |$W$| with the highest saturation,
  3252. breaking ties randomly
  3253. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3254. |$\mathrm{color}[u] \gets c$|
  3255. |$W \gets W - \{u\}$|
  3256. \end{lstlisting}
  3257. \caption{The saturation-based greedy graph coloring algorithm.}
  3258. \label{fig:satur-algo}
  3259. \end{figure}
  3260. With the DSATUR algorithm in hand, let us return to the running
  3261. example and consider how to color the interference graph in
  3262. Figure~\ref{fig:interfere}.
  3263. %
  3264. We start by assigning the register nodes to their own color. For
  3265. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  3266. assigned $-2$. The variables are not yet colored, so they are
  3267. annotated with a dash. We then update the saturation for vertices that
  3268. are adjacent to a register, obtaining the following annotated
  3269. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  3270. it interferes with both \code{rax} and \code{rsp}.
  3271. \[
  3272. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3273. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3274. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3275. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3276. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3277. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3278. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3279. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3280. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3281. \draw (t1) to (rax);
  3282. \draw (t1) to (z);
  3283. \draw (z) to (y);
  3284. \draw (z) to (w);
  3285. \draw (x) to (w);
  3286. \draw (y) to (w);
  3287. \draw (v) to (w);
  3288. \draw (v) to (rsp);
  3289. \draw (w) to (rsp);
  3290. \draw (x) to (rsp);
  3291. \draw (y) to (rsp);
  3292. \path[-.,bend left=15] (z) edge node {} (rsp);
  3293. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3294. \draw (rax) to (rsp);
  3295. \end{tikzpicture}
  3296. \]
  3297. The algorithm says to select a maximally saturated vertex. So we pick
  3298. $\ttm{t}$ and color it with the first available integer, which is
  3299. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3300. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3301. \[
  3302. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3303. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3304. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3305. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3306. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3307. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3308. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3309. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3310. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3311. \draw (t1) to (rax);
  3312. \draw (t1) to (z);
  3313. \draw (z) to (y);
  3314. \draw (z) to (w);
  3315. \draw (x) to (w);
  3316. \draw (y) to (w);
  3317. \draw (v) to (w);
  3318. \draw (v) to (rsp);
  3319. \draw (w) to (rsp);
  3320. \draw (x) to (rsp);
  3321. \draw (y) to (rsp);
  3322. \path[-.,bend left=15] (z) edge node {} (rsp);
  3323. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3324. \draw (rax) to (rsp);
  3325. \end{tikzpicture}
  3326. \]
  3327. We repeat the process, selecting the next maximally saturated vertex,
  3328. which is \code{z}, and color it with the first available number, which
  3329. is $1$. We add $1$ to the saturation for the neighboring vertices
  3330. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3331. \[
  3332. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3333. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3334. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3335. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3336. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3337. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3338. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3339. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3340. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3341. \draw (t1) to (rax);
  3342. \draw (t1) to (z);
  3343. \draw (z) to (y);
  3344. \draw (z) to (w);
  3345. \draw (x) to (w);
  3346. \draw (y) to (w);
  3347. \draw (v) to (w);
  3348. \draw (v) to (rsp);
  3349. \draw (w) to (rsp);
  3350. \draw (x) to (rsp);
  3351. \draw (y) to (rsp);
  3352. \path[-.,bend left=15] (z) edge node {} (rsp);
  3353. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3354. \draw (rax) to (rsp);
  3355. \end{tikzpicture}
  3356. \]
  3357. The most saturated vertices are now \code{w} and \code{y}. We color
  3358. \code{w} with the first available color, which is $0$.
  3359. \[
  3360. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3361. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3362. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3363. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3364. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3365. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3366. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  3367. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  3368. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3369. \draw (t1) to (rax);
  3370. \draw (t1) to (z);
  3371. \draw (z) to (y);
  3372. \draw (z) to (w);
  3373. \draw (x) to (w);
  3374. \draw (y) to (w);
  3375. \draw (v) to (w);
  3376. \draw (v) to (rsp);
  3377. \draw (w) to (rsp);
  3378. \draw (x) to (rsp);
  3379. \draw (y) to (rsp);
  3380. \path[-.,bend left=15] (z) edge node {} (rsp);
  3381. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3382. \draw (rax) to (rsp);
  3383. \end{tikzpicture}
  3384. \]
  3385. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3386. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3387. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3388. and \code{z}, whose colors are $0$ and $1$ respectively.
  3389. \[
  3390. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3391. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3392. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3393. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3394. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3395. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3396. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3397. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3398. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3399. \draw (t1) to (rax);
  3400. \draw (t1) to (z);
  3401. \draw (z) to (y);
  3402. \draw (z) to (w);
  3403. \draw (x) to (w);
  3404. \draw (y) to (w);
  3405. \draw (v) to (w);
  3406. \draw (v) to (rsp);
  3407. \draw (w) to (rsp);
  3408. \draw (x) to (rsp);
  3409. \draw (y) to (rsp);
  3410. \path[-.,bend left=15] (z) edge node {} (rsp);
  3411. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3412. \draw (rax) to (rsp);
  3413. \end{tikzpicture}
  3414. \]
  3415. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  3416. \[
  3417. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3418. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3419. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3420. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3421. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3422. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3423. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3424. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3425. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3426. \draw (t1) to (rax);
  3427. \draw (t1) to (z);
  3428. \draw (z) to (y);
  3429. \draw (z) to (w);
  3430. \draw (x) to (w);
  3431. \draw (y) to (w);
  3432. \draw (v) to (w);
  3433. \draw (v) to (rsp);
  3434. \draw (w) to (rsp);
  3435. \draw (x) to (rsp);
  3436. \draw (y) to (rsp);
  3437. \path[-.,bend left=15] (z) edge node {} (rsp);
  3438. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3439. \draw (rax) to (rsp);
  3440. \end{tikzpicture}
  3441. \]
  3442. In the last step of the algorithm, we color \code{x} with $1$.
  3443. \[
  3444. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3445. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3446. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3447. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3448. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3449. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  3450. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3451. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3452. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3453. \draw (t1) to (rax);
  3454. \draw (t1) to (z);
  3455. \draw (z) to (y);
  3456. \draw (z) to (w);
  3457. \draw (x) to (w);
  3458. \draw (y) to (w);
  3459. \draw (v) to (w);
  3460. \draw (v) to (rsp);
  3461. \draw (w) to (rsp);
  3462. \draw (x) to (rsp);
  3463. \draw (y) to (rsp);
  3464. \path[-.,bend left=15] (z) edge node {} (rsp);
  3465. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3466. \draw (rax) to (rsp);
  3467. \end{tikzpicture}
  3468. \]
  3469. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  3470. \small
  3471. \begin{tcolorbox}[title=Priority Queue]
  3472. A \emph{priority queue} is a collection of items in which the
  3473. removal of items is governed by priority. In a ``min'' queue,
  3474. lower priority items are removed first. An implementation is in
  3475. \code{priority\_queue.rkt} of the support code. \index{priority
  3476. queue} \index{minimum priority queue}
  3477. \begin{description}
  3478. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3479. priority queue that uses the $\itm{cmp}$ predicate to determine
  3480. whether its first argument has lower or equal priority to its
  3481. second argument.
  3482. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3483. items in the queue.
  3484. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3485. the item into the queue and returns a handle for the item in the
  3486. queue.
  3487. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3488. the lowest priority.
  3489. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3490. notifies the queue that the priority has decreased for the item
  3491. associated with the given handle.
  3492. \end{description}
  3493. \end{tcolorbox}
  3494. \end{wrapfigure}
  3495. We recommend creating an auxiliary function named \code{color-graph}
  3496. that takes an interference graph and a list of all the variables in
  3497. the program. This function should return a mapping of variables to
  3498. their colors (represented as natural numbers). By creating this helper
  3499. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  3500. when we add support for functions.
  3501. To prioritize the processing of highly saturated nodes inside the
  3502. \code{color-graph} function, we recommend using the priority queue
  3503. data structure (see the side bar on the right). In addition, you will
  3504. need to maintain a mapping from variables to their ``handles'' in the
  3505. priority queue so that you can notify the priority queue when their
  3506. saturation changes.
  3507. With the coloring complete, we finalize the assignment of variables to
  3508. registers and stack locations. We map the first $k$ colors to the $k$
  3509. registers and the rest of the colors to stack locations. Suppose for
  3510. the moment that we have just one register to use for register
  3511. allocation, \key{rcx}. Then we have the following map from colors to
  3512. locations.
  3513. \[
  3514. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3515. \]
  3516. Composing this mapping with the coloring, we arrive at the following
  3517. assignment of variables to locations.
  3518. \begin{gather*}
  3519. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  3520. \ttm{w} \mapsto \key{\%rcx}, \,
  3521. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3522. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3523. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3524. \ttm{t} \mapsto \key{\%rcx} \}
  3525. \end{gather*}
  3526. Adapt the code from the \code{assign-homes} pass
  3527. (Section~\ref{sec:assign-Rvar}) to replace the variables with their
  3528. assigned location. Applying the above assignment to our running
  3529. example, on the left, yields the program on the right.
  3530. % why frame size of 32? -JGS
  3531. \begin{center}
  3532. \begin{minipage}{0.3\textwidth}
  3533. \begin{lstlisting}
  3534. movq $1, v
  3535. movq $42, w
  3536. movq v, x
  3537. addq $7, x
  3538. movq x, y
  3539. movq x, z
  3540. addq w, z
  3541. movq y, t
  3542. negq t
  3543. movq z, %rax
  3544. addq t, %rax
  3545. jmp conclusion
  3546. \end{lstlisting}
  3547. \end{minipage}
  3548. $\Rightarrow\qquad$
  3549. \begin{minipage}{0.45\textwidth}
  3550. \begin{lstlisting}
  3551. movq $1, -8(%rbp)
  3552. movq $42, %rcx
  3553. movq -8(%rbp), -8(%rbp)
  3554. addq $7, -8(%rbp)
  3555. movq -8(%rbp), -16(%rbp)
  3556. movq -8(%rbp), -8(%rbp)
  3557. addq %rcx, -8(%rbp)
  3558. movq -16(%rbp), %rcx
  3559. negq %rcx
  3560. movq -8(%rbp), %rax
  3561. addq %rcx, %rax
  3562. jmp conclusion
  3563. \end{lstlisting}
  3564. \end{minipage}
  3565. \end{center}
  3566. \begin{exercise}\normalfont
  3567. %
  3568. Implement the compiler pass \code{allocate-registers}.
  3569. %
  3570. Create five programs that exercise all of the register allocation
  3571. algorithm, including spilling variables to the stack.
  3572. %
  3573. Replace \code{assign-homes} in the list of \code{passes} in the
  3574. \code{run-tests.rkt} script with the three new passes:
  3575. \code{uncover-live}, \code{build-interference}, and
  3576. \code{allocate-registers}.
  3577. %
  3578. Temporarily remove the \code{print-x86} pass from the list of passes
  3579. and the call to \code{compiler-tests}.
  3580. %
  3581. Run the script to test the register allocator.
  3582. \end{exercise}
  3583. \section{Patch Instructions}
  3584. \label{sec:patch-instructions}
  3585. The remaining step in the compilation to x86 is to ensure that the
  3586. instructions have at most one argument that is a memory access.
  3587. In the running example, the instruction \code{movq -8(\%rbp), -16(\%rbp)}
  3588. is problematic. The fix is to first move \code{-8(\%rbp)}
  3589. into \code{rax} and then move \code{rax} into \code{-16(\%rbp)}.
  3590. %
  3591. The two moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  3592. problematic, but they can be fixed by simply deleting them. In
  3593. general, we recommend deleting all the trivial moves whose source and
  3594. destination are the same location.
  3595. %
  3596. The following is the output of \code{patch-instructions} on the
  3597. running example.
  3598. \begin{center}
  3599. \begin{minipage}{0.4\textwidth}
  3600. \begin{lstlisting}
  3601. movq $1, -8(%rbp)
  3602. movq $42, %rcx
  3603. movq -8(%rbp), -8(%rbp)
  3604. addq $7, -8(%rbp)
  3605. movq -8(%rbp), -16(%rbp)
  3606. movq -8(%rbp), -8(%rbp)
  3607. addq %rcx, -8(%rbp)
  3608. movq -16(%rbp), %rcx
  3609. negq %rcx
  3610. movq -8(%rbp), %rax
  3611. addq %rcx, %rax
  3612. jmp conclusion
  3613. \end{lstlisting}
  3614. \end{minipage}
  3615. $\Rightarrow\qquad$
  3616. \begin{minipage}{0.45\textwidth}
  3617. \begin{lstlisting}
  3618. movq $1, -8(%rbp)
  3619. movq $42, %rcx
  3620. addq $7, -8(%rbp)
  3621. movq -8(%rbp), %rax
  3622. movq %rax, -16(%rbp)
  3623. addq %rcx, -8(%rbp)
  3624. movq -16(%rbp), %rcx
  3625. negq %rcx
  3626. movq -8(%rbp), %rax
  3627. addq %rcx, %rax
  3628. jmp conclusion
  3629. \end{lstlisting}
  3630. \end{minipage}
  3631. \end{center}
  3632. \begin{exercise}\normalfont
  3633. %
  3634. Implement the \code{patch-instructions} compiler pass.
  3635. %
  3636. Insert it after \code{allocate-registers} in the list of \code{passes}
  3637. in the \code{run-tests.rkt} script.
  3638. %
  3639. Run the script to test the \code{patch-instructions} pass.
  3640. \end{exercise}
  3641. \section{Print x86}
  3642. \label{sec:print-x86-reg-alloc}
  3643. \index{calling conventions}
  3644. \index{prelude}\index{conclusion}
  3645. Recall that the \code{print-x86} pass generates the prelude and
  3646. conclusion instructions to satisfy the x86 calling conventions
  3647. (Section~\ref{sec:calling-conventions}). With the addition of the
  3648. register allocator, the callee-saved registers used by the register
  3649. allocator must be saved in the prelude and restored in the conclusion.
  3650. In the \code{allocate-registers} pass, add an entry to the \itm{info}
  3651. of \code{X86Program} named \code{used-callee} that stores the set of
  3652. callee-saved registers that were assigned to variables. The
  3653. \code{print-x86} pass can then access this information to decide which
  3654. callee-saved registers need to be saved and restored.
  3655. %
  3656. When calculating the size of the frame to adjust the \code{rsp} in the
  3657. prelude, make sure to take into account the space used for saving the
  3658. callee-saved registers. Also, don't forget that the frame needs to be
  3659. a multiple of 16 bytes!
  3660. An overview of all of the passes involved in register allocation is
  3661. shown in Figure~\ref{fig:reg-alloc-passes}.
  3662. \begin{figure}[tbp]
  3663. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3664. \node (Rvar) at (0,2) {\large \LangVar{}};
  3665. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  3666. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  3667. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  3668. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  3669. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  3670. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  3671. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  3672. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  3673. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  3674. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  3675. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  3676. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-1);
  3677. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3678. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  3679. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3680. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3681. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3682. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3683. \end{tikzpicture}
  3684. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  3685. \label{fig:reg-alloc-passes}
  3686. \end{figure}
  3687. \begin{exercise}\normalfont
  3688. Update the \code{print-x86} pass as described in this section.
  3689. %
  3690. In the \code{run-tests.rkt} script, reinstate \code{print-x86} in the
  3691. list of passes and the call to \code{compiler-tests}.
  3692. %
  3693. Run the script to test the complete compiler for \LangVar{} that
  3694. performs register allocation.
  3695. \end{exercise}
  3696. \section{Challenge: Move Biasing}
  3697. \label{sec:move-biasing}
  3698. \index{move biasing}
  3699. This section describes an enhancement to the register allocator for
  3700. students looking for an extra challenge or who have a deeper interest
  3701. in register allocation.
  3702. To motivate the need for move biasing we return to the running example
  3703. but this time use all of the general purpose registers. So we have
  3704. the following mapping of color numbers to registers.
  3705. \[
  3706. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  3707. \]
  3708. Using the same assignment of variables to color numbers that was
  3709. produced by the register allocator described in the last section, we
  3710. get the following program.
  3711. \begin{center}
  3712. \begin{minipage}{0.3\textwidth}
  3713. \begin{lstlisting}
  3714. movq $1, v
  3715. movq $42, w
  3716. movq v, x
  3717. addq $7, x
  3718. movq x, y
  3719. movq x, z
  3720. addq w, z
  3721. movq y, t
  3722. negq t
  3723. movq z, %rax
  3724. addq t, %rax
  3725. jmp conclusion
  3726. \end{lstlisting}
  3727. \end{minipage}
  3728. $\Rightarrow\qquad$
  3729. \begin{minipage}{0.45\textwidth}
  3730. \begin{lstlisting}
  3731. movq $1, %rdx
  3732. movq $42, %rcx
  3733. movq %rdx, %rdx
  3734. addq $7, %rdx
  3735. movq %rdx, %rsi
  3736. movq %rdx, %rdx
  3737. addq %rcx, %rdx
  3738. movq %rsi, %rcx
  3739. negq %rcx
  3740. movq %rdx, %rax
  3741. addq %rcx, %rax
  3742. jmp conclusion
  3743. \end{lstlisting}
  3744. \end{minipage}
  3745. \end{center}
  3746. In the above output code there are two \key{movq} instructions that
  3747. can be removed because their source and target are the same. However,
  3748. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3749. register, we could instead remove three \key{movq} instructions. We
  3750. can accomplish this by taking into account which variables appear in
  3751. \key{movq} instructions with which other variables.
  3752. We say that two variables $p$ and $q$ are \emph{move
  3753. related}\index{move related} if they participate together in a
  3754. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3755. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3756. for a variable, it should prefer a color that has already been used
  3757. for a move-related variable (assuming that they do not interfere). Of
  3758. course, this preference should not override the preference for
  3759. registers over stack locations. This preference should be used as a
  3760. tie breaker when choosing between registers or when choosing between
  3761. stack locations.
  3762. We recommend representing the move relationships in a graph, similar
  3763. to how we represented interference. The following is the \emph{move
  3764. graph} for our running example.
  3765. \[
  3766. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3767. \node (rax) at (0,0) {$\ttm{rax}$};
  3768. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3769. \node (t) at (0,2) {$\ttm{t}$};
  3770. \node (z) at (3,2) {$\ttm{z}$};
  3771. \node (x) at (6,2) {$\ttm{x}$};
  3772. \node (y) at (3,0) {$\ttm{y}$};
  3773. \node (w) at (6,0) {$\ttm{w}$};
  3774. \node (v) at (9,0) {$\ttm{v}$};
  3775. \draw (v) to (x);
  3776. \draw (x) to (y);
  3777. \draw (x) to (z);
  3778. \draw (y) to (t);
  3779. \end{tikzpicture}
  3780. \]
  3781. Now we replay the graph coloring, pausing to see the coloring of
  3782. \code{y}. Recall the following configuration. The most saturated vertices
  3783. were \code{w} and \code{y}.
  3784. \[
  3785. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3786. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3787. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3788. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3789. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3790. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3791. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3792. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3793. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3794. \draw (t1) to (rax);
  3795. \draw (t1) to (z);
  3796. \draw (z) to (y);
  3797. \draw (z) to (w);
  3798. \draw (x) to (w);
  3799. \draw (y) to (w);
  3800. \draw (v) to (w);
  3801. \draw (v) to (rsp);
  3802. \draw (w) to (rsp);
  3803. \draw (x) to (rsp);
  3804. \draw (y) to (rsp);
  3805. \path[-.,bend left=15] (z) edge node {} (rsp);
  3806. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3807. \draw (rax) to (rsp);
  3808. \end{tikzpicture}
  3809. \]
  3810. %
  3811. Last time we chose to color \code{w} with $0$. But this time we see
  3812. that \code{w} is not move related to any vertex, but \code{y} is move
  3813. related to \code{t}. So we choose to color \code{y} the same color as
  3814. \code{t}, $0$.
  3815. \[
  3816. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3817. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3818. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3819. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3820. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3821. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3822. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  3823. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  3824. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3825. \draw (t1) to (rax);
  3826. \draw (t1) to (z);
  3827. \draw (z) to (y);
  3828. \draw (z) to (w);
  3829. \draw (x) to (w);
  3830. \draw (y) to (w);
  3831. \draw (v) to (w);
  3832. \draw (v) to (rsp);
  3833. \draw (w) to (rsp);
  3834. \draw (x) to (rsp);
  3835. \draw (y) to (rsp);
  3836. \path[-.,bend left=15] (z) edge node {} (rsp);
  3837. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3838. \draw (rax) to (rsp);
  3839. \end{tikzpicture}
  3840. \]
  3841. Now \code{w} is the most saturated, so we color it $2$.
  3842. \[
  3843. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3844. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3845. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3846. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3847. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3848. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  3849. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3850. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3851. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  3852. \draw (t1) to (rax);
  3853. \draw (t1) to (z);
  3854. \draw (z) to (y);
  3855. \draw (z) to (w);
  3856. \draw (x) to (w);
  3857. \draw (y) to (w);
  3858. \draw (v) to (w);
  3859. \draw (v) to (rsp);
  3860. \draw (w) to (rsp);
  3861. \draw (x) to (rsp);
  3862. \draw (y) to (rsp);
  3863. \path[-.,bend left=15] (z) edge node {} (rsp);
  3864. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3865. \draw (rax) to (rsp);
  3866. \end{tikzpicture}
  3867. \]
  3868. At this point, vertices \code{x} and \code{v} are most saturated, but
  3869. \code{x} is move related to \code{y} and \code{z}, so we color
  3870. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3871. \[
  3872. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3873. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3874. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3875. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3876. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3877. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  3878. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3879. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3880. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  3881. \draw (t1) to (rax);
  3882. \draw (t) to (z);
  3883. \draw (z) to (y);
  3884. \draw (z) to (w);
  3885. \draw (x) to (w);
  3886. \draw (y) to (w);
  3887. \draw (v) to (w);
  3888. \draw (v) to (rsp);
  3889. \draw (w) to (rsp);
  3890. \draw (x) to (rsp);
  3891. \draw (y) to (rsp);
  3892. \path[-.,bend left=15] (z) edge node {} (rsp);
  3893. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3894. \draw (rax) to (rsp);
  3895. \end{tikzpicture}
  3896. \]
  3897. So we have the following assignment of variables to registers.
  3898. \begin{gather*}
  3899. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3900. \ttm{w} \mapsto \key{\%rsi}, \,
  3901. \ttm{x} \mapsto \key{\%rcx}, \,
  3902. \ttm{y} \mapsto \key{\%rcx}, \,
  3903. \ttm{z} \mapsto \key{\%rdx}, \,
  3904. \ttm{t} \mapsto \key{\%rcx} \}
  3905. \end{gather*}
  3906. We apply this register assignment to the running example, on the left,
  3907. to obtain the code in the middle. The \code{patch-instructions} then
  3908. removes the three trivial moves to obtain the code on the right.
  3909. \begin{minipage}{0.25\textwidth}
  3910. \begin{lstlisting}
  3911. movq $1, v
  3912. movq $42, w
  3913. movq v, x
  3914. addq $7, x
  3915. movq x, y
  3916. movq x, z
  3917. addq w, z
  3918. movq y, t
  3919. negq t
  3920. movq z, %rax
  3921. addq t, %rax
  3922. jmp conclusion
  3923. \end{lstlisting}
  3924. \end{minipage}
  3925. $\Rightarrow\qquad$
  3926. \begin{minipage}{0.25\textwidth}
  3927. \begin{lstlisting}
  3928. movq $1, %rcx
  3929. movq $42, %rsi
  3930. movq %rcx, %rcx
  3931. addq $7, %rcx
  3932. movq %rcx, %rcx
  3933. movq %rcx, %rdx
  3934. addq %rsi, %rdx
  3935. movq %rcx, %rcx
  3936. negq %rcx
  3937. movq %rdx, %rax
  3938. addq %rcx, %rax
  3939. jmp conclusion
  3940. \end{lstlisting}
  3941. \end{minipage}
  3942. $\Rightarrow\qquad$
  3943. \begin{minipage}{0.25\textwidth}
  3944. \begin{lstlisting}
  3945. movq $1, %rcx
  3946. movq $42, %rsi
  3947. addq $7, %rcx
  3948. movq %rcx, %rdx
  3949. addq %rsi, %rdx
  3950. negq %rcx
  3951. movq %rdx, %rax
  3952. addq %rcx, %rax
  3953. jmp conclusion
  3954. \end{lstlisting}
  3955. \end{minipage}
  3956. \begin{exercise}\normalfont
  3957. Change your implementation of \code{allocate-registers} to take move
  3958. biasing into account. Create two new tests that include at least one
  3959. opportunity for move biasing and visually inspect the output x86
  3960. programs to make sure that your move biasing is working properly. Make
  3961. sure that your compiler still passes all of the tests.
  3962. \end{exercise}
  3963. \margincomment{\footnotesize To do: another neat challenge would be to do
  3964. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3965. %% \subsection{Output of the Running Example}
  3966. %% \label{sec:reg-alloc-output}
  3967. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3968. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3969. and move biasing. To demonstrate both the use of registers and the
  3970. stack, we have limited the register allocator to use just two
  3971. registers: \code{rbx} and \code{rcx}. In the prelude\index{prelude}
  3972. of the \code{main} function, we push \code{rbx} onto the stack because
  3973. it is a callee-saved register and it was assigned to variable by the
  3974. register allocator. We subtract \code{8} from the \code{rsp} at the
  3975. end of the prelude to reserve space for the one spilled variable.
  3976. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3977. Moving on the the \code{start} block, we see how the registers were
  3978. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3979. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3980. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3981. that the prelude saved the callee-save register \code{rbx} onto the
  3982. stack. The spilled variables must be placed lower on the stack than
  3983. the saved callee-save registers, so in this case \code{w} is placed at
  3984. \code{-16(\%rbp)}.
  3985. In the \code{conclusion}\index{conclusion}, we undo the work that was
  3986. done in the prelude. We move the stack pointer up by \code{8} bytes
  3987. (the room for spilled variables), then we pop the old values of
  3988. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  3989. \code{retq} to return control to the operating system.
  3990. \begin{figure}[tbp]
  3991. % var_test_28.rkt
  3992. % (use-minimal-set-of-registers! #t)
  3993. % and only rbx rcx
  3994. % tmp 0 rbx
  3995. % z 1 rcx
  3996. % y 0 rbx
  3997. % w 2 16(%rbp)
  3998. % v 0 rbx
  3999. % x 0 rbx
  4000. \begin{lstlisting}
  4001. start:
  4002. movq $1, %rbx
  4003. movq $42, -16(%rbp)
  4004. addq $7, %rbx
  4005. movq %rbx, %rcx
  4006. addq -16(%rbp), %rcx
  4007. negq %rbx
  4008. movq %rcx, %rax
  4009. addq %rbx, %rax
  4010. jmp conclusion
  4011. .globl main
  4012. main:
  4013. pushq %rbp
  4014. movq %rsp, %rbp
  4015. pushq %rbx
  4016. subq $8, %rsp
  4017. jmp start
  4018. conclusion:
  4019. addq $8, %rsp
  4020. popq %rbx
  4021. popq %rbp
  4022. retq
  4023. \end{lstlisting}
  4024. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  4025. \label{fig:running-example-x86}
  4026. \end{figure}
  4027. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4028. \chapter{Booleans and Control Flow}
  4029. \label{ch:Rif}
  4030. \index{Boolean}
  4031. \index{control flow}
  4032. \index{conditional expression}
  4033. The \LangInt{} and \LangVar{} languages only have a single kind of
  4034. value, integers. In this chapter we add a second kind of value, the
  4035. Booleans, to create the \LangIf{} language. The Boolean values
  4036. \emph{true} and \emph{false} are written \key{\#t} and \key{\#f}
  4037. respectively in Racket. The \LangIf{} language includes several
  4038. operations that involve Booleans (\key{and}, \key{not}, \key{eq?},
  4039. \key{<}, etc.) and the conditional \key{if} expression. With the
  4040. addition of \key{if}, programs can have non-trivial control flow which
  4041. impacts \code{explicate-control} and liveness analysis. Also, because
  4042. we now have two kinds of values, we need to handle programs that apply
  4043. an operation to the wrong kind of value, such as \code{(not 1)}.
  4044. There are two language design options for such situations. One option
  4045. is to signal an error and the other is to provide a wider
  4046. interpretation of the operation. The Racket language uses a mixture of
  4047. these two options, depending on the operation and the kind of
  4048. value. For example, the result of \code{(not 1)} in Racket is
  4049. \code{\#f} because Racket treats non-zero integers as if they were
  4050. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  4051. error in Racket because \code{car} expects a pair.
  4052. Typed Racket makes similar design choices as Racket, except much of
  4053. the error detection happens at compile time instead of run time. Typed
  4054. Racket accepts and runs \code{(not 1)}, producing \code{\#f}. But in
  4055. the case of \code{(car 1)}, Typed Racket reports a compile-time error
  4056. because Typed Racket expects the type of the argument to be of the
  4057. form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  4058. The \LangIf{} language performs type checking during compilation like
  4059. Typed Racket. In Chapter~\ref{ch:type-dynamic} we study the
  4060. alternative choice, that is, a dynamically typed language like Racket.
  4061. The \LangIf{} language is a subset of Typed Racket; for some
  4062. operations we are more restrictive, for example, rejecting
  4063. \code{(not 1)}.
  4064. This chapter is organized as follows. We begin by defining the syntax
  4065. and interpreter for the \LangIf{} language
  4066. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  4067. checking and build a type checker for \LangIf{}
  4068. (Section~\ref{sec:type-check-Rif}). To compile \LangIf{} we need to
  4069. enlarge the intermediate language \LangCVar{} into \LangCIf{}
  4070. (Section~\ref{sec:Cif}) and \LangXInt{} into \LangXIf{}
  4071. (Section~\ref{sec:x86-if}). The remaining sections of this chapter
  4072. discuss how our compiler passes change to accommodate Booleans and
  4073. conditional control flow. There is one new pass, named \code{shrink},
  4074. that translates some operators into others, thereby reducing the
  4075. number of operators that need to be handled in later passes. The
  4076. largest changes occur in \code{explicate-control}, to translate
  4077. \code{if} expressions into control-flow graphs
  4078. (Section~\ref{sec:explicate-control-Rif}). Regarding register
  4079. allocation, the liveness analysis now has multiple basic blocks to
  4080. process and there is the interesting question of how to handle
  4081. conditional jumps.
  4082. \section{The \LangIf{} Language}
  4083. \label{sec:lang-if}
  4084. The concrete syntax of the \LangIf{} language is defined in
  4085. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  4086. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  4087. \LangVar{} (shown in gray), the Boolean literals \code{\#t} and
  4088. \code{\#f}, and the conditional \code{if} expression. We expand the
  4089. operators to include
  4090. \begin{enumerate}
  4091. \item subtraction on integers,
  4092. \item the logical operators \key{and}, \key{or} and \key{not},
  4093. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  4094. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  4095. comparing integers.
  4096. \end{enumerate}
  4097. We reorganize the abstract syntax for the primitive operations in
  4098. Figure~\ref{fig:Rif-syntax}, using only one grammar rule for all of
  4099. them. This means that the grammar no longer checks whether the arity
  4100. of an operators matches the number of arguments. That responsibility
  4101. is moved to the type checker for \LangIf{}, which we introduce in
  4102. Section~\ref{sec:type-check-Rif}.
  4103. \begin{figure}[tp]
  4104. \centering
  4105. \fbox{
  4106. \begin{minipage}{0.96\textwidth}
  4107. \[
  4108. \begin{array}{lcl}
  4109. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4110. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4111. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  4112. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  4113. &\mid& \itm{bool}
  4114. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  4115. \mid (\key{not}\;\Exp) \\
  4116. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  4117. \LangIf{} &::=& \Exp
  4118. \end{array}
  4119. \]
  4120. \end{minipage}
  4121. }
  4122. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  4123. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  4124. \label{fig:Rif-concrete-syntax}
  4125. \end{figure}
  4126. \begin{figure}[tp]
  4127. \centering
  4128. \fbox{
  4129. \begin{minipage}{0.96\textwidth}
  4130. \[
  4131. \begin{array}{lcl}
  4132. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  4133. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  4134. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  4135. \mid \code{and} \mid \code{or} \mid \code{not} \\
  4136. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4137. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  4138. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4139. \LangIf{} &::=& \PROGRAM{\code{'()}}{\Exp}
  4140. \end{array}
  4141. \]
  4142. \end{minipage}
  4143. }
  4144. \caption{The abstract syntax of \LangIf{}.}
  4145. \label{fig:Rif-syntax}
  4146. \end{figure}
  4147. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  4148. which inherits from the interpreter for \LangVar{}
  4149. (Figure~\ref{fig:interp-Rvar}). The literals \code{\#t} and \code{\#f}
  4150. evaluate to the corresponding Boolean values. The conditional
  4151. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  4152. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  4153. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  4154. operations \code{not} and \code{and} behave as you might expect, but
  4155. note that the \code{and} operation is short-circuiting. That is, given
  4156. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  4157. evaluated if $e_1$ evaluates to \code{\#f}.
  4158. With the increase in the number of primitive operations, the
  4159. interpreter would become repetitive without some care. We refactor
  4160. the case for \code{Prim}, moving the code that differs with each
  4161. operation into the \code{interp-op} method shown in in
  4162. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  4163. separately because of its short-circuiting behavior.
  4164. \begin{figure}[tbp]
  4165. \begin{lstlisting}
  4166. (define interp-Rif-class
  4167. (class interp-Rvar-class
  4168. (super-new)
  4169. (define/public (interp-op op) ...)
  4170. (define/override ((interp-exp env) e)
  4171. (define recur (interp-exp env))
  4172. (match e
  4173. [(Bool b) b]
  4174. [(If cnd thn els)
  4175. (match (recur cnd)
  4176. [#t (recur thn)]
  4177. [#f (recur els)])]
  4178. [(Prim 'and (list e1 e2))
  4179. (match (recur e1)
  4180. [#t (match (recur e2) [#t #t] [#f #f])]
  4181. [#f #f])]
  4182. [(Prim op args)
  4183. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  4184. [else ((super interp-exp env) e)]))
  4185. ))
  4186. (define (interp-Rif p)
  4187. (send (new interp-Rif-class) interp-program p))
  4188. \end{lstlisting}
  4189. \caption{Interpreter for the \LangIf{} language. (See
  4190. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  4191. \label{fig:interp-Rif}
  4192. \end{figure}
  4193. \begin{figure}[tbp]
  4194. \begin{lstlisting}
  4195. (define/public (interp-op op)
  4196. (match op
  4197. ['+ fx+]
  4198. ['- fx-]
  4199. ['read read-fixnum]
  4200. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  4201. ['or (lambda (v1 v2)
  4202. (cond [(and (boolean? v1) (boolean? v2))
  4203. (or v1 v2)]))]
  4204. ['eq? (lambda (v1 v2)
  4205. (cond [(or (and (fixnum? v1) (fixnum? v2))
  4206. (and (boolean? v1) (boolean? v2))
  4207. (and (vector? v1) (vector? v2)))
  4208. (eq? v1 v2)]))]
  4209. ['< (lambda (v1 v2)
  4210. (cond [(and (fixnum? v1) (fixnum? v2))
  4211. (< v1 v2)]))]
  4212. ['<= (lambda (v1 v2)
  4213. (cond [(and (fixnum? v1) (fixnum? v2))
  4214. (<= v1 v2)]))]
  4215. ['> (lambda (v1 v2)
  4216. (cond [(and (fixnum? v1) (fixnum? v2))
  4217. (> v1 v2)]))]
  4218. ['>= (lambda (v1 v2)
  4219. (cond [(and (fixnum? v1) (fixnum? v2))
  4220. (>= v1 v2)]))]
  4221. [else (error 'interp-op "unknown operator")]))
  4222. \end{lstlisting}
  4223. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  4224. \label{fig:interp-op-Rif}
  4225. \end{figure}
  4226. \section{Type Checking \LangIf{} Programs}
  4227. \label{sec:type-check-Rif}
  4228. \index{type checking}
  4229. \index{semantic analysis}
  4230. It is helpful to think about type checking in two complementary
  4231. ways. A type checker predicts the type of value that will be produced
  4232. by each expression in the program. For \LangIf{}, we have just two types,
  4233. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4234. \begin{lstlisting}
  4235. (+ 10 (- (+ 12 20)))
  4236. \end{lstlisting}
  4237. produces an \key{Integer} while
  4238. \begin{lstlisting}
  4239. (and (not #f) #t)
  4240. \end{lstlisting}
  4241. produces a \key{Boolean}.
  4242. Another way to think about type checking is that it enforces a set of
  4243. rules about which operators can be applied to which kinds of
  4244. values. For example, our type checker for \LangIf{} signals an error
  4245. for the below expression
  4246. \begin{lstlisting}
  4247. (not (+ 10 (- (+ 12 20))))
  4248. \end{lstlisting}
  4249. The subexpression \code{(+ 10 (- (+ 12 20)))} has type \key{Integer}
  4250. but the type checker enforces the rule that the argument of \code{not}
  4251. must be a \key{Boolean}.
  4252. We implement type checking using classes and methods because they
  4253. provide the open recursion needed to reuse code as we extend the type
  4254. checker in later chapters, analogous to the use of classes and methods
  4255. for the interpreters (Section~\ref{sec:extensible-interp}).
  4256. We separate the type checker for the \LangVar{} fragment into its own
  4257. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  4258. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  4259. from the type checker for \LangVar{}. These type checkers are in the
  4260. files \code{type-check-Rvar.rkt} and \code{type-check-Rif.rkt} of the
  4261. support code.
  4262. %
  4263. Each type checker is a structurally recursive function over the AST.
  4264. Given an input expression \code{e}, the type checker either signals an
  4265. error or returns an expression and its type (\key{Integer} or
  4266. \key{Boolean}). It returns an expression because there are situations
  4267. in which we want to change or update the expression.
  4268. Next we discuss the \code{match} cases in \code{type-check-exp} of
  4269. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  4270. \code{Integer}. To handle variables, the type checker uses the
  4271. environment \code{env} to map variables to types. Consider the case
  4272. for \key{let}. We type check the initializing expression to obtain
  4273. its type \key{T} and then associate type \code{T} with the variable
  4274. \code{x} in the environment used to type check the body of the
  4275. \key{let}. Thus, when the type checker encounters a use of variable
  4276. \code{x}, it can find its type in the environment. Regarding
  4277. primitive operators, we recursively analyze the arguments and then
  4278. invoke \code{type-check-op} to check whether the argument types are
  4279. allowed.
  4280. Several auxiliary methods are used in the type checker. The method
  4281. \code{operator-types} defines a dictionary that maps the operator
  4282. names to their parameter and return types. The \code{type-equal?}
  4283. method determines whether two types are equal, which for now simply
  4284. dispatches to \code{equal?} (deep equality). The
  4285. \code{check-type-equal?} method triggers an error if the two types are
  4286. not equal. The \code{type-check-op} method looks up the operator in
  4287. the \code{operator-types} dictionary and then checks whether the
  4288. argument types are equal to the parameter types. The result is the
  4289. return type of the operator.
  4290. \begin{figure}[tbp]
  4291. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4292. (define type-check-Rvar-class
  4293. (class object%
  4294. (super-new)
  4295. (define/public (operator-types)
  4296. '((+ . ((Integer Integer) . Integer))
  4297. (- . ((Integer) . Integer))
  4298. (read . (() . Integer))))
  4299. (define/public (type-equal? t1 t2) (equal? t1 t2))
  4300. (define/public (check-type-equal? t1 t2 e)
  4301. (unless (type-equal? t1 t2)
  4302. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  4303. (define/public (type-check-op op arg-types e)
  4304. (match (dict-ref (operator-types) op)
  4305. [`(,param-types . ,return-type)
  4306. (for ([at arg-types] [pt param-types])
  4307. (check-type-equal? at pt e))
  4308. return-type]
  4309. [else (error 'type-check-op "unrecognized ~a" op)]))
  4310. (define/public (type-check-exp env)
  4311. (lambda (e)
  4312. (match e
  4313. [(Int n) (values (Int n) 'Integer)]
  4314. [(Var x) (values (Var x) (dict-ref env x))]
  4315. [(Let x e body)
  4316. (define-values (e^ Te) ((type-check-exp env) e))
  4317. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  4318. (values (Let x e^ b) Tb)]
  4319. [(Prim op es)
  4320. (define-values (new-es ts)
  4321. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  4322. (values (Prim op new-es) (type-check-op op ts e))]
  4323. [else (error 'type-check-exp "couldn't match" e)])))
  4324. (define/public (type-check-program e)
  4325. (match e
  4326. [(Program info body)
  4327. (define-values (body^ Tb) ((type-check-exp '()) body))
  4328. (check-type-equal? Tb 'Integer body)
  4329. (Program info body^)]
  4330. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  4331. ))
  4332. (define (type-check-Rvar p)
  4333. (send (new type-check-Rvar-class) type-check-program p))
  4334. \end{lstlisting}
  4335. \caption{Type checker for the \LangVar{} language.}
  4336. \label{fig:type-check-Rvar}
  4337. \end{figure}
  4338. \begin{figure}[tbp]
  4339. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4340. (define type-check-Rif-class
  4341. (class type-check-Rvar-class
  4342. (super-new)
  4343. (inherit check-type-equal?)
  4344. (define/override (operator-types)
  4345. (append '((- . ((Integer Integer) . Integer))
  4346. (and . ((Boolean Boolean) . Boolean))
  4347. (or . ((Boolean Boolean) . Boolean))
  4348. (< . ((Integer Integer) . Boolean))
  4349. (<= . ((Integer Integer) . Boolean))
  4350. (> . ((Integer Integer) . Boolean))
  4351. (>= . ((Integer Integer) . Boolean))
  4352. (not . ((Boolean) . Boolean))
  4353. )
  4354. (super operator-types)))
  4355. (define/override (type-check-exp env)
  4356. (lambda (e)
  4357. (match e
  4358. [(Prim 'eq? (list e1 e2))
  4359. (define-values (e1^ T1) ((type-check-exp env) e1))
  4360. (define-values (e2^ T2) ((type-check-exp env) e2))
  4361. (check-type-equal? T1 T2 e)
  4362. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  4363. [(Bool b) (values (Bool b) 'Boolean)]
  4364. [(If cnd thn els)
  4365. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  4366. (define-values (thn^ Tt) ((type-check-exp env) thn))
  4367. (define-values (els^ Te) ((type-check-exp env) els))
  4368. (check-type-equal? Tc 'Boolean e)
  4369. (check-type-equal? Tt Te e)
  4370. (values (If cnd^ thn^ els^) Te)]
  4371. [else ((super type-check-exp env) e)])))
  4372. ))
  4373. (define (type-check-Rif p)
  4374. (send (new type-check-Rif-class) type-check-program p))
  4375. \end{lstlisting}
  4376. \caption{Type checker for the \LangIf{} language.}
  4377. \label{fig:type-check-Rif}
  4378. \end{figure}
  4379. Next we discuss the type checker for \LangIf{} in
  4380. Figure~\ref{fig:type-check-Rif}. The operator \code{eq?} requires the
  4381. two arguments to have the same type. The type of a Boolean constant is
  4382. \code{Boolean}. The condition of an \code{if} must be of
  4383. \code{Boolean} type and the two branches must have the same type. The
  4384. \code{operator-types} function adds dictionary entries for the other
  4385. new operators.
  4386. \begin{exercise}\normalfont
  4387. Create 10 new test programs in \LangIf{}. Half of the programs should
  4388. have a type error. For those programs, create an empty file with the
  4389. same base name but with file extension \code{.tyerr}. For example, if
  4390. the test \code{cond\_test\_14.rkt} is expected to error, then create
  4391. an empty file named \code{cond\_test\_14.tyerr}. This indicates to
  4392. \code{interp-tests} and \code{compiler-tests} that a type error is
  4393. expected. The other half of the test programs should not have type
  4394. errors.
  4395. In the \code{run-tests.rkt} script, change the second argument of
  4396. \code{interp-tests} and \code{compiler-tests} to
  4397. \code{type-check-Rif}, which causes the type checker to run prior to
  4398. the compiler passes. Temporarily change the \code{passes} to an empty
  4399. list and run the script, thereby checking that the new test programs
  4400. either type check or not as intended.
  4401. \end{exercise}
  4402. \section{The \LangCIf{} Intermediate Language}
  4403. \label{sec:Cif}
  4404. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  4405. \LangCIf{} intermediate language. (The concrete syntax is in the
  4406. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  4407. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  4408. operators to the \Exp{} non-terminal and the literals \key{\#t} and
  4409. \key{\#f} to the \Arg{} non-terminal.
  4410. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  4411. statements to the \Tail{} non-terminal. The condition of an \code{if}
  4412. statement is a comparison operation and the branches are \code{goto}
  4413. statements, making it straightforward to compile \code{if} statements
  4414. to x86.
  4415. \begin{figure}[tp]
  4416. \fbox{
  4417. \begin{minipage}{0.96\textwidth}
  4418. \small
  4419. \[
  4420. \begin{array}{lcl}
  4421. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4422. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4423. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4424. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4425. &\mid& \UNIOP{\key{'not}}{\Atm}
  4426. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4427. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4428. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4429. \mid \GOTO{\itm{label}} \\
  4430. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4431. \LangCIf{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  4432. \end{array}
  4433. \]
  4434. \end{minipage}
  4435. }
  4436. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  4437. (Figure~\ref{fig:c0-syntax}).}
  4438. \label{fig:c1-syntax}
  4439. \end{figure}
  4440. \section{The \LangXIf{} Language}
  4441. \label{sec:x86-if}
  4442. \index{x86} To implement the new logical operations, the comparison
  4443. operations, and the \key{if} expression, we need to delve further into
  4444. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  4445. define the concrete and abstract syntax for the \LangXIf{} subset
  4446. of x86, which includes instructions for logical operations,
  4447. comparisons, and conditional jumps.
  4448. One challenge is that x86 does not provide an instruction that
  4449. directly implements logical negation (\code{not} in \LangIf{} and
  4450. \LangCIf{}). However, the \code{xorq} instruction can be used to
  4451. encode \code{not}. The \key{xorq} instruction takes two arguments,
  4452. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  4453. bit of its arguments, and writes the results into its second argument.
  4454. Recall the truth table for exclusive-or:
  4455. \begin{center}
  4456. \begin{tabular}{l|cc}
  4457. & 0 & 1 \\ \hline
  4458. 0 & 0 & 1 \\
  4459. 1 & 1 & 0
  4460. \end{tabular}
  4461. \end{center}
  4462. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  4463. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  4464. for the bit $1$, the result is the opposite of the second bit. Thus,
  4465. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  4466. the first argument:
  4467. \[
  4468. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  4469. \qquad\Rightarrow\qquad
  4470. \begin{array}{l}
  4471. \key{movq}~ \Arg\key{,} \Var\\
  4472. \key{xorq}~ \key{\$1,} \Var
  4473. \end{array}
  4474. \]
  4475. \begin{figure}[tp]
  4476. \fbox{
  4477. \begin{minipage}{0.96\textwidth}
  4478. \[
  4479. \begin{array}{lcl}
  4480. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4481. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4482. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  4483. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4484. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  4485. \key{subq} \; \Arg\key{,} \Arg \mid
  4486. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  4487. && \gray{ \key{callq} \; \itm{label} \mid
  4488. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  4489. && \gray{ \itm{label}\key{:}\; \Instr }
  4490. \mid \key{xorq}~\Arg\key{,}~\Arg
  4491. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  4492. && \key{set}cc~\Arg
  4493. \mid \key{movzbq}~\Arg\key{,}~\Arg
  4494. \mid \key{j}cc~\itm{label}
  4495. \\
  4496. \LangXIf{} &::= & \gray{ \key{.globl main} }\\
  4497. & & \gray{ \key{main:} \; \Instr\ldots }
  4498. \end{array}
  4499. \]
  4500. \end{minipage}
  4501. }
  4502. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  4503. \label{fig:x86-1-concrete}
  4504. \end{figure}
  4505. \begin{figure}[tp]
  4506. \fbox{
  4507. \begin{minipage}{0.98\textwidth}
  4508. \small
  4509. \[
  4510. \begin{array}{lcl}
  4511. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4512. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4513. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4514. \mid \BYTEREG{\itm{bytereg}} \\
  4515. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4516. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  4517. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  4518. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4519. \mid \UNIINSTR{\code{negq}}{\Arg} } \\
  4520. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4521. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4522. &\mid& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  4523. \mid \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  4524. &\mid& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  4525. \mid \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  4526. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4527. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  4528. \LangXIf{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  4529. \end{array}
  4530. \]
  4531. \end{minipage}
  4532. }
  4533. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  4534. \label{fig:x86-1}
  4535. \end{figure}
  4536. Next we consider the x86 instructions that are relevant for compiling
  4537. the comparison operations. The \key{cmpq} instruction compares its two
  4538. arguments to determine whether one argument is less than, equal, or
  4539. greater than the other argument. The \key{cmpq} instruction is unusual
  4540. regarding the order of its arguments and where the result is
  4541. placed. The argument order is backwards: if you want to test whether
  4542. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4543. \key{cmpq} is placed in the special EFLAGS register. This register
  4544. cannot be accessed directly but it can be queried by a number of
  4545. instructions, including the \key{set} instruction. The instruction
  4546. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  4547. depending on whether the comparison comes out according to the
  4548. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  4549. for less-or-equal, \key{g} for greater, \key{ge} for
  4550. greater-or-equal). The \key{set} instruction has an annoying quirk in
  4551. that its destination argument must be single byte register, such as
  4552. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  4553. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  4554. instruction can be used to move from a single byte register to a
  4555. normal 64-bit register. The abstract syntax for the \code{set}
  4556. instruction differs from the concrete syntax in that it separates the
  4557. instruction name from the condition code.
  4558. The x86 instruction for conditional jump is relevant to the
  4559. compilation of \key{if} expressions. The instruction
  4560. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  4561. the instruction after \itm{label} depending on whether the result in
  4562. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  4563. jump instruction falls through to the next instruction. Like the
  4564. abstract syntax for \code{set}, the abstract syntax for conditional
  4565. jump separates the instruction name from the condition code. For
  4566. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4567. the conditional jump instruction relies on the EFLAGS register, it is
  4568. common for it to be immediately preceded by a \key{cmpq} instruction
  4569. to set the EFLAGS register.
  4570. \section{Shrink the \LangIf{} Language}
  4571. \label{sec:shrink-Rif}
  4572. The \LangIf{} language includes several operators that are easily
  4573. expressible with other operators. For example, subtraction is
  4574. expressible using addition and negation.
  4575. \[
  4576. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  4577. \]
  4578. Several of the comparison operations are expressible using less-than
  4579. and logical negation.
  4580. \[
  4581. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  4582. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  4583. \]
  4584. The \key{let} is needed in the above translation to ensure that
  4585. expression $e_1$ is evaluated before $e_2$.
  4586. By performing these translations in the front-end of the compiler, the
  4587. later passes of the compiler do not need to deal with these operators,
  4588. making the passes shorter.
  4589. %% On the other hand, sometimes
  4590. %% these translations make it more difficult to generate the most
  4591. %% efficient code with respect to the number of instructions. However,
  4592. %% these differences typically do not affect the number of accesses to
  4593. %% memory, which is the primary factor that determines execution time on
  4594. %% modern computer architectures.
  4595. \begin{exercise}\normalfont
  4596. Implement the pass \code{shrink} to remove subtraction, \key{and},
  4597. \key{or}, \key{<=}, \key{>}, and \key{>=} from the language by
  4598. translating them to other constructs in \LangIf{}.
  4599. %
  4600. Create six test programs that involve these operators.
  4601. %
  4602. In the \code{run-tests.rkt} script, add the following entry for
  4603. \code{shrink} to the list of passes (it should be the only pass at
  4604. this point).
  4605. \begin{lstlisting}
  4606. (list "shrink" shrink interp-Rif type-check-Rif)
  4607. \end{lstlisting}
  4608. This instructs \code{interp-tests} to run the intepreter
  4609. \code{interp-Rif} and the type checker \code{type-check-Rif} on the
  4610. output of \code{shrink}.
  4611. %
  4612. Run the script to test your compiler on all the test programs.
  4613. \end{exercise}
  4614. \section{Uniquify Variables}
  4615. \label{sec:uniquify-Rif}
  4616. Add cases to \code{uniquify-exp} to handle Boolean constants and
  4617. \code{if} expressions.
  4618. \begin{exercise}\normalfont
  4619. Update the \code{uniquify-exp} for \LangIf{} and add the following
  4620. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  4621. \begin{lstlisting}
  4622. (list "uniquify" uniquify interp-Rif type-check-Rif)
  4623. \end{lstlisting}
  4624. Run the script to test your compiler.
  4625. \end{exercise}
  4626. \section{Remove Complex Operands}
  4627. \label{sec:remove-complex-opera-Rif}
  4628. The output language for this pass is \LangIfANF{}
  4629. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  4630. \LangIf{}. The \code{Bool} form is an atomic expressions but
  4631. \code{If} is not. All three sub-expressions of an \code{If} are
  4632. allowed to be complex expressions but the operands of \code{not} and
  4633. the comparisons must be atoms.
  4634. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4635. \code{rco-atom} functions according to whether the output needs to be
  4636. \Exp{} or \Atm{} as specified in the grammar for \LangIfANF{}.
  4637. Regarding \code{If}, it is particularly important to \textbf{not}
  4638. replace its condition with a temporary variable because that would
  4639. interfere with the generation of high-quality output in the
  4640. \code{explicate-control} pass.
  4641. \begin{figure}[tp]
  4642. \centering
  4643. \fbox{
  4644. \begin{minipage}{0.96\textwidth}
  4645. \[
  4646. \begin{array}{rcl}
  4647. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4648. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4649. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4650. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4651. &\mid& \UNIOP{\key{not}}{\Atm} \\
  4652. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4653. R^{\dagger}_2 &::=& \PROGRAM{\code{()}}{\Exp}
  4654. \end{array}
  4655. \]
  4656. \end{minipage}
  4657. }
  4658. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  4659. \label{fig:Rif-anf-syntax}
  4660. \end{figure}
  4661. \begin{exercise}\normalfont
  4662. %
  4663. Add cases for Boolean constants and \code{if} to the \code{rco-atom}
  4664. and \code{rco-exp} functions in \code{compiler.rkt}.
  4665. %
  4666. Create three new \LangInt{} programs that exercise the interesting
  4667. code in this pass.
  4668. %
  4669. In the \code{run-tests.rkt} script, add the following entry to the
  4670. list of \code{passes} and then run the script to test your compiler.
  4671. \begin{lstlisting}
  4672. (list "remove-complex" remove-complex-opera* interp-Rif type-check-Rif)
  4673. \end{lstlisting}
  4674. \end{exercise}
  4675. \section{Explicate Control}
  4676. \label{sec:explicate-control-Rif}
  4677. Recall that the purpose of \code{explicate-control} is to make the
  4678. order of evaluation explicit in the syntax of the program. With the
  4679. addition of \key{if} this get more interesting.
  4680. As a motivating example, consider the following program that has an
  4681. \key{if} expression nested in the predicate of another \key{if}.
  4682. % cond_test_41.rkt
  4683. \begin{center}
  4684. \begin{minipage}{0.96\textwidth}
  4685. \begin{lstlisting}
  4686. (let ([x (read)])
  4687. (let ([y (read)])
  4688. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4689. (+ y 2)
  4690. (+ y 10))))
  4691. \end{lstlisting}
  4692. \end{minipage}
  4693. \end{center}
  4694. %
  4695. The naive way to compile \key{if} and the comparison would be to
  4696. handle each of them in isolation, regardless of their context. Each
  4697. comparison would be translated into a \key{cmpq} instruction followed
  4698. by a couple instructions to move the result from the EFLAGS register
  4699. into a general purpose register or stack location. Each \key{if} would
  4700. be translated into a \key{cmpq} instruction followed by a conditional
  4701. jump. The generated code for the inner \key{if} in the above example
  4702. would be as follows.
  4703. \begin{center}
  4704. \begin{minipage}{0.96\textwidth}
  4705. \begin{lstlisting}
  4706. ...
  4707. cmpq $1, x ;; (< x 1)
  4708. setl %al
  4709. movzbq %al, tmp
  4710. cmpq $1, tmp ;; (if ...)
  4711. je then_branch_1
  4712. jmp else_branch_1
  4713. ...
  4714. \end{lstlisting}
  4715. \end{minipage}
  4716. \end{center}
  4717. However, if we take context into account we can do better and reduce
  4718. the use of \key{cmpq} instructions for accessing the EFLAG register.
  4719. Our goal will be compile \key{if} expressions so that the relevant
  4720. comparison instruction appears directly before the conditional jump.
  4721. For example, we want to generate the following code for the inner
  4722. \code{if}.
  4723. \begin{center}
  4724. \begin{minipage}{0.96\textwidth}
  4725. \begin{lstlisting}
  4726. ...
  4727. cmpq $1, x
  4728. je then_branch_1
  4729. jmp else_branch_1
  4730. ...
  4731. \end{lstlisting}
  4732. \end{minipage}
  4733. \end{center}
  4734. One way to achieve this is to reorganize the code at the level of
  4735. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  4736. the following code.
  4737. \begin{center}
  4738. \begin{minipage}{0.96\textwidth}
  4739. \begin{lstlisting}
  4740. (let ([x (read)])
  4741. (let ([y (read)])
  4742. (if (< x 1)
  4743. (if (eq? x 0)
  4744. (+ y 2)
  4745. (+ y 10))
  4746. (if (eq? x 2)
  4747. (+ y 2)
  4748. (+ y 10)))))
  4749. \end{lstlisting}
  4750. \end{minipage}
  4751. \end{center}
  4752. Unfortunately, this approach duplicates the two branches from the
  4753. outer \code{if} and a compiler must never duplicate code!
  4754. We need a way to perform the above transformation but without
  4755. duplicating code. That is, we need a way for different parts of a
  4756. program to refer to the same piece of code. At the level of x86
  4757. assembly this is straightforward because we can label the code for
  4758. each branch and insert jumps in all the places that need to execute
  4759. the branch. In our intermediate language, we need to move away from
  4760. abstract syntax \emph{trees} and instead use \emph{graphs}. In
  4761. particular, we use a standard program representation called a
  4762. \emph{control flow graph} (CFG), due to Frances Elizabeth
  4763. \citet{Allen:1970uq}. \index{control-flow graph} Each vertex is a
  4764. labeled sequence of code, called a \emph{basic block}, and each edge
  4765. represents a jump to another block. The \key{CProgram} construct of
  4766. \LangCVar{} and \LangCIf{} contains a control flow graph represented
  4767. as an alist mapping labels to basic blocks. Each basic block is
  4768. represented by the $\Tail$ non-terminal.
  4769. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4770. \code{remove-complex-opera*} pass and then the
  4771. \code{explicate-control} pass on the example program. We walk through
  4772. the output program and then discuss the algorithm.
  4773. %
  4774. Following the order of evaluation in the output of
  4775. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4776. and then the comparison \lstinline{(< x 1)} in the predicate of the
  4777. inner \key{if}. In the output of \code{explicate-control}, in the
  4778. block labeled \code{start}, is two assignment statements followed by a
  4779. \code{if} statement that branches to \code{block40} or
  4780. \code{block41}. The blocks associated with those labels contain the
  4781. translations of the code \lstinline{(eq? x 0)} and \lstinline{(eq? x 2)},
  4782. respectively. In particular, we start \code{block40} with the
  4783. comparison \lstinline{(eq? x 0)} and then branch to \code{block38} or
  4784. \code{block39}, the two branches of the outer \key{if}, i.e.,
  4785. \lstinline{(+ y 2)} and \lstinline{(+ y 10)}. The story for
  4786. \code{block41} is similar.
  4787. \begin{figure}[tbp]
  4788. \begin{tabular}{lll}
  4789. \begin{minipage}{0.4\textwidth}
  4790. % cond_test_41.rkt
  4791. \begin{lstlisting}
  4792. (let ([x (read)])
  4793. (let ([y (read)])
  4794. (if (if (< x 1)
  4795. (eq? x 0)
  4796. (eq? x 2))
  4797. (+ y 2)
  4798. (+ y 10))))
  4799. \end{lstlisting}
  4800. \hspace{40pt}$\Downarrow$
  4801. \begin{lstlisting}
  4802. (let ([x (read)])
  4803. (let ([y (read)])
  4804. (if (if (< x 1)
  4805. (eq? x 0)
  4806. (eq? x 2))
  4807. (+ y 2)
  4808. (+ y 10))))
  4809. \end{lstlisting}
  4810. \end{minipage}
  4811. &
  4812. $\Rightarrow$
  4813. &
  4814. \begin{minipage}{0.55\textwidth}
  4815. \begin{lstlisting}
  4816. start:
  4817. x = (read);
  4818. y = (read);
  4819. if (< x 1) goto block40;
  4820. else goto block41;
  4821. block40:
  4822. if (eq? x 0) goto block38;
  4823. else goto block39;
  4824. block41:
  4825. if (eq? x 2) goto block38;
  4826. else goto block39;
  4827. block38:
  4828. return (+ y 2);
  4829. block39:
  4830. return (+ y 10);
  4831. \end{lstlisting}
  4832. \end{minipage}
  4833. \end{tabular}
  4834. \caption{Translation from \LangIf{} to \LangCIf{}
  4835. via the \code{explicate-control}.}
  4836. \label{fig:explicate-control-s1-38}
  4837. \end{figure}
  4838. %% The nice thing about the output of \code{explicate-control} is that
  4839. %% there are no unnecessary comparisons and every comparison is part of a
  4840. %% conditional jump.
  4841. %% The down-side of this output is that it includes
  4842. %% trivial blocks, such as the blocks labeled \code{block92} through
  4843. %% \code{block95}, that only jump to another block. We discuss a solution
  4844. %% to this problem in Section~\ref{sec:opt-jumps}.
  4845. Recall that in Section~\ref{sec:explicate-control-Rvar} we implement
  4846. \code{explicate-control} for \LangVar{} using two mutually recursive
  4847. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4848. former function translates expressions in tail position whereas the
  4849. later function translates expressions on the right-hand-side of a
  4850. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  4851. have a new kind of position to deal with: the predicate position of
  4852. the \key{if}. We need another function, \code{explicate-pred}, that
  4853. takes an \LangIf{} expression and two blocks for the then-branch and
  4854. else-branch. The output of \code{explicate-pred} is a block.
  4855. %
  4856. In the following paragraphs we discuss specific cases in the
  4857. \code{explicate-pred} function as well as additions to the
  4858. \code{explicate-tail} and \code{explicate-assign} functions.
  4859. \begin{figure}[tbp]
  4860. \begin{lstlisting}
  4861. (define (explicate-pred cnd thn els)
  4862. (match cnd
  4863. [(Var x) ___]
  4864. [(Let x rhs body) ___]
  4865. [(Prim 'not (list e)) ___]
  4866. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  4867. (IfStmt (Prim op arg*) (force (block->goto thn))
  4868. (force (block->goto els)))]
  4869. [(Bool b) (if b thn els)]
  4870. [(If cnd^ thn^ els^) ___]
  4871. [else (error "explicate-pred unhandled case" cnd)]))
  4872. \end{lstlisting}
  4873. \caption{Skeleton for the \key{explicate-pred} auxiliary function.}
  4874. \label{fig:explicate-pred}
  4875. \end{figure}
  4876. The skeleton for the \code{explicate-pred} function is given in
  4877. Figure~\ref{fig:explicate-pred}. It has a case for every expression
  4878. that can have type \code{Boolean}. We detail a few cases here and
  4879. leave the rest for the reader. The input to this function is an
  4880. expression and two blocks, \code{thn} and \code{els}, for the two
  4881. branches of the enclosing \key{if}.
  4882. %
  4883. Consider the case for Boolean constants in
  4884. Figure~\ref{fig:explicate-pred}. We perform a kind of partial
  4885. evaluation\index{partial evaluation} and output either the \code{thn}
  4886. or \code{els} branch depending on whether the constant is true or
  4887. false. This case demonstrates that we sometimes discard the \code{thn}
  4888. or \code{els} blocks that are input to \code{explicate-pred}.
  4889. The case for \key{if} in \code{explicate-pred} is particularly
  4890. illuminating because it deals with the challenges we discussed above
  4891. regarding nested \key{if} expressions
  4892. (Figure~\ref{fig:explicate-control-s1-38}). The \lstinline{thn^} and
  4893. \lstinline{els^} branches of the \key{if} inherit their context from
  4894. the current one, that is, predicate context. So you should recursively
  4895. apply \code{explicate-pred} to the \lstinline{thn^} and
  4896. \lstinline{els^} branches. For both of those recursive calls, pass
  4897. \code{thn} and \code{els} as the extra parameters. Thus, \code{thn}
  4898. and \code{els} may get used twice, once inside each recursive call. As
  4899. discussed above, to avoid duplicating code, we need to add them to the
  4900. control-flow graph so that we can instead refer to them by name and
  4901. execute them with a \key{goto}. However, as we saw in the cases above
  4902. for Boolean constants, the blocks \code{thn} and \code{els} may not
  4903. get used at all and we don't want to prematurely add them to the
  4904. control-flow graph if they end up being discarded.
  4905. The solution to this conundrum is to use \emph{lazy
  4906. evaluation}\index{lazy evaluation}\citep{Friedman:1976aa} to delay
  4907. adding the blocks to the control-flow graph until the points where we
  4908. know they will be used. Racket provides support for lazy evaluation
  4909. with the
  4910. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  4911. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  4912. \index{delay} creates a \emph{promise}\index{promise} in which the
  4913. evaluation of the expressions is postponed. When \key{(force}
  4914. $p$\key{)}\index{force} is applied to a promise $p$ for the first
  4915. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  4916. $e_n$ is cached in the promise and returned. If \code{force} is
  4917. applied again to the same promise, then the cached result is returned.
  4918. If \code{force} is applied to an argument that is not a promise,
  4919. \code{force} simply returns the argument.
  4920. We use lazy evaluation for the input and output blocks of the
  4921. functions \code{explicate-pred} and \code{explicate-assign} and for
  4922. the output block of \code{explicate-tail}. So instead of taking and
  4923. returning blocks, they take and return promises. Furthermore, when we
  4924. come to a situation in which we a block might be used more than once,
  4925. as in the case for \code{if} in \code{explicate-pred}, we transform
  4926. the promise into a new promise that will add the block to the
  4927. control-flow graph and return a \code{goto}. The following auxiliary
  4928. function named \code{block->goto} accomplishes this task. It begins
  4929. with \code{delay} to create a promise. When forced, this promise will
  4930. force the original promise. If that returns a \code{goto} (because the
  4931. block was already added to the control-flow graph), then we return the
  4932. \code{goto}. Otherwise we add the block to the control-flow graph with
  4933. another auxiliary function named \code{add-node}. That function
  4934. returns the label for the new block, which we use to create a
  4935. \code{goto}.
  4936. \begin{lstlisting}
  4937. (define (block->goto block)
  4938. (delay
  4939. (define b (force block))
  4940. (match b
  4941. [(Goto label) (Goto label)]
  4942. [else (Goto (add-node b))])))
  4943. \end{lstlisting}
  4944. Returning to the discussion of \code{explicate-pred}
  4945. (Figure~\ref{fig:explicate-pred}), consider the case for comparison
  4946. operators. This is one of the base cases of the recursive function so
  4947. we translate the comparison to an \code{if} statement. We apply
  4948. \code{block->goto} to \code{thn} and \code{els} to obtain two promises
  4949. that will add then to the control-flow graph, which we can immediately
  4950. \code{force} to obtain the two goto's that form the branches of the
  4951. \code{if} statement.
  4952. %% Getting back to the case for \code{if} in \code{explicate-pred}, we
  4953. %% make the recursive calls to \code{explicate-pred} on the ``then'' and
  4954. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  4955. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  4956. %% results from the two recursive calls. We complete the case for
  4957. %% \code{if} by recursively apply \code{explicate-pred} to the condition
  4958. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  4959. %% the result $B_5$.
  4960. %% \[
  4961. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4962. %% \quad\Rightarrow\quad
  4963. %% B_5
  4964. %% \]
  4965. The \code{explicate-tail} and \code{explicate-assign} functions need
  4966. additional cases for Boolean constants and \key{if}.
  4967. %
  4968. In the cases for \code{if}, the two branches inherit the current
  4969. context, so in \code{explicate-tail} they are in tail position and in
  4970. \code{explicate-assign} they are in assignment position. The
  4971. \code{cont} parameter of \code{explicate-assign} is used in both
  4972. recursive calls, so make sure to use \code{block->goto} on it.
  4973. %% In the case for \code{if} in \code{explicate-tail}, the two branches
  4974. %% inherit the current context, so they are in tail position. Thus, the
  4975. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  4976. %% \code{explicate-tail}.
  4977. %% %
  4978. %% We need to pass $B_0$ as the accumulator argument for both of these
  4979. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  4980. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  4981. %% to the control-flow graph and obtain a promised goto $G_0$.
  4982. %% %
  4983. %% Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  4984. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  4985. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  4986. %% \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  4987. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  4988. %% \[
  4989. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4990. %% \]
  4991. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4992. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  4993. %% should not be confused with the labels for the blocks that appear in
  4994. %% the generated code. We initially construct unlabeled blocks; we only
  4995. %% attach labels to blocks when we add them to the control-flow graph, as
  4996. %% we see in the next case.
  4997. %% Next consider the case for \key{if} in the \code{explicate-assign}
  4998. %% function. The context of the \key{if} is an assignment to some
  4999. %% variable $x$ and then the control continues to some promised block
  5000. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  5001. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  5002. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  5003. %% branches of the \key{if} inherit the current context, so they are in
  5004. %% assignment positions. Let $B_2$ be the result of applying
  5005. %% \code{explicate-assign} to the ``then'' branch, variable $x$, and
  5006. %% $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  5007. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  5008. %% the result of applying \code{explicate-pred} to the predicate
  5009. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  5010. %% translates to the promise $B_4$.
  5011. %% \[
  5012. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  5013. %% \]
  5014. %% This completes the description of \code{explicate-control} for \LangIf{}.
  5015. The way in which the \code{shrink} pass transforms logical operations
  5016. such as \code{and} and \code{or} can impact the quality of code
  5017. generated by \code{explicate-control}. For example, consider the
  5018. following program.
  5019. % cond_test_21.rkt
  5020. \begin{lstlisting}
  5021. (if (and (eq? (read) 0) (eq? (read) 1))
  5022. 0
  5023. 42)
  5024. \end{lstlisting}
  5025. The \code{and} operation should transform into something that the
  5026. \code{explicate-pred} function can still analyze and descend through to
  5027. reach the underlying \code{eq?} conditions. Ideally, your
  5028. \code{explicate-control} pass should generate code similar to the
  5029. following for the above program.
  5030. \begin{center}
  5031. \begin{lstlisting}
  5032. start:
  5033. tmp1 = (read);
  5034. if (eq? tmp1 0) goto block40;
  5035. else goto block39;
  5036. block40:
  5037. tmp2 = (read);
  5038. if (eq? tmp2 1) goto block38;
  5039. else goto block39;
  5040. block38:
  5041. return 0;
  5042. block39:
  5043. return 42;
  5044. \end{lstlisting}
  5045. \end{center}
  5046. \begin{exercise}\normalfont
  5047. Implement the pass \code{explicate-control} by adding the cases for
  5048. Boolean constants and \key{if} to the \code{explicate-tail} and
  5049. \code{explicate-assign}. Implement the auxiliary function
  5050. \code{explicate-pred} for predicate contexts.
  5051. %
  5052. Create test cases that exercise all of the new cases in the code for
  5053. this pass.
  5054. %
  5055. Add the following entry to the list of \code{passes} in
  5056. \code{run-tests.rkt} and then run this script to test your compiler.
  5057. \begin{lstlisting}
  5058. (list "explicate-control" explicate-control interp-Cif type-check-Cif)
  5059. \end{lstlisting}
  5060. \end{exercise}
  5061. \section{Select Instructions}
  5062. \label{sec:select-Rif}
  5063. \index{instruction selection}
  5064. The \code{select-instructions} pass translate \LangCIf{} to
  5065. \LangXIfVar{}. Recall that we implement this pass using three
  5066. auxiliary functions, one for each of the non-terminals $\Atm$,
  5067. $\Stmt$, and $\Tail$.
  5068. For $\Atm$, we have new cases for the Booleans. We take the usual
  5069. approach of encoding them as integers, with true as 1 and false as 0.
  5070. \[
  5071. \key{\#t} \Rightarrow \key{1}
  5072. \qquad
  5073. \key{\#f} \Rightarrow \key{0}
  5074. \]
  5075. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  5076. be implemented in terms of \code{xorq} as we discussed at the
  5077. beginning of this section. Given an assignment
  5078. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  5079. if the left-hand side $\itm{var}$ is
  5080. the same as $\Atm$, then just the \code{xorq} suffices.
  5081. \[
  5082. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  5083. \quad\Rightarrow\quad
  5084. \key{xorq}~\key{\$}1\key{,}~\Var
  5085. \]
  5086. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  5087. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  5088. x86. Then we have
  5089. \[
  5090. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  5091. \quad\Rightarrow\quad
  5092. \begin{array}{l}
  5093. \key{movq}~\Arg\key{,}~\Var\\
  5094. \key{xorq}~\key{\$}1\key{,}~\Var
  5095. \end{array}
  5096. \]
  5097. Next consider the cases for \code{eq?} and less-than comparison.
  5098. Translating these operations to x86 is slightly involved due to the
  5099. unusual nature of the \key{cmpq} instruction discussed above. We
  5100. recommend translating an assignment from \code{eq?} into the following
  5101. sequence of three instructions. \\
  5102. \begin{tabular}{lll}
  5103. \begin{minipage}{0.4\textwidth}
  5104. \begin{lstlisting}
  5105. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  5106. \end{lstlisting}
  5107. \end{minipage}
  5108. &
  5109. $\Rightarrow$
  5110. &
  5111. \begin{minipage}{0.4\textwidth}
  5112. \begin{lstlisting}
  5113. cmpq |$\Arg_2$|, |$\Arg_1$|
  5114. sete %al
  5115. movzbq %al, |$\Var$|
  5116. \end{lstlisting}
  5117. \end{minipage}
  5118. \end{tabular} \\
  5119. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  5120. and \key{if} statements. Both are straightforward to translate to
  5121. x86. A \key{goto} becomes a jump instruction.
  5122. \[
  5123. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  5124. \]
  5125. An \key{if} statement becomes a compare instruction followed by a
  5126. conditional jump (for the ``then'' branch) and the fall-through is to
  5127. a regular jump (for the ``else'' branch).\\
  5128. \begin{tabular}{lll}
  5129. \begin{minipage}{0.4\textwidth}
  5130. \begin{lstlisting}
  5131. if (eq? |$\Atm_1$| |$\Atm_2$|) goto |$\ell_1$|;
  5132. else goto |$\ell_2$|;
  5133. \end{lstlisting}
  5134. \end{minipage}
  5135. &
  5136. $\Rightarrow$
  5137. &
  5138. \begin{minipage}{0.4\textwidth}
  5139. \begin{lstlisting}
  5140. cmpq |$\Arg_2$|, |$\Arg_1$|
  5141. je |$\ell_1$|
  5142. jmp |$\ell_2$|
  5143. \end{lstlisting}
  5144. \end{minipage}
  5145. \end{tabular} \\
  5146. \begin{exercise}\normalfont
  5147. Expand your \code{select-instructions} pass to handle the new features
  5148. of the \LangIf{} language.
  5149. %
  5150. Add the following entry to the list of \code{passes} in
  5151. \code{run-tests.rkt}
  5152. \begin{lstlisting}
  5153. (list "select-instructions" select-instructions interp-pseudo-x86-1)
  5154. \end{lstlisting}
  5155. %
  5156. Run the script to test your compiler on all the test programs.
  5157. \end{exercise}
  5158. \section{Register Allocation}
  5159. \label{sec:register-allocation-Rif}
  5160. \index{register allocation}
  5161. The changes required for \LangIf{} affect liveness analysis, building the
  5162. interference graph, and assigning homes, but the graph coloring
  5163. algorithm itself does not change.
  5164. \subsection{Liveness Analysis}
  5165. \label{sec:liveness-analysis-Rif}
  5166. \index{liveness analysis}
  5167. Recall that for \LangVar{} we implemented liveness analysis for a single
  5168. basic block (Section~\ref{sec:liveness-analysis-Rvar}). With the
  5169. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  5170. produces many basic blocks arranged in a control-flow graph. We
  5171. recommend that you create a new auxiliary function named
  5172. \code{uncover-live-CFG} that applies liveness analysis to a
  5173. control-flow graph.
  5174. The first question we is: what order should we process the basic
  5175. blocks in the control-flow graph? Recall that to perform liveness
  5176. analysis on a basic block we need to know its live-after set. If a
  5177. basic block has no successors (i.e. no out-edges in the control flow
  5178. graph), then it has an empty live-after set and we can immediately
  5179. apply liveness analysis to it. If a basic block has some successors,
  5180. then we need to complete liveness analysis on those blocks first. In
  5181. graph theory, a sequence of nodes is in \emph{topological
  5182. order}\index{topological order} if each vertex comes before its
  5183. successors. We need the opposite, so we can transpose the graph
  5184. before computing a topological order.
  5185. %
  5186. Use the \code{tsort} and \code{transpose} functions of the Racket
  5187. \code{graph} package to accomplish this.
  5188. %
  5189. As an aside, a topological ordering is only guaranteed to exist if the
  5190. graph does not contain any cycles. That is indeed the case for the
  5191. control-flow graphs that we generate from \LangIf{} programs.
  5192. However, in Chapter~\ref{ch:Rwhile} we add loops to \LangLoop{} and
  5193. learn how to handle cycles in the control-flow graph.
  5194. You'll need to construct a directed graph to represent the
  5195. control-flow graph. Do not use the \code{directed-graph} of the
  5196. \code{graph} package because that only allows at most one edge between
  5197. each pair of vertices, but a control-flow graph may have multiple
  5198. edges between a pair of vertices. The \code{multigraph.rkt} file in
  5199. the support code implements a graph representation that allows
  5200. multiple edges between a pair of vertices.
  5201. The next question is how to analyze jump instructions. Recall that in
  5202. Section~\ref{sec:liveness-analysis-Rvar} we maintain an alist named
  5203. \code{label->live} that maps each label to the set of live locations
  5204. at the beginning of its block. We use \code{label->live} to determine
  5205. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  5206. that we have many basic blocks, \code{label->live} needs to be updated
  5207. as we process the blocks. In particular, after performing liveness
  5208. analysis on a block, we take the live-before set of its first
  5209. instruction and associate that with the block's label in the
  5210. \code{label->live}.
  5211. In \LangXIfVar{} we also have the conditional jump
  5212. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  5213. this instruction is particularly interesting because during
  5214. compilation we do not know which way a conditional jump will go. So
  5215. we do not know whether to use the live-before set for the following
  5216. instruction or the live-before set for the $\itm{label}$. However,
  5217. there is no harm to the correctness of the compiler if we classify
  5218. more locations as live than the ones that are truly live during a
  5219. particular execution of the instruction. Thus, we can take the union
  5220. of the live-before sets from the following instruction and from the
  5221. mapping for $\itm{label}$ in \code{label->live}.
  5222. The auxiliary functions for computing the variables in an
  5223. instruction's argument and for computing the variables read-from ($R$)
  5224. or written-to ($W$) by an instruction need to be updated to handle the
  5225. new kinds of arguments and instructions in \LangXIfVar{}.
  5226. \begin{exercise}\normalfont
  5227. Update the \code{uncover-live} pass and implement the
  5228. \code{uncover-live-CFG} auxiliary function to apply liveness analysis
  5229. to the control-flow graph. Add the following entry to the list of
  5230. \code{passes} in the \code{run-tests.rkt} script.
  5231. \begin{lstlisting}
  5232. (list "uncover-live" uncover-live interp-pseudo-x86-1)
  5233. \end{lstlisting}
  5234. \end{exercise}
  5235. \subsection{Build the Interference Graph}
  5236. \label{sec:build-interference-Rif}
  5237. Many of the new instructions in \LangXIfVar{} can be handled in the
  5238. same way as the instructions in \LangXVar{}. Thus, if your code was
  5239. already quite general, it will not need to be changed to handle the
  5240. new instructions. If you code is not general enough, we recommend that
  5241. you change your code to be more general. For example, you can factor
  5242. out the computing of the the read and write sets for each kind of
  5243. instruction into two auxiliary functions.
  5244. Note that the \key{movzbq} instruction requires some special care,
  5245. similar to the \key{movq} instruction. See rule number 1 in
  5246. Section~\ref{sec:build-interference}.
  5247. \begin{exercise}\normalfont
  5248. Update the \code{build-interference} pass for \LangXIfVar{} and add the
  5249. following entries to the list of \code{passes} in the
  5250. \code{run-tests.rkt} script.
  5251. \begin{lstlisting}
  5252. (list "build-interference" build-interference interp-pseudo-x86-1)
  5253. (list "allocate-registers" allocate-registers interp-x86-1)
  5254. \end{lstlisting}
  5255. Run the script to test your compiler on all the \LangIf{} test
  5256. programs.
  5257. \end{exercise}
  5258. \section{Patch Instructions}
  5259. The second argument of the \key{cmpq} instruction must not be an
  5260. immediate value (such as an integer). So if you are comparing two
  5261. immediates, we recommend inserting a \key{movq} instruction to put the
  5262. second argument in \key{rax}. Also, recall that instructions may have
  5263. at most one memory reference.
  5264. %
  5265. The second argument of the \key{movzbq} must be a register.
  5266. %
  5267. There are no special restrictions on the jump instructions.
  5268. \begin{exercise}\normalfont
  5269. %
  5270. Update \code{patch-instructions} pass for \LangXIfVar{}.
  5271. %
  5272. Add the following entry to the list of \code{passes} in
  5273. \code{run-tests.rkt} and then run this script to test your compiler.
  5274. \begin{lstlisting}
  5275. (list "patch-instructions" patch-instructions interp-x86-1)
  5276. \end{lstlisting}
  5277. \end{exercise}
  5278. \begin{figure}[tbp]
  5279. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5280. \node (Rif) at (0,2) {\large \LangIf{}};
  5281. \node (Rif-2) at (3,2) {\large \LangIf{}};
  5282. \node (Rif-3) at (6,2) {\large \LangIf{}};
  5283. \node (Rif-4) at (9,2) {\large \LangIf{}};
  5284. \node (Rif-5) at (12,2) {\large \LangIf{}};
  5285. \node (C1-1) at (3,0) {\large \LangCIf{}};
  5286. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  5287. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  5288. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  5289. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  5290. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  5291. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  5292. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  5293. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  5294. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  5295. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  5296. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  5297. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  5298. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5299. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  5300. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5301. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5302. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  5303. \end{tikzpicture}
  5304. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  5305. \label{fig:Rif-passes}
  5306. \end{figure}
  5307. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  5308. compilation of \LangIf{}.
  5309. \section{An Example Translation}
  5310. Figure~\ref{fig:if-example-x86} shows a simple example program in
  5311. \LangIf{} translated to x86, showing the results of
  5312. \code{explicate-control}, \code{select-instructions}, and the final
  5313. x86 assembly code.
  5314. \begin{figure}[tbp]
  5315. \begin{tabular}{lll}
  5316. \begin{minipage}{0.4\textwidth}
  5317. % cond_test_20.rkt
  5318. \begin{lstlisting}
  5319. (if (eq? (read) 1) 42 0)
  5320. \end{lstlisting}
  5321. $\Downarrow$
  5322. \begin{lstlisting}
  5323. start:
  5324. tmp7951 = (read);
  5325. if (eq? tmp7951 1)
  5326. goto block7952;
  5327. else
  5328. goto block7953;
  5329. block7952:
  5330. return 42;
  5331. block7953:
  5332. return 0;
  5333. \end{lstlisting}
  5334. $\Downarrow$
  5335. \begin{lstlisting}
  5336. start:
  5337. callq read_int
  5338. movq %rax, tmp7951
  5339. cmpq $1, tmp7951
  5340. je block7952
  5341. jmp block7953
  5342. block7953:
  5343. movq $0, %rax
  5344. jmp conclusion
  5345. block7952:
  5346. movq $42, %rax
  5347. jmp conclusion
  5348. \end{lstlisting}
  5349. \end{minipage}
  5350. &
  5351. $\Rightarrow\qquad$
  5352. \begin{minipage}{0.4\textwidth}
  5353. \begin{lstlisting}
  5354. start:
  5355. callq read_int
  5356. movq %rax, %rcx
  5357. cmpq $1, %rcx
  5358. je block7952
  5359. jmp block7953
  5360. block7953:
  5361. movq $0, %rax
  5362. jmp conclusion
  5363. block7952:
  5364. movq $42, %rax
  5365. jmp conclusion
  5366. .globl main
  5367. main:
  5368. pushq %rbp
  5369. movq %rsp, %rbp
  5370. pushq %r13
  5371. pushq %r12
  5372. pushq %rbx
  5373. pushq %r14
  5374. subq $0, %rsp
  5375. jmp start
  5376. conclusion:
  5377. addq $0, %rsp
  5378. popq %r14
  5379. popq %rbx
  5380. popq %r12
  5381. popq %r13
  5382. popq %rbp
  5383. retq
  5384. \end{lstlisting}
  5385. \end{minipage}
  5386. \end{tabular}
  5387. \caption{Example compilation of an \key{if} expression to x86.}
  5388. \label{fig:if-example-x86}
  5389. \end{figure}
  5390. \section{Challenge: Remove Jumps}
  5391. \label{sec:opt-jumps}
  5392. %% Recall that in the example output of \code{explicate-control} in
  5393. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  5394. %% \code{block60} are trivial blocks, they do nothing but jump to another
  5395. %% block. The first goal of this challenge assignment is to remove those
  5396. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  5397. %% \code{explicate-control} on the left and shows the result of bypassing
  5398. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  5399. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  5400. %% \code{block55}. The optimized code on the right of
  5401. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  5402. %% \code{then} branch jumping directly to \code{block55}. The story is
  5403. %% similar for the \code{else} branch, as well as for the two branches in
  5404. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  5405. %% have been optimized in this way, there are no longer any jumps to
  5406. %% blocks \code{block57} through \code{block60}, so they can be removed.
  5407. %% \begin{figure}[tbp]
  5408. %% \begin{tabular}{lll}
  5409. %% \begin{minipage}{0.4\textwidth}
  5410. %% \begin{lstlisting}
  5411. %% block62:
  5412. %% tmp54 = (read);
  5413. %% if (eq? tmp54 2) then
  5414. %% goto block59;
  5415. %% else
  5416. %% goto block60;
  5417. %% block61:
  5418. %% tmp53 = (read);
  5419. %% if (eq? tmp53 0) then
  5420. %% goto block57;
  5421. %% else
  5422. %% goto block58;
  5423. %% block60:
  5424. %% goto block56;
  5425. %% block59:
  5426. %% goto block55;
  5427. %% block58:
  5428. %% goto block56;
  5429. %% block57:
  5430. %% goto block55;
  5431. %% block56:
  5432. %% return (+ 700 77);
  5433. %% block55:
  5434. %% return (+ 10 32);
  5435. %% start:
  5436. %% tmp52 = (read);
  5437. %% if (eq? tmp52 1) then
  5438. %% goto block61;
  5439. %% else
  5440. %% goto block62;
  5441. %% \end{lstlisting}
  5442. %% \end{minipage}
  5443. %% &
  5444. %% $\Rightarrow$
  5445. %% &
  5446. %% \begin{minipage}{0.55\textwidth}
  5447. %% \begin{lstlisting}
  5448. %% block62:
  5449. %% tmp54 = (read);
  5450. %% if (eq? tmp54 2) then
  5451. %% goto block55;
  5452. %% else
  5453. %% goto block56;
  5454. %% block61:
  5455. %% tmp53 = (read);
  5456. %% if (eq? tmp53 0) then
  5457. %% goto block55;
  5458. %% else
  5459. %% goto block56;
  5460. %% block56:
  5461. %% return (+ 700 77);
  5462. %% block55:
  5463. %% return (+ 10 32);
  5464. %% start:
  5465. %% tmp52 = (read);
  5466. %% if (eq? tmp52 1) then
  5467. %% goto block61;
  5468. %% else
  5469. %% goto block62;
  5470. %% \end{lstlisting}
  5471. %% \end{minipage}
  5472. %% \end{tabular}
  5473. %% \caption{Optimize jumps by removing trivial blocks.}
  5474. %% \label{fig:optimize-jumps}
  5475. %% \end{figure}
  5476. %% The name of this pass is \code{optimize-jumps}. We recommend
  5477. %% implementing this pass in two phases. The first phrase builds a hash
  5478. %% table that maps labels to possibly improved labels. The second phase
  5479. %% changes the target of each \code{goto} to use the improved label. If
  5480. %% the label is for a trivial block, then the hash table should map the
  5481. %% label to the first non-trivial block that can be reached from this
  5482. %% label by jumping through trivial blocks. If the label is for a
  5483. %% non-trivial block, then the hash table should map the label to itself;
  5484. %% we do not want to change jumps to non-trivial blocks.
  5485. %% The first phase can be accomplished by constructing an empty hash
  5486. %% table, call it \code{short-cut}, and then iterating over the control
  5487. %% flow graph. Each time you encouter a block that is just a \code{goto},
  5488. %% then update the hash table, mapping the block's source to the target
  5489. %% of the \code{goto}. Also, the hash table may already have mapped some
  5490. %% labels to the block's source, to you must iterate through the hash
  5491. %% table and update all of those so that they instead map to the target
  5492. %% of the \code{goto}.
  5493. %% For the second phase, we recommend iterating through the $\Tail$ of
  5494. %% each block in the program, updating the target of every \code{goto}
  5495. %% according to the mapping in \code{short-cut}.
  5496. %% \begin{exercise}\normalfont
  5497. %% Implement the \code{optimize-jumps} pass as a transformation from
  5498. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  5499. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  5500. %% example programs. Then check that your compiler still passes all of
  5501. %% your tests.
  5502. %% \end{exercise}
  5503. There is an opportunity for optimizing jumps that is apparent in the
  5504. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  5505. ends with a jump to \code{block7953} and there are no other jumps to
  5506. \code{block7953} in the rest of the program. In this situation we can
  5507. avoid the runtime overhead of this jump by merging \code{block7953}
  5508. into the preceding block, in this case the \code{start} block.
  5509. Figure~\ref{fig:remove-jumps} shows the output of
  5510. \code{select-instructions} on the left and the result of this
  5511. optimization on the right.
  5512. \begin{figure}[tbp]
  5513. \begin{tabular}{lll}
  5514. \begin{minipage}{0.5\textwidth}
  5515. % cond_test_20.rkt
  5516. \begin{lstlisting}
  5517. start:
  5518. callq read_int
  5519. movq %rax, tmp7951
  5520. cmpq $1, tmp7951
  5521. je block7952
  5522. jmp block7953
  5523. block7953:
  5524. movq $0, %rax
  5525. jmp conclusion
  5526. block7952:
  5527. movq $42, %rax
  5528. jmp conclusion
  5529. \end{lstlisting}
  5530. \end{minipage}
  5531. &
  5532. $\Rightarrow\qquad$
  5533. \begin{minipage}{0.4\textwidth}
  5534. \begin{lstlisting}
  5535. start:
  5536. callq read_int
  5537. movq %rax, tmp7951
  5538. cmpq $1, tmp7951
  5539. je block7952
  5540. movq $0, %rax
  5541. jmp conclusion
  5542. block7952:
  5543. movq $42, %rax
  5544. jmp conclusion
  5545. \end{lstlisting}
  5546. \end{minipage}
  5547. \end{tabular}
  5548. \caption{Merging basic blocks by removing unnecessary jumps.}
  5549. \label{fig:remove-jumps}
  5550. \end{figure}
  5551. \begin{exercise}\normalfont
  5552. %
  5553. Implement a pass named \code{remove-jumps} that merges basic blocks
  5554. into their preceding basic block, when there is only one preceding
  5555. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  5556. %
  5557. In the \code{run-tests.rkt} script, add the following entry to the
  5558. list of \code{passes} between \code{allocate-registers}
  5559. and \code{patch-instructions}.
  5560. \begin{lstlisting}
  5561. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  5562. \end{lstlisting}
  5563. Run this script to test your compiler.
  5564. %
  5565. Check that \code{remove-jumps} accomplishes the goal of merging basic
  5566. blocks on several test programs.
  5567. \end{exercise}
  5568. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5569. \chapter{Tuples and Garbage Collection}
  5570. \label{ch:Rvec}
  5571. \index{tuple}
  5572. \index{vector}
  5573. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  5574. all the IR grammars are spelled out! \\ --Jeremy}
  5575. \margincomment{\scriptsize Be more explicit about how to deal with
  5576. the root stack. \\ --Jeremy}
  5577. In this chapter we study the implementation of mutable tuples, called
  5578. vectors in Racket. This language feature is the first to use the
  5579. computer's \emph{heap}\index{heap} because the lifetime of a Racket
  5580. tuple is indefinite, that is, a tuple lives forever from the
  5581. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  5582. is important to reclaim the space associated with a tuple when it is
  5583. no longer needed, which is why we also study \emph{garbage collection}
  5584. \emph{garbage collection} techniques in this chapter.
  5585. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  5586. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  5587. language of Chapter~\ref{ch:Rif} with vectors and Racket's
  5588. \code{void} value. The reason for including the later is that the
  5589. \code{vector-set!} operation returns a value of type
  5590. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5591. called the \code{Unit} type in the programming languages
  5592. literature. Racket's \code{Void} type is inhabited by a single value
  5593. \code{void} which corresponds to \code{unit} or \code{()} in the
  5594. literature~\citep{Pierce:2002hj}.}.
  5595. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5596. copying live objects back and forth between two halves of the
  5597. heap. The garbage collector requires coordination with the compiler so
  5598. that it can see all of the \emph{root} pointers, that is, pointers in
  5599. registers or on the procedure call stack.
  5600. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5601. discuss all the necessary changes and additions to the compiler
  5602. passes, including a new compiler pass named \code{expose-allocation}.
  5603. \section{The \LangVec{} Language}
  5604. \label{sec:r3}
  5605. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  5606. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  5607. \LangVec{} language includes three new forms: \code{vector} for creating a
  5608. tuple, \code{vector-ref} for reading an element of a tuple, and
  5609. \code{vector-set!} for writing to an element of a tuple. The program
  5610. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5611. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5612. the 3-tuple, demonstrating that tuples are first-class values. The
  5613. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5614. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5615. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5616. 1-tuple. So the result of the program is \code{42}.
  5617. \begin{figure}[tbp]
  5618. \centering
  5619. \fbox{
  5620. \begin{minipage}{0.96\textwidth}
  5621. \[
  5622. \begin{array}{lcl}
  5623. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5624. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}\\
  5625. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5626. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5627. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5628. \mid \LP\key{and}\;\Exp\;\Exp\RP
  5629. \mid \LP\key{or}\;\Exp\;\Exp\RP
  5630. \mid \LP\key{not}\;\Exp\RP } \\
  5631. &\mid& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  5632. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5633. &\mid& \LP\key{vector}\;\Exp\ldots\RP
  5634. \mid \LP\key{vector-length}\;\Exp\RP \\
  5635. &\mid& \LP\key{vector-ref}\;\Exp\;\Int\RP
  5636. \mid \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  5637. &\mid& \LP\key{void}\RP \mid \LP\key{has-type}~\Exp~\Type\RP\\
  5638. \LangVec{} &::=& \Exp
  5639. \end{array}
  5640. \]
  5641. \end{minipage}
  5642. }
  5643. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  5644. (Figure~\ref{fig:Rif-concrete-syntax}).}
  5645. \label{fig:Rvec-concrete-syntax}
  5646. \end{figure}
  5647. \begin{figure}[tbp]
  5648. \begin{lstlisting}
  5649. (let ([t (vector 40 #t (vector 2))])
  5650. (if (vector-ref t 1)
  5651. (+ (vector-ref t 0)
  5652. (vector-ref (vector-ref t 2) 0))
  5653. 44))
  5654. \end{lstlisting}
  5655. \caption{Example program that creates tuples and reads from them.}
  5656. \label{fig:vector-eg}
  5657. \end{figure}
  5658. \begin{figure}[tp]
  5659. \centering
  5660. \fbox{
  5661. \begin{minipage}{0.96\textwidth}
  5662. \[
  5663. \begin{array}{lcl}
  5664. \itm{op} &::=& \ldots \mid \code{vector} \mid \code{vector-length} \\
  5665. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5666. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5667. \mid \BOOL{\itm{bool}}
  5668. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5669. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  5670. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  5671. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5672. \LangVec{} &::=& \PROGRAM{\key{'()}}{\Exp}
  5673. \end{array}
  5674. \]
  5675. \end{minipage}
  5676. }
  5677. \caption{The abstract syntax of \LangVec{}.}
  5678. \label{fig:Rvec-syntax}
  5679. \end{figure}
  5680. \index{allocate}
  5681. \index{heap allocate}
  5682. Tuples are our first encounter with heap-allocated data, which raises
  5683. several interesting issues. First, variable binding performs a
  5684. shallow-copy when dealing with tuples, which means that different
  5685. variables can refer to the same tuple, that is, different variables
  5686. can be \emph{aliases} for the same entity. Consider the following
  5687. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5688. Thus, the mutation through \code{t2} is visible when referencing the
  5689. tuple from \code{t1}, so the result of this program is \code{42}.
  5690. \index{alias}\index{mutation}
  5691. \begin{center}
  5692. \begin{minipage}{0.96\textwidth}
  5693. \begin{lstlisting}
  5694. (let ([t1 (vector 3 7)])
  5695. (let ([t2 t1])
  5696. (let ([_ (vector-set! t2 0 42)])
  5697. (vector-ref t1 0))))
  5698. \end{lstlisting}
  5699. \end{minipage}
  5700. \end{center}
  5701. The next issue concerns the lifetime of tuples. Of course, they are
  5702. created by the \code{vector} form, but when does their lifetime end?
  5703. Notice that \LangVec{} does not include an operation for deleting
  5704. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5705. of static scoping. For example, the following program returns
  5706. \code{42} even though the variable \code{w} goes out of scope prior to
  5707. the \code{vector-ref} that reads from the vector it was bound to.
  5708. \begin{center}
  5709. \begin{minipage}{0.96\textwidth}
  5710. \begin{lstlisting}
  5711. (let ([v (vector (vector 44))])
  5712. (let ([x (let ([w (vector 42)])
  5713. (let ([_ (vector-set! v 0 w)])
  5714. 0))])
  5715. (+ x (vector-ref (vector-ref v 0) 0))))
  5716. \end{lstlisting}
  5717. \end{minipage}
  5718. \end{center}
  5719. From the perspective of programmer-observable behavior, tuples live
  5720. forever. Of course, if they really lived forever, then many programs
  5721. would run out of memory.\footnote{The \LangVec{} language does not have
  5722. looping or recursive functions, so it is nigh impossible to write a
  5723. program in \LangVec{} that will run out of memory. However, we add
  5724. recursive functions in the next Chapter!} A Racket implementation
  5725. must therefore perform automatic garbage collection.
  5726. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  5727. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  5728. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  5729. terms of the corresponding operations in Racket. One subtle point is
  5730. that the \code{vector-set!} operation returns the \code{\#<void>}
  5731. value. The \code{\#<void>} value can be passed around just like other
  5732. values inside an \LangVec{} program and a \code{\#<void>} value can be
  5733. compared for equality with another \code{\#<void>} value. However,
  5734. there are no other operations specific to the the \code{\#<void>}
  5735. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  5736. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  5737. otherwise.
  5738. \begin{figure}[tbp]
  5739. \begin{lstlisting}
  5740. (define interp-Rvec-class
  5741. (class interp-Rif-class
  5742. (super-new)
  5743. (define/override (interp-op op)
  5744. (match op
  5745. ['eq? (lambda (v1 v2)
  5746. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5747. (and (boolean? v1) (boolean? v2))
  5748. (and (vector? v1) (vector? v2))
  5749. (and (void? v1) (void? v2)))
  5750. (eq? v1 v2)]))]
  5751. ['vector vector]
  5752. ['vector-length vector-length]
  5753. ['vector-ref vector-ref]
  5754. ['vector-set! vector-set!]
  5755. [else (super interp-op op)]
  5756. ))
  5757. (define/override ((interp-exp env) e)
  5758. (define recur (interp-exp env))
  5759. (match e
  5760. [(HasType e t) (recur e)]
  5761. [(Void) (void)]
  5762. [else ((super interp-exp env) e)]
  5763. ))
  5764. ))
  5765. (define (interp-Rvec p)
  5766. (send (new interp-Rvec-class) interp-program p))
  5767. \end{lstlisting}
  5768. \caption{Interpreter for the \LangVec{} language.}
  5769. \label{fig:interp-Rvec}
  5770. \end{figure}
  5771. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  5772. deserves some explanation. When allocating a vector, we need to know
  5773. which elements of the vector are pointers (i.e. are also vectors). We
  5774. can obtain this information during type checking. The type checker in
  5775. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  5776. expression, it also wraps every \key{vector} creation with the form
  5777. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  5778. %
  5779. To create the s-expression for the \code{Vector} type in
  5780. Figure~\ref{fig:type-check-Rvec}, we use the
  5781. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5782. operator} \code{,@} to insert the list \code{t*} without its usual
  5783. start and end parentheses. \index{unquote-slicing}
  5784. \begin{figure}[tp]
  5785. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5786. (define type-check-Rvec-class
  5787. (class type-check-Rif-class
  5788. (super-new)
  5789. (inherit check-type-equal?)
  5790. (define/override (type-check-exp env)
  5791. (lambda (e)
  5792. (define recur (type-check-exp env))
  5793. (match e
  5794. [(Void) (values (Void) 'Void)]
  5795. [(Prim 'vector es)
  5796. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5797. (define t `(Vector ,@t*))
  5798. (values (HasType (Prim 'vector e*) t) t)]
  5799. [(Prim 'vector-ref (list e1 (Int i)))
  5800. (define-values (e1^ t) (recur e1))
  5801. (match t
  5802. [`(Vector ,ts ...)
  5803. (unless (and (0 . <= . i) (i . < . (length ts)))
  5804. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5805. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  5806. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5807. [(Prim 'vector-set! (list e1 (Int i) arg) )
  5808. (define-values (e-vec t-vec) (recur e1))
  5809. (define-values (e-arg^ t-arg) (recur arg))
  5810. (match t-vec
  5811. [`(Vector ,ts ...)
  5812. (unless (and (0 . <= . i) (i . < . (length ts)))
  5813. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5814. (check-type-equal? (list-ref ts i) t-arg e)
  5815. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5816. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  5817. [(Prim 'vector-length (list e))
  5818. (define-values (e^ t) (recur e))
  5819. (match t
  5820. [`(Vector ,ts ...)
  5821. (values (Prim 'vector-length (list e^)) 'Integer)]
  5822. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5823. [(Prim 'eq? (list arg1 arg2))
  5824. (define-values (e1 t1) (recur arg1))
  5825. (define-values (e2 t2) (recur arg2))
  5826. (match* (t1 t2)
  5827. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  5828. [(other wise) (check-type-equal? t1 t2 e)])
  5829. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  5830. [(HasType (Prim 'vector es) t)
  5831. ((type-check-exp env) (Prim 'vector es))]
  5832. [(HasType e1 t)
  5833. (define-values (e1^ t^) (recur e1))
  5834. (check-type-equal? t t^ e)
  5835. (values (HasType e1^ t) t)]
  5836. [else ((super type-check-exp env) e)]
  5837. )))
  5838. ))
  5839. (define (type-check-Rvec p)
  5840. (send (new type-check-Rvec-class) type-check-program p))
  5841. \end{lstlisting}
  5842. \caption{Type checker for the \LangVec{} language.}
  5843. \label{fig:type-check-Rvec}
  5844. \end{figure}
  5845. \section{Garbage Collection}
  5846. \label{sec:GC}
  5847. Here we study a relatively simple algorithm for garbage collection
  5848. that is the basis of state-of-the-art garbage
  5849. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5850. particular, we describe a two-space copying
  5851. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5852. perform the
  5853. copy~\citep{Cheney:1970aa}.
  5854. \index{copying collector}
  5855. \index{two-space copying collector}
  5856. Figure~\ref{fig:copying-collector} gives a
  5857. coarse-grained depiction of what happens in a two-space collector,
  5858. showing two time steps, prior to garbage collection (on the top) and
  5859. after garbage collection (on the bottom). In a two-space collector,
  5860. the heap is divided into two parts named the FromSpace and the
  5861. ToSpace. Initially, all allocations go to the FromSpace until there is
  5862. not enough room for the next allocation request. At that point, the
  5863. garbage collector goes to work to make more room.
  5864. \index{ToSpace}
  5865. \index{FromSpace}
  5866. The garbage collector must be careful not to reclaim tuples that will
  5867. be used by the program in the future. Of course, it is impossible in
  5868. general to predict what a program will do, but we can over approximate
  5869. the will-be-used tuples by preserving all tuples that could be
  5870. accessed by \emph{any} program given the current computer state. A
  5871. program could access any tuple whose address is in a register or on
  5872. the procedure call stack. These addresses are called the \emph{root
  5873. set}\index{root set}. In addition, a program could access any tuple that is
  5874. transitively reachable from the root set. Thus, it is safe for the
  5875. garbage collector to reclaim the tuples that are not reachable in this
  5876. way.
  5877. So the goal of the garbage collector is twofold:
  5878. \begin{enumerate}
  5879. \item preserve all tuple that are reachable from the root set via a
  5880. path of pointers, that is, the \emph{live} tuples, and
  5881. \item reclaim the memory of everything else, that is, the
  5882. \emph{garbage}.
  5883. \end{enumerate}
  5884. A copying collector accomplishes this by copying all of the live
  5885. objects from the FromSpace into the ToSpace and then performs a sleight
  5886. of hand, treating the ToSpace as the new FromSpace and the old
  5887. FromSpace as the new ToSpace. In the example of
  5888. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5889. root set, one in a register and two on the stack. All of the live
  5890. objects have been copied to the ToSpace (the right-hand side of
  5891. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5892. pointer relationships. For example, the pointer in the register still
  5893. points to a 2-tuple whose first element is a 3-tuple and whose second
  5894. element is a 2-tuple. There are four tuples that are not reachable
  5895. from the root set and therefore do not get copied into the ToSpace.
  5896. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5897. created by a well-typed program in \LangVec{} because it contains a
  5898. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  5899. We design the garbage collector to deal with cycles to begin with so
  5900. we will not need to revisit this issue.
  5901. \begin{figure}[tbp]
  5902. \centering
  5903. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5904. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5905. \caption{A copying collector in action.}
  5906. \label{fig:copying-collector}
  5907. \end{figure}
  5908. There are many alternatives to copying collectors (and their bigger
  5909. siblings, the generational collectors) when its comes to garbage
  5910. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5911. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5912. collectors are that allocation is fast (just a comparison and pointer
  5913. increment), there is no fragmentation, cyclic garbage is collected,
  5914. and the time complexity of collection only depends on the amount of
  5915. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5916. main disadvantages of a two-space copying collector is that it uses a
  5917. lot of space and takes a long time to perform the copy, though these
  5918. problems are ameliorated in generational collectors. Racket and
  5919. Scheme programs tend to allocate many small objects and generate a lot
  5920. of garbage, so copying and generational collectors are a good fit.
  5921. Garbage collection is an active research topic, especially concurrent
  5922. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5923. developing new techniques and revisiting old
  5924. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5925. meet every year at the International Symposium on Memory Management to
  5926. present these findings.
  5927. \subsection{Graph Copying via Cheney's Algorithm}
  5928. \label{sec:cheney}
  5929. \index{Cheney's algorithm}
  5930. Let us take a closer look at the copying of the live objects. The
  5931. allocated objects and pointers can be viewed as a graph and we need to
  5932. copy the part of the graph that is reachable from the root set. To
  5933. make sure we copy all of the reachable vertices in the graph, we need
  5934. an exhaustive graph traversal algorithm, such as depth-first search or
  5935. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5936. such algorithms take into account the possibility of cycles by marking
  5937. which vertices have already been visited, so as to ensure termination
  5938. of the algorithm. These search algorithms also use a data structure
  5939. such as a stack or queue as a to-do list to keep track of the vertices
  5940. that need to be visited. We use breadth-first search and a trick
  5941. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5942. and copying tuples into the ToSpace.
  5943. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5944. copy progresses. The queue is represented by a chunk of contiguous
  5945. memory at the beginning of the ToSpace, using two pointers to track
  5946. the front and the back of the queue. The algorithm starts by copying
  5947. all tuples that are immediately reachable from the root set into the
  5948. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5949. old tuple to indicate that it has been visited. We discuss how this
  5950. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5951. pointers inside the copied tuples in the queue still point back to the
  5952. FromSpace. Once the initial queue has been created, the algorithm
  5953. enters a loop in which it repeatedly processes the tuple at the front
  5954. of the queue and pops it off the queue. To process a tuple, the
  5955. algorithm copies all the tuple that are directly reachable from it to
  5956. the ToSpace, placing them at the back of the queue. The algorithm then
  5957. updates the pointers in the popped tuple so they point to the newly
  5958. copied tuples.
  5959. \begin{figure}[tbp]
  5960. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5961. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5962. \label{fig:cheney}
  5963. \end{figure}
  5964. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5965. tuple whose second element is $42$ to the back of the queue. The other
  5966. pointer goes to a tuple that has already been copied, so we do not
  5967. need to copy it again, but we do need to update the pointer to the new
  5968. location. This can be accomplished by storing a \emph{forwarding
  5969. pointer} to the new location in the old tuple, back when we initially
  5970. copied the tuple into the ToSpace. This completes one step of the
  5971. algorithm. The algorithm continues in this way until the front of the
  5972. queue is empty, that is, until the front catches up with the back.
  5973. \subsection{Data Representation}
  5974. \label{sec:data-rep-gc}
  5975. The garbage collector places some requirements on the data
  5976. representations used by our compiler. First, the garbage collector
  5977. needs to distinguish between pointers and other kinds of data. There
  5978. are several ways to accomplish this.
  5979. \begin{enumerate}
  5980. \item Attached a tag to each object that identifies what type of
  5981. object it is~\citep{McCarthy:1960dz}.
  5982. \item Store different types of objects in different
  5983. regions~\citep{Steele:1977ab}.
  5984. \item Use type information from the program to either generate
  5985. type-specific code for collecting or to generate tables that can
  5986. guide the
  5987. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5988. \end{enumerate}
  5989. Dynamically typed languages, such as Lisp, need to tag objects
  5990. anyways, so option 1 is a natural choice for those languages.
  5991. However, \LangVec{} is a statically typed language, so it would be
  5992. unfortunate to require tags on every object, especially small and
  5993. pervasive objects like integers and Booleans. Option 3 is the
  5994. best-performing choice for statically typed languages, but comes with
  5995. a relatively high implementation complexity. To keep this chapter
  5996. within a 2-week time budget, we recommend a combination of options 1
  5997. and 2, using separate strategies for the stack and the heap.
  5998. Regarding the stack, we recommend using a separate stack for pointers,
  5999. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  6000. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  6001. is, when a local variable needs to be spilled and is of type
  6002. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  6003. stack instead of the normal procedure call stack. Furthermore, we
  6004. always spill vector-typed variables if they are live during a call to
  6005. the collector, thereby ensuring that no pointers are in registers
  6006. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  6007. example from Figure~\ref{fig:copying-collector} and contrasts it with
  6008. the data layout using a root stack. The root stack contains the two
  6009. pointers from the regular stack and also the pointer in the second
  6010. register.
  6011. \begin{figure}[tbp]
  6012. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  6013. \caption{Maintaining a root stack to facilitate garbage collection.}
  6014. \label{fig:shadow-stack}
  6015. \end{figure}
  6016. The problem of distinguishing between pointers and other kinds of data
  6017. also arises inside of each tuple on the heap. We solve this problem by
  6018. attaching a tag, an extra 64-bits, to each
  6019. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  6020. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  6021. that we have drawn the bits in a big-endian way, from right-to-left,
  6022. with bit location 0 (the least significant bit) on the far right,
  6023. which corresponds to the direction of the x86 shifting instructions
  6024. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  6025. is dedicated to specifying which elements of the tuple are pointers,
  6026. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  6027. indicates there is a pointer and a 0 bit indicates some other kind of
  6028. data. The pointer mask starts at bit location 7. We have limited
  6029. tuples to a maximum size of 50 elements, so we just need 50 bits for
  6030. the pointer mask. The tag also contains two other pieces of
  6031. information. The length of the tuple (number of elements) is stored in
  6032. bits location 1 through 6. Finally, the bit at location 0 indicates
  6033. whether the tuple has yet to be copied to the ToSpace. If the bit has
  6034. value 1, then this tuple has not yet been copied. If the bit has
  6035. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  6036. of a pointer are always zero anyways because our tuples are 8-byte
  6037. aligned.)
  6038. \begin{figure}[tbp]
  6039. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  6040. \caption{Representation of tuples in the heap.}
  6041. \label{fig:tuple-rep}
  6042. \end{figure}
  6043. \subsection{Implementation of the Garbage Collector}
  6044. \label{sec:organize-gz}
  6045. \index{prelude}
  6046. An implementation of the copying collector is provided in the
  6047. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  6048. interface to the garbage collector that is used by the compiler. The
  6049. \code{initialize} function creates the FromSpace, ToSpace, and root
  6050. stack and should be called in the prelude of the \code{main}
  6051. function. The arguments of \code{initialize} are the root stack size
  6052. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  6053. good choice for both. The \code{initialize} function puts the address
  6054. of the beginning of the FromSpace into the global variable
  6055. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  6056. the address that is 1-past the last element of the FromSpace. (We use
  6057. half-open intervals to represent chunks of
  6058. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  6059. points to the first element of the root stack.
  6060. As long as there is room left in the FromSpace, your generated code
  6061. can allocate tuples simply by moving the \code{free\_ptr} forward.
  6062. %
  6063. The amount of room left in FromSpace is the difference between the
  6064. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  6065. function should be called when there is not enough room left in the
  6066. FromSpace for the next allocation. The \code{collect} function takes
  6067. a pointer to the current top of the root stack (one past the last item
  6068. that was pushed) and the number of bytes that need to be
  6069. allocated. The \code{collect} function performs the copying collection
  6070. and leaves the heap in a state such that the next allocation will
  6071. succeed.
  6072. \begin{figure}[tbp]
  6073. \begin{lstlisting}
  6074. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  6075. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  6076. int64_t* free_ptr;
  6077. int64_t* fromspace_begin;
  6078. int64_t* fromspace_end;
  6079. int64_t** rootstack_begin;
  6080. \end{lstlisting}
  6081. \caption{The compiler's interface to the garbage collector.}
  6082. \label{fig:gc-header}
  6083. \end{figure}
  6084. %% \begin{exercise}
  6085. %% In the file \code{runtime.c} you will find the implementation of
  6086. %% \code{initialize} and a partial implementation of \code{collect}.
  6087. %% The \code{collect} function calls another function, \code{cheney},
  6088. %% to perform the actual copy, and that function is left to the reader
  6089. %% to implement. The following is the prototype for \code{cheney}.
  6090. %% \begin{lstlisting}
  6091. %% static void cheney(int64_t** rootstack_ptr);
  6092. %% \end{lstlisting}
  6093. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  6094. %% rootstack (which is an array of pointers). The \code{cheney} function
  6095. %% also communicates with \code{collect} through the global
  6096. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  6097. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  6098. %% the ToSpace:
  6099. %% \begin{lstlisting}
  6100. %% static int64_t* tospace_begin;
  6101. %% static int64_t* tospace_end;
  6102. %% \end{lstlisting}
  6103. %% The job of the \code{cheney} function is to copy all the live
  6104. %% objects (reachable from the root stack) into the ToSpace, update
  6105. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  6106. %% update the root stack so that it points to the objects in the
  6107. %% ToSpace, and finally to swap the global pointers for the FromSpace
  6108. %% and ToSpace.
  6109. %% \end{exercise}
  6110. %% \section{Compiler Passes}
  6111. %% \label{sec:code-generation-gc}
  6112. The introduction of garbage collection has a non-trivial impact on our
  6113. compiler passes. We introduce a new compiler pass named
  6114. \code{expose-allocation}. We make
  6115. significant changes to \code{select-instructions},
  6116. \code{build-interference}, \code{allocate-registers}, and
  6117. \code{print-x86} and make minor changes in several more passes. The
  6118. following program will serve as our running example. It creates two
  6119. tuples, one nested inside the other. Both tuples have length one. The
  6120. program accesses the element in the inner tuple tuple via two vector
  6121. references.
  6122. % tests/s2_17.rkt
  6123. \begin{lstlisting}
  6124. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  6125. \end{lstlisting}
  6126. \section{Shrink}
  6127. \label{sec:shrink-Rvec}
  6128. Recall that the \code{shrink} pass translates the primitives operators
  6129. into a smaller set of primitives. Because this pass comes after type
  6130. checking, but before the passes that require the type information in
  6131. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  6132. to wrap \code{HasType} around each AST node that it generates.
  6133. \section{Expose Allocation}
  6134. \label{sec:expose-allocation}
  6135. The pass \code{expose-allocation} lowers the \code{vector} creation
  6136. form into a conditional call to the collector followed by the
  6137. allocation. We choose to place the \code{expose-allocation} pass
  6138. before \code{remove-complex-opera*} because the code generated by
  6139. \code{expose-allocation} contains complex operands. We also place
  6140. \code{expose-allocation} before \code{explicate-control} because
  6141. \code{expose-allocation} introduces new variables using \code{let},
  6142. but \code{let} is gone after \code{explicate-control}.
  6143. The output of \code{expose-allocation} is a language \LangAlloc{} that
  6144. extends \LangVec{} with the three new forms that we use in the translation
  6145. of the \code{vector} form.
  6146. \[
  6147. \begin{array}{lcl}
  6148. \Exp &::=& \cdots
  6149. \mid (\key{collect} \,\itm{int})
  6150. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  6151. \mid (\key{global-value} \,\itm{name})
  6152. \end{array}
  6153. \]
  6154. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  6155. $n$ bytes. It will become a call to the \code{collect} function in
  6156. \code{runtime.c} in \code{select-instructions}. The
  6157. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  6158. \index{allocate}
  6159. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  6160. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  6161. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  6162. a global variable, such as \code{free\_ptr}.
  6163. In the following, we show the transformation for the \code{vector}
  6164. form into 1) a sequence of let-bindings for the initializing
  6165. expressions, 2) a conditional call to \code{collect}, 3) a call to
  6166. \code{allocate}, and 4) the initialization of the vector. In the
  6167. following, \itm{len} refers to the length of the vector and
  6168. \itm{bytes} is how many total bytes need to be allocated for the
  6169. vector, which is 8 for the tag plus \itm{len} times 8.
  6170. \begin{lstlisting}
  6171. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  6172. |$\Longrightarrow$|
  6173. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  6174. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  6175. (global-value fromspace_end))
  6176. (void)
  6177. (collect |\itm{bytes}|))])
  6178. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  6179. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  6180. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  6181. |$v$|) ... )))) ...)
  6182. \end{lstlisting}
  6183. In the above, we suppressed all of the \code{has-type} forms in the
  6184. output for the sake of readability. The placement of the initializing
  6185. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  6186. sequence of \code{vector-set!} is important, as those expressions may
  6187. trigger garbage collection and we cannot have an allocated but
  6188. uninitialized tuple on the heap during a collection.
  6189. Figure~\ref{fig:expose-alloc-output} shows the output of the
  6190. \code{expose-allocation} pass on our running example.
  6191. \begin{figure}[tbp]
  6192. % tests/s2_17.rkt
  6193. \begin{lstlisting}
  6194. (vector-ref
  6195. (vector-ref
  6196. (let ([vecinit7976
  6197. (let ([vecinit7972 42])
  6198. (let ([collectret7974
  6199. (if (< (+ (global-value free_ptr) 16)
  6200. (global-value fromspace_end))
  6201. (void)
  6202. (collect 16)
  6203. )])
  6204. (let ([alloc7971 (allocate 1 (Vector Integer))])
  6205. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  6206. alloc7971)
  6207. )
  6208. )
  6209. )
  6210. ])
  6211. (let ([collectret7978
  6212. (if (< (+ (global-value free_ptr) 16)
  6213. (global-value fromspace_end))
  6214. (void)
  6215. (collect 16)
  6216. )])
  6217. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  6218. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  6219. alloc7975)
  6220. )
  6221. )
  6222. )
  6223. 0)
  6224. 0)
  6225. \end{lstlisting}
  6226. \caption{Output of the \code{expose-allocation} pass, minus
  6227. all of the \code{has-type} forms.}
  6228. \label{fig:expose-alloc-output}
  6229. \end{figure}
  6230. \section{Remove Complex Operands}
  6231. \label{sec:remove-complex-opera-Rvec}
  6232. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  6233. should all be treated as complex operands.
  6234. %% A new case for
  6235. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  6236. %% handled carefully to prevent the \code{Prim} node from being separated
  6237. %% from its enclosing \code{HasType}.
  6238. Figure~\ref{fig:Rvec-anf-syntax}
  6239. shows the grammar for the output language \LangVecANF{} of this
  6240. pass, which is \LangVec{} in administrative normal form.
  6241. \begin{figure}[tp]
  6242. \centering
  6243. \fbox{
  6244. \begin{minipage}{0.96\textwidth}
  6245. \small
  6246. \[
  6247. \begin{array}{rcl}
  6248. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  6249. \mid \VOID{} \\
  6250. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  6251. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  6252. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6253. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  6254. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  6255. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  6256. \mid \LP\key{GlobalValue}~\Var\RP\\
  6257. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  6258. R^{\dagger}_3 &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  6259. \end{array}
  6260. \]
  6261. \end{minipage}
  6262. }
  6263. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  6264. \label{fig:Rvec-anf-syntax}
  6265. \end{figure}
  6266. \section{Explicate Control and the \LangCVec{} language}
  6267. \label{sec:explicate-control-r3}
  6268. \begin{figure}[tp]
  6269. \fbox{
  6270. \begin{minipage}{0.96\textwidth}
  6271. \small
  6272. \[
  6273. \begin{array}{lcl}
  6274. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6275. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6276. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6277. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6278. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6279. &\mid& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  6280. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  6281. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  6282. &\mid& \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP\\
  6283. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  6284. \mid \LP\key{Collect} \,\itm{int}\RP \\
  6285. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6286. \mid \GOTO{\itm{label}} } \\
  6287. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6288. \LangCVec{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  6289. \end{array}
  6290. \]
  6291. \end{minipage}
  6292. }
  6293. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  6294. (Figure~\ref{fig:c1-syntax}).}
  6295. \label{fig:c2-syntax}
  6296. \end{figure}
  6297. The output of \code{explicate-control} is a program in the
  6298. intermediate language \LangCVec{}, whose abstract syntax is defined in
  6299. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  6300. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  6301. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  6302. \key{vector-set!}, and \key{global-value} expressions and the
  6303. \code{collect} statement. The \code{explicate-control} pass can treat
  6304. these new forms much like the other expression forms that we've
  6305. already encoutered.
  6306. \section{Select Instructions and the \LangXGlobal{} Language}
  6307. \label{sec:select-instructions-gc}
  6308. \index{instruction selection}
  6309. %% void (rep as zero)
  6310. %% allocate
  6311. %% collect (callq collect)
  6312. %% vector-ref
  6313. %% vector-set!
  6314. %% global (postpone)
  6315. In this pass we generate x86 code for most of the new operations that
  6316. were needed to compile tuples, including \code{Allocate},
  6317. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  6318. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  6319. the later has a different concrete syntax (see
  6320. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  6321. \index{x86}
  6322. The \code{vector-ref} and \code{vector-set!} forms translate into
  6323. \code{movq} instructions. (The plus one in the offset is to get past
  6324. the tag at the beginning of the tuple representation.)
  6325. \begin{lstlisting}
  6326. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  6327. |$\Longrightarrow$|
  6328. movq |$\itm{vec}'$|, %r11
  6329. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  6330. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  6331. |$\Longrightarrow$|
  6332. movq |$\itm{vec}'$|, %r11
  6333. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  6334. movq $0, |$\itm{lhs'}$|
  6335. \end{lstlisting}
  6336. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  6337. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  6338. register \code{r11} ensures that offset expression
  6339. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  6340. removing \code{r11} from consideration by the register allocating.
  6341. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  6342. \code{rax}. Then the generated code for \code{vector-set!} would be
  6343. \begin{lstlisting}
  6344. movq |$\itm{vec}'$|, %rax
  6345. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  6346. movq $0, |$\itm{lhs}'$|
  6347. \end{lstlisting}
  6348. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  6349. \code{patch-instructions} would insert a move through \code{rax}
  6350. as follows.
  6351. \begin{lstlisting}
  6352. movq |$\itm{vec}'$|, %rax
  6353. movq |$\itm{arg}'$|, %rax
  6354. movq %rax, |$8(n+1)$|(%rax)
  6355. movq $0, |$\itm{lhs}'$|
  6356. \end{lstlisting}
  6357. But the above sequence of instructions does not work because we're
  6358. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  6359. $\itm{arg}'$) at the same time!
  6360. We compile the \code{allocate} form to operations on the
  6361. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  6362. is the next free address in the FromSpace, so we copy it into
  6363. \code{r11} and then move it forward by enough space for the tuple
  6364. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  6365. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  6366. initialize the \itm{tag} and finally copy the address in \code{r11} to
  6367. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  6368. tag is organized. We recommend using the Racket operations
  6369. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  6370. during compilation. The type annotation in the \code{vector} form is
  6371. used to determine the pointer mask region of the tag.
  6372. \begin{lstlisting}
  6373. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  6374. |$\Longrightarrow$|
  6375. movq free_ptr(%rip), %r11
  6376. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  6377. movq $|$\itm{tag}$|, 0(%r11)
  6378. movq %r11, |$\itm{lhs}'$|
  6379. \end{lstlisting}
  6380. The \code{collect} form is compiled to a call to the \code{collect}
  6381. function in the runtime. The arguments to \code{collect} are 1) the
  6382. top of the root stack and 2) the number of bytes that need to be
  6383. allocated. We use another dedicated register, \code{r15}, to
  6384. store the pointer to the top of the root stack. So \code{r15} is not
  6385. available for use by the register allocator.
  6386. \begin{lstlisting}
  6387. (collect |$\itm{bytes}$|)
  6388. |$\Longrightarrow$|
  6389. movq %r15, %rdi
  6390. movq $|\itm{bytes}|, %rsi
  6391. callq collect
  6392. \end{lstlisting}
  6393. \begin{figure}[tp]
  6394. \fbox{
  6395. \begin{minipage}{0.96\textwidth}
  6396. \[
  6397. \begin{array}{lcl}
  6398. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  6399. \LangXGlobal{} &::= & \gray{ \key{.globl main} }\\
  6400. & & \gray{ \key{main:} \; \Instr\ldots }
  6401. \end{array}
  6402. \]
  6403. \end{minipage}
  6404. }
  6405. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  6406. \label{fig:x86-2-concrete}
  6407. \end{figure}
  6408. \begin{figure}[tp]
  6409. \fbox{
  6410. \begin{minipage}{0.96\textwidth}
  6411. \small
  6412. \[
  6413. \begin{array}{lcl}
  6414. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6415. \mid \BYTEREG{\Reg}} \\
  6416. &\mid& (\key{Global}~\Var) \\
  6417. \LangXGlobal{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  6418. \end{array}
  6419. \]
  6420. \end{minipage}
  6421. }
  6422. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  6423. \label{fig:x86-2}
  6424. \end{figure}
  6425. The concrete and abstract syntax of the \LangXGlobal{} language is
  6426. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  6427. differs from \LangXIf{} just in the addition of the form for global
  6428. variables.
  6429. %
  6430. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  6431. \code{select-instructions} pass on the running example.
  6432. \begin{figure}[tbp]
  6433. \centering
  6434. % tests/s2_17.rkt
  6435. \begin{minipage}[t]{0.5\textwidth}
  6436. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6437. block35:
  6438. movq free_ptr(%rip), alloc9024
  6439. addq $16, free_ptr(%rip)
  6440. movq alloc9024, %r11
  6441. movq $131, 0(%r11)
  6442. movq alloc9024, %r11
  6443. movq vecinit9025, 8(%r11)
  6444. movq $0, initret9026
  6445. movq alloc9024, %r11
  6446. movq 8(%r11), tmp9034
  6447. movq tmp9034, %r11
  6448. movq 8(%r11), %rax
  6449. jmp conclusion
  6450. block36:
  6451. movq $0, collectret9027
  6452. jmp block35
  6453. block38:
  6454. movq free_ptr(%rip), alloc9020
  6455. addq $16, free_ptr(%rip)
  6456. movq alloc9020, %r11
  6457. movq $3, 0(%r11)
  6458. movq alloc9020, %r11
  6459. movq vecinit9021, 8(%r11)
  6460. movq $0, initret9022
  6461. movq alloc9020, vecinit9025
  6462. movq free_ptr(%rip), tmp9031
  6463. movq tmp9031, tmp9032
  6464. addq $16, tmp9032
  6465. movq fromspace_end(%rip), tmp9033
  6466. cmpq tmp9033, tmp9032
  6467. jl block36
  6468. jmp block37
  6469. block37:
  6470. movq %r15, %rdi
  6471. movq $16, %rsi
  6472. callq 'collect
  6473. jmp block35
  6474. block39:
  6475. movq $0, collectret9023
  6476. jmp block38
  6477. \end{lstlisting}
  6478. \end{minipage}
  6479. \begin{minipage}[t]{0.45\textwidth}
  6480. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6481. start:
  6482. movq $42, vecinit9021
  6483. movq free_ptr(%rip), tmp9028
  6484. movq tmp9028, tmp9029
  6485. addq $16, tmp9029
  6486. movq fromspace_end(%rip), tmp9030
  6487. cmpq tmp9030, tmp9029
  6488. jl block39
  6489. jmp block40
  6490. block40:
  6491. movq %r15, %rdi
  6492. movq $16, %rsi
  6493. callq 'collect
  6494. jmp block38
  6495. \end{lstlisting}
  6496. \end{minipage}
  6497. \caption{Output of the \code{select-instructions} pass.}
  6498. \label{fig:select-instr-output-gc}
  6499. \end{figure}
  6500. \clearpage
  6501. \section{Register Allocation}
  6502. \label{sec:reg-alloc-gc}
  6503. \index{register allocation}
  6504. As discussed earlier in this chapter, the garbage collector needs to
  6505. access all the pointers in the root set, that is, all variables that
  6506. are vectors. It will be the responsibility of the register allocator
  6507. to make sure that:
  6508. \begin{enumerate}
  6509. \item the root stack is used for spilling vector-typed variables, and
  6510. \item if a vector-typed variable is live during a call to the
  6511. collector, it must be spilled to ensure it is visible to the
  6512. collector.
  6513. \end{enumerate}
  6514. The later responsibility can be handled during construction of the
  6515. interference graph, by adding interference edges between the call-live
  6516. vector-typed variables and all the callee-saved registers. (They
  6517. already interfere with the caller-saved registers.) The type
  6518. information for variables is in the \code{Program} form, so we
  6519. recommend adding another parameter to the \code{build-interference}
  6520. function to communicate this alist.
  6521. The spilling of vector-typed variables to the root stack can be
  6522. handled after graph coloring, when choosing how to assign the colors
  6523. (integers) to registers and stack locations. The \code{Program} output
  6524. of this pass changes to also record the number of spills to the root
  6525. stack.
  6526. % build-interference
  6527. %
  6528. % callq
  6529. % extra parameter for var->type assoc. list
  6530. % update 'program' and 'if'
  6531. % allocate-registers
  6532. % allocate spilled vectors to the rootstack
  6533. % don't change color-graph
  6534. \section{Print x86}
  6535. \label{sec:print-x86-gc}
  6536. \index{prelude}\index{conclusion}
  6537. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  6538. \code{print-x86} pass on the running example. In the prelude and
  6539. conclusion of the \code{main} function, we treat the root stack very
  6540. much like the regular stack in that we move the root stack pointer
  6541. (\code{r15}) to make room for the spills to the root stack, except
  6542. that the root stack grows up instead of down. For the running
  6543. example, there was just one spill so we increment \code{r15} by 8
  6544. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  6545. One issue that deserves special care is that there may be a call to
  6546. \code{collect} prior to the initializing assignments for all the
  6547. variables in the root stack. We do not want the garbage collector to
  6548. accidentally think that some uninitialized variable is a pointer that
  6549. needs to be followed. Thus, we zero-out all locations on the root
  6550. stack in the prelude of \code{main}. In
  6551. Figure~\ref{fig:print-x86-output-gc}, the instruction
  6552. %
  6553. \lstinline{movq $0, (%r15)}
  6554. %
  6555. accomplishes this task. The garbage collector tests each root to see
  6556. if it is null prior to dereferencing it.
  6557. \begin{figure}[htbp]
  6558. \begin{minipage}[t]{0.5\textwidth}
  6559. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6560. block35:
  6561. movq free_ptr(%rip), %rcx
  6562. addq $16, free_ptr(%rip)
  6563. movq %rcx, %r11
  6564. movq $131, 0(%r11)
  6565. movq %rcx, %r11
  6566. movq -8(%r15), %rax
  6567. movq %rax, 8(%r11)
  6568. movq $0, %rdx
  6569. movq %rcx, %r11
  6570. movq 8(%r11), %rcx
  6571. movq %rcx, %r11
  6572. movq 8(%r11), %rax
  6573. jmp conclusion
  6574. block36:
  6575. movq $0, %rcx
  6576. jmp block35
  6577. block38:
  6578. movq free_ptr(%rip), %rcx
  6579. addq $16, free_ptr(%rip)
  6580. movq %rcx, %r11
  6581. movq $3, 0(%r11)
  6582. movq %rcx, %r11
  6583. movq %rbx, 8(%r11)
  6584. movq $0, %rdx
  6585. movq %rcx, -8(%r15)
  6586. movq free_ptr(%rip), %rcx
  6587. addq $16, %rcx
  6588. movq fromspace_end(%rip), %rdx
  6589. cmpq %rdx, %rcx
  6590. jl block36
  6591. movq %r15, %rdi
  6592. movq $16, %rsi
  6593. callq collect
  6594. jmp block35
  6595. block39:
  6596. movq $0, %rcx
  6597. jmp block38
  6598. \end{lstlisting}
  6599. \end{minipage}
  6600. \begin{minipage}[t]{0.45\textwidth}
  6601. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6602. start:
  6603. movq $42, %rbx
  6604. movq free_ptr(%rip), %rdx
  6605. addq $16, %rdx
  6606. movq fromspace_end(%rip), %rcx
  6607. cmpq %rcx, %rdx
  6608. jl block39
  6609. movq %r15, %rdi
  6610. movq $16, %rsi
  6611. callq collect
  6612. jmp block38
  6613. .globl main
  6614. main:
  6615. pushq %rbp
  6616. movq %rsp, %rbp
  6617. pushq %r13
  6618. pushq %r12
  6619. pushq %rbx
  6620. pushq %r14
  6621. subq $0, %rsp
  6622. movq $16384, %rdi
  6623. movq $16384, %rsi
  6624. callq initialize
  6625. movq rootstack_begin(%rip), %r15
  6626. movq $0, (%r15)
  6627. addq $8, %r15
  6628. jmp start
  6629. conclusion:
  6630. subq $8, %r15
  6631. addq $0, %rsp
  6632. popq %r14
  6633. popq %rbx
  6634. popq %r12
  6635. popq %r13
  6636. popq %rbp
  6637. retq
  6638. \end{lstlisting}
  6639. \end{minipage}
  6640. \caption{Output of the \code{print-x86} pass.}
  6641. \label{fig:print-x86-output-gc}
  6642. \end{figure}
  6643. \begin{figure}[p]
  6644. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6645. \node (Rvec) at (0,2) {\large \LangVec{}};
  6646. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  6647. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  6648. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  6649. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  6650. \node (C2-4) at (3,0) {\large \LangCVec{}};
  6651. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  6652. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  6653. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  6654. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  6655. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  6656. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  6657. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  6658. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  6659. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  6660. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  6661. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  6662. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  6663. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  6664. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6665. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6666. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6667. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6668. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  6669. \end{tikzpicture}
  6670. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  6671. \label{fig:Rvec-passes}
  6672. \end{figure}
  6673. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  6674. for the compilation of \LangVec{}.
  6675. \section{Challenge: Simple Structures}
  6676. \label{sec:simple-structures}
  6677. \index{struct}
  6678. \index{structure}
  6679. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6680. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  6681. Recall that a \code{struct} in Typed Racket is a user-defined data
  6682. type that contains named fields and that is heap allocated, similar to
  6683. a vector. The following is an example of a structure definition, in
  6684. this case the definition of a \code{point} type.
  6685. \begin{lstlisting}
  6686. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6687. \end{lstlisting}
  6688. \begin{figure}[tbp]
  6689. \centering
  6690. \fbox{
  6691. \begin{minipage}{0.96\textwidth}
  6692. \[
  6693. \begin{array}{lcl}
  6694. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6695. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6696. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6697. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6698. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6699. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6700. \mid (\key{and}\;\Exp\;\Exp)
  6701. \mid (\key{or}\;\Exp\;\Exp)
  6702. \mid (\key{not}\;\Exp) } \\
  6703. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6704. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6705. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6706. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6707. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6708. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6709. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6710. \LangStruct{} &::=& \Def \ldots \; \Exp
  6711. \end{array}
  6712. \]
  6713. \end{minipage}
  6714. }
  6715. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  6716. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6717. \label{fig:r3s-concrete-syntax}
  6718. \end{figure}
  6719. An instance of a structure is created using function call syntax, with
  6720. the name of the structure in the function position:
  6721. \begin{lstlisting}
  6722. (point 7 12)
  6723. \end{lstlisting}
  6724. Function-call syntax is also used to read the value in a field of a
  6725. structure. The function name is formed by the structure name, a dash,
  6726. and the field name. The following example uses \code{point-x} and
  6727. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6728. instances.
  6729. \begin{center}
  6730. \begin{lstlisting}
  6731. (let ([pt1 (point 7 12)])
  6732. (let ([pt2 (point 4 3)])
  6733. (+ (- (point-x pt1) (point-x pt2))
  6734. (- (point-y pt1) (point-y pt2)))))
  6735. \end{lstlisting}
  6736. \end{center}
  6737. Similarly, to write to a field of a structure, use its set function,
  6738. whose name starts with \code{set-}, followed by the structure name,
  6739. then a dash, then the field name, and concluded with an exclamation
  6740. mark. The following example uses \code{set-point-x!} to change the
  6741. \code{x} field from \code{7} to \code{42}.
  6742. \begin{center}
  6743. \begin{lstlisting}
  6744. (let ([pt (point 7 12)])
  6745. (let ([_ (set-point-x! pt 42)])
  6746. (point-x pt)))
  6747. \end{lstlisting}
  6748. \end{center}
  6749. \begin{exercise}\normalfont
  6750. Extend your compiler with support for simple structures, compiling
  6751. \LangStruct{} to x86 assembly code. Create five new test cases that use
  6752. structures and test your compiler.
  6753. \end{exercise}
  6754. \section{Challenge: Generational Collection}
  6755. The copying collector described in Section~\ref{sec:GC} can incur
  6756. significant runtime overhead because the call to \code{collect} takes
  6757. time proportional to all of the live data. One way to reduce this
  6758. overhead is to reduce how much data is inspected in each call to
  6759. \code{collect}. In particular, researchers have observed that recently
  6760. allocated data is more likely to become garbage then data that has
  6761. survived one or more previous calls to \code{collect}. This insight
  6762. motivated the creation of \emph{generational garbage collectors}
  6763. \index{generational garbage collector} that
  6764. 1) segregates data according to its age into two or more generations,
  6765. 2) allocates less space for younger generations, so collecting them is
  6766. faster, and more space for the older generations, and 3) performs
  6767. collection on the younger generations more frequently then for older
  6768. generations~\citep{Wilson:1992fk}.
  6769. For this challenge assignment, the goal is to adapt the copying
  6770. collector implemented in \code{runtime.c} to use two generations, one
  6771. for young data and one for old data. Each generation consists of a
  6772. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6773. \code{collect} function to use the two generations.
  6774. \begin{enumerate}
  6775. \item Copy the young generation's FromSpace to its ToSpace then switch
  6776. the role of the ToSpace and FromSpace
  6777. \item If there is enough space for the requested number of bytes in
  6778. the young FromSpace, then return from \code{collect}.
  6779. \item If there is not enough space in the young FromSpace for the
  6780. requested bytes, then move the data from the young generation to the
  6781. old one with the following steps:
  6782. \begin{enumerate}
  6783. \item If there is enough room in the old FromSpace, copy the young
  6784. FromSpace to the old FromSpace and then return.
  6785. \item If there is not enough room in the old FromSpace, then collect
  6786. the old generation by copying the old FromSpace to the old ToSpace
  6787. and swap the roles of the old FromSpace and ToSpace.
  6788. \item If there is enough room now, copy the young FromSpace to the
  6789. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6790. and ToSpace for the old generation. Copy the young FromSpace and
  6791. the old FromSpace into the larger FromSpace for the old
  6792. generation and then return.
  6793. \end{enumerate}
  6794. \end{enumerate}
  6795. We recommend that you generalize the \code{cheney} function so that it
  6796. can be used for all the copies mentioned above: between the young
  6797. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6798. between the young FromSpace and old FromSpace. This can be
  6799. accomplished by adding parameters to \code{cheney} that replace its
  6800. use of the global variables \code{fromspace\_begin},
  6801. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6802. Note that the collection of the young generation does not traverse the
  6803. old generation. This introduces a potential problem: there may be
  6804. young data that is only reachable through pointers in the old
  6805. generation. If these pointers are not taken into account, the
  6806. collector could throw away young data that is live! One solution,
  6807. called \emph{pointer recording}, is to maintain a set of all the
  6808. pointers from the old generation into the new generation and consider
  6809. this set as part of the root set. To maintain this set, the compiler
  6810. must insert extra instructions around every \code{vector-set!}. If the
  6811. vector being modified is in the old generation, and if the value being
  6812. written is a pointer into the new generation, than that pointer must
  6813. be added to the set. Also, if the value being overwritten was a
  6814. pointer into the new generation, then that pointer should be removed
  6815. from the set.
  6816. \begin{exercise}\normalfont
  6817. Adapt the \code{collect} function in \code{runtime.c} to implement
  6818. generational garbage collection, as outlined in this section.
  6819. Update the code generation for \code{vector-set!} to implement
  6820. pointer recording. Make sure that your new compiler and runtime
  6821. passes your test suite.
  6822. \end{exercise}
  6823. % TODO: challenge, implement homogeneous vectors
  6824. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6825. \chapter{Functions}
  6826. \label{ch:Rfun}
  6827. \index{function}
  6828. This chapter studies the compilation of functions similar to those
  6829. found in the C language. This corresponds to a subset of Typed Racket
  6830. in which only top-level function definitions are allowed. This kind of
  6831. function is an important stepping stone to implementing
  6832. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6833. is the topic of Chapter~\ref{ch:Rlam}.
  6834. \section{The \LangFun{} Language}
  6835. The concrete and abstract syntax for function definitions and function
  6836. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  6837. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  6838. \LangFun{} begin with zero or more function definitions. The function
  6839. names from these definitions are in-scope for the entire program,
  6840. including all other function definitions (so the ordering of function
  6841. definitions does not matter). The concrete syntax for function
  6842. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6843. where the first expression must
  6844. evaluate to a function and the rest are the arguments.
  6845. The abstract syntax for function application is
  6846. $\APPLY{\Exp}{\Exp\ldots}$.
  6847. %% The syntax for function application does not include an explicit
  6848. %% keyword, which is error prone when using \code{match}. To alleviate
  6849. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6850. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6851. Functions are first-class in the sense that a function pointer
  6852. \index{function pointer} is data and can be stored in memory or passed
  6853. as a parameter to another function. Thus, we introduce a function
  6854. type, written
  6855. \begin{lstlisting}
  6856. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6857. \end{lstlisting}
  6858. for a function whose $n$ parameters have the types $\Type_1$ through
  6859. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6860. these functions (with respect to Racket functions) is that they are
  6861. not lexically scoped. That is, the only external entities that can be
  6862. referenced from inside a function body are other globally-defined
  6863. functions. The syntax of \LangFun{} prevents functions from being nested
  6864. inside each other.
  6865. \begin{figure}[tp]
  6866. \centering
  6867. \fbox{
  6868. \begin{minipage}{0.96\textwidth}
  6869. \small
  6870. \[
  6871. \begin{array}{lcl}
  6872. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6873. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6874. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6875. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6876. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6877. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6878. \mid (\key{and}\;\Exp\;\Exp)
  6879. \mid (\key{or}\;\Exp\;\Exp)
  6880. \mid (\key{not}\;\Exp)} \\
  6881. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6882. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6883. (\key{vector-ref}\;\Exp\;\Int)} \\
  6884. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6885. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6886. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6887. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6888. \LangFun{} &::=& \Def \ldots \; \Exp
  6889. \end{array}
  6890. \]
  6891. \end{minipage}
  6892. }
  6893. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6894. \label{fig:Rfun-concrete-syntax}
  6895. \end{figure}
  6896. \begin{figure}[tp]
  6897. \centering
  6898. \fbox{
  6899. \begin{minipage}{0.96\textwidth}
  6900. \small
  6901. \[
  6902. \begin{array}{lcl}
  6903. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6904. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6905. &\mid& \gray{ \BOOL{\itm{bool}}
  6906. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6907. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6908. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6909. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6910. \LangFun{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6911. \end{array}
  6912. \]
  6913. \end{minipage}
  6914. }
  6915. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  6916. \label{fig:Rfun-syntax}
  6917. \end{figure}
  6918. The program in Figure~\ref{fig:Rfun-function-example} is a
  6919. representative example of defining and using functions in \LangFun{}. We
  6920. define a function \code{map-vec} that applies some other function
  6921. \code{f} to both elements of a vector and returns a new
  6922. vector containing the results. We also define a function \code{add1}.
  6923. The program applies
  6924. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6925. \code{(vector 1 42)}, from which we return the \code{42}.
  6926. \begin{figure}[tbp]
  6927. \begin{lstlisting}
  6928. (define (map-vec [f : (Integer -> Integer)]
  6929. [v : (Vector Integer Integer)])
  6930. : (Vector Integer Integer)
  6931. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6932. (define (add1 [x : Integer]) : Integer
  6933. (+ x 1))
  6934. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6935. \end{lstlisting}
  6936. \caption{Example of using functions in \LangFun{}.}
  6937. \label{fig:Rfun-function-example}
  6938. \end{figure}
  6939. The definitional interpreter for \LangFun{} is in
  6940. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  6941. responsible for setting up the mutual recursion between the top-level
  6942. function definitions. We use the classic back-patching \index{back-patching}
  6943. approach that uses mutable variables and makes two passes over the function
  6944. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6945. top-level environment using a mutable cons cell for each function
  6946. definition. Note that the \code{lambda} value for each function is
  6947. incomplete; it does not yet include the environment. Once the
  6948. top-level environment is constructed, we then iterate over it and
  6949. update the \code{lambda} values to use the top-level environment.
  6950. \begin{figure}[tp]
  6951. \begin{lstlisting}
  6952. (define interp-Rfun-class
  6953. (class interp-Rvec-class
  6954. (super-new)
  6955. (define/override ((interp-exp env) e)
  6956. (define recur (interp-exp env))
  6957. (match e
  6958. [(Var x) (unbox (dict-ref env x))]
  6959. [(Let x e body)
  6960. (define new-env (dict-set env x (box (recur e))))
  6961. ((interp-exp new-env) body)]
  6962. [(Apply fun args)
  6963. (define fun-val (recur fun))
  6964. (define arg-vals (for/list ([e args]) (recur e)))
  6965. (match fun-val
  6966. [`(function (,xs ...) ,body ,fun-env)
  6967. (define params-args (for/list ([x xs] [arg arg-vals])
  6968. (cons x (box arg))))
  6969. (define new-env (append params-args fun-env))
  6970. ((interp-exp new-env) body)]
  6971. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  6972. [else ((super interp-exp env) e)]
  6973. ))
  6974. (define/public (interp-def d)
  6975. (match d
  6976. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6977. (cons f (box `(function ,xs ,body ())))]))
  6978. (define/override (interp-program p)
  6979. (match p
  6980. [(ProgramDefsExp info ds body)
  6981. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6982. (for/list ([f (in-dict-values top-level)])
  6983. (set-box! f (match (unbox f)
  6984. [`(function ,xs ,body ())
  6985. `(function ,xs ,body ,top-level)])))
  6986. ((interp-exp top-level) body))]))
  6987. ))
  6988. (define (interp-Rfun p)
  6989. (send (new interp-Rfun-class) interp-program p))
  6990. \end{lstlisting}
  6991. \caption{Interpreter for the \LangFun{} language.}
  6992. \label{fig:interp-Rfun}
  6993. \end{figure}
  6994. \margincomment{TODO: explain type checker}
  6995. The type checker for \LangFun{} is is in Figure~\ref{fig:type-check-Rfun}.
  6996. \begin{figure}[tp]
  6997. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6998. (define type-check-Rfun-class
  6999. (class type-check-Rvec-class
  7000. (super-new)
  7001. (inherit check-type-equal?)
  7002. (define/public (type-check-apply env e es)
  7003. (define-values (e^ ty) ((type-check-exp env) e))
  7004. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  7005. ((type-check-exp env) e)))
  7006. (match ty
  7007. [`(,ty^* ... -> ,rt)
  7008. (for ([arg-ty ty*] [param-ty ty^*])
  7009. (check-type-equal? arg-ty param-ty (Apply e es)))
  7010. (values e^ e* rt)]))
  7011. (define/override (type-check-exp env)
  7012. (lambda (e)
  7013. (match e
  7014. [(FunRef f)
  7015. (values (FunRef f) (dict-ref env f))]
  7016. [(Apply e es)
  7017. (define-values (e^ es^ rt) (type-check-apply env e es))
  7018. (values (Apply e^ es^) rt)]
  7019. [(Call e es)
  7020. (define-values (e^ es^ rt) (type-check-apply env e es))
  7021. (values (Call e^ es^) rt)]
  7022. [else ((super type-check-exp env) e)])))
  7023. (define/public (type-check-def env)
  7024. (lambda (e)
  7025. (match e
  7026. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  7027. (define new-env (append (map cons xs ps) env))
  7028. (define-values (body^ ty^) ((type-check-exp new-env) body))
  7029. (check-type-equal? ty^ rt body)
  7030. (Def f p:t* rt info body^)])))
  7031. (define/public (fun-def-type d)
  7032. (match d
  7033. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  7034. (define/override (type-check-program e)
  7035. (match e
  7036. [(ProgramDefsExp info ds body)
  7037. (define new-env (for/list ([d ds])
  7038. (cons (Def-name d) (fun-def-type d))))
  7039. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  7040. (define-values (body^ ty) ((type-check-exp new-env) body))
  7041. (check-type-equal? ty 'Integer body)
  7042. (ProgramDefsExp info ds^ body^)]))))
  7043. (define (type-check-Rfun p)
  7044. (send (new type-check-Rfun-class) type-check-program p))
  7045. \end{lstlisting}
  7046. \caption{Type checker for the \LangFun{} language.}
  7047. \label{fig:type-check-Rfun}
  7048. \end{figure}
  7049. \section{Functions in x86}
  7050. \label{sec:fun-x86}
  7051. \margincomment{\tiny Make sure callee-saved registers are discussed
  7052. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  7053. \margincomment{\tiny Talk about the return address on the
  7054. stack and what callq and retq does.\\ --Jeremy }
  7055. The x86 architecture provides a few features to support the
  7056. implementation of functions. We have already seen that x86 provides
  7057. labels so that one can refer to the location of an instruction, as is
  7058. needed for jump instructions. Labels can also be used to mark the
  7059. beginning of the instructions for a function. Going further, we can
  7060. obtain the address of a label by using the \key{leaq} instruction and
  7061. PC-relative addressing. For example, the following puts the
  7062. address of the \code{add1} label into the \code{rbx} register.
  7063. \begin{lstlisting}
  7064. leaq add1(%rip), %rbx
  7065. \end{lstlisting}
  7066. The instruction pointer register \key{rip} (aka. the program counter
  7067. \index{program counter}) always points to the next instruction to be
  7068. executed. When combined with an label, as in \code{add1(\%rip)}, the
  7069. linker computes the distance $d$ between the address of \code{add1}
  7070. and where the \code{rip} would be at that moment and then changes
  7071. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  7072. the address of \code{add1}.
  7073. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  7074. jump to a function whose location is given by a label. To support
  7075. function calls in this chapter we instead will be jumping to a
  7076. function whose location is given by an address in a register, that is,
  7077. we need to make an \emph{indirect function call}. The x86 syntax for
  7078. this is a \code{callq} instruction but with an asterisk before the
  7079. register name.\index{indirect function call}
  7080. \begin{lstlisting}
  7081. callq *%rbx
  7082. \end{lstlisting}
  7083. \subsection{Calling Conventions}
  7084. \index{calling conventions}
  7085. The \code{callq} instruction provides partial support for implementing
  7086. functions: it pushes the return address on the stack and it jumps to
  7087. the target. However, \code{callq} does not handle
  7088. \begin{enumerate}
  7089. \item parameter passing,
  7090. \item pushing frames on the procedure call stack and popping them off,
  7091. or
  7092. \item determining how registers are shared by different functions.
  7093. \end{enumerate}
  7094. Regarding (1) parameter passing, recall that the following six
  7095. registers are used to pass arguments to a function, in this order.
  7096. \begin{lstlisting}
  7097. rdi rsi rdx rcx r8 r9
  7098. \end{lstlisting}
  7099. If there are
  7100. more than six arguments, then the convention is to use space on the
  7101. frame of the caller for the rest of the arguments. However, to ease
  7102. the implementation of efficient tail calls
  7103. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  7104. arguments.
  7105. %
  7106. Also recall that the register \code{rax} is for the return value of
  7107. the function.
  7108. \index{prelude}\index{conclusion}
  7109. Regarding (2) frames \index{frame} and the procedure call stack,
  7110. \index{procedure call stack} recall from Section~\ref{sec:x86} that
  7111. the stack grows down, with each function call using a chunk of space
  7112. called a frame. The caller sets the stack pointer, register
  7113. \code{rsp}, to the last data item in its frame. The callee must not
  7114. change anything in the caller's frame, that is, anything that is at or
  7115. above the stack pointer. The callee is free to use locations that are
  7116. below the stack pointer.
  7117. Recall that we are storing variables of vector type on the root stack.
  7118. So the prelude needs to move the root stack pointer \code{r15} up and
  7119. the conclusion needs to move the root stack pointer back down. Also,
  7120. the prelude must initialize to \code{0} this frame's slots in the root
  7121. stack to signal to the garbage collector that those slots do not yet
  7122. contain a pointer to a vector. Otherwise the garbage collector will
  7123. interpret the garbage bits in those slots as memory addresses and try
  7124. to traverse them, causing serious mayhem!
  7125. Regarding (3) the sharing of registers between different functions,
  7126. recall from Section~\ref{sec:calling-conventions} that the registers
  7127. are divided into two groups, the caller-saved registers and the
  7128. callee-saved registers. The caller should assume that all the
  7129. caller-saved registers get overwritten with arbitrary values by the
  7130. callee. That is why we recommend in
  7131. Section~\ref{sec:calling-conventions} that variables that are live
  7132. during a function call should not be assigned to caller-saved
  7133. registers.
  7134. On the flip side, if the callee wants to use a callee-saved register,
  7135. the callee must save the contents of those registers on their stack
  7136. frame and then put them back prior to returning to the caller. That
  7137. is why we recommended in Section~\ref{sec:calling-conventions} that if
  7138. the register allocator assigns a variable to a callee-saved register,
  7139. then the prelude of the \code{main} function must save that register
  7140. to the stack and the conclusion of \code{main} must restore it. This
  7141. recommendation now generalizes to all functions.
  7142. Also recall that the base pointer, register \code{rbp}, is used as a
  7143. point-of-reference within a frame, so that each local variable can be
  7144. accessed at a fixed offset from the base pointer
  7145. (Section~\ref{sec:x86}).
  7146. %
  7147. Figure~\ref{fig:call-frames} shows the general layout of the caller
  7148. and callee frames.
  7149. \begin{figure}[tbp]
  7150. \centering
  7151. \begin{tabular}{r|r|l|l} \hline
  7152. Caller View & Callee View & Contents & Frame \\ \hline
  7153. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  7154. 0(\key{\%rbp}) & & old \key{rbp} \\
  7155. -8(\key{\%rbp}) & & callee-saved $1$ \\
  7156. \ldots & & \ldots \\
  7157. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  7158. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  7159. \ldots & & \ldots \\
  7160. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  7161. %% & & \\
  7162. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  7163. %% & \ldots & \ldots \\
  7164. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  7165. \hline
  7166. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  7167. & 0(\key{\%rbp}) & old \key{rbp} \\
  7168. & -8(\key{\%rbp}) & callee-saved $1$ \\
  7169. & \ldots & \ldots \\
  7170. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  7171. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  7172. & \ldots & \ldots \\
  7173. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  7174. \end{tabular}
  7175. \caption{Memory layout of caller and callee frames.}
  7176. \label{fig:call-frames}
  7177. \end{figure}
  7178. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  7179. %% local variables and for storing the values of callee-saved registers
  7180. %% (we shall refer to all of these collectively as ``locals''), and that
  7181. %% at the beginning of a function we move the stack pointer \code{rsp}
  7182. %% down to make room for them.
  7183. %% We recommend storing the local variables
  7184. %% first and then the callee-saved registers, so that the local variables
  7185. %% can be accessed using \code{rbp} the same as before the addition of
  7186. %% functions.
  7187. %% To make additional room for passing arguments, we shall
  7188. %% move the stack pointer even further down. We count how many stack
  7189. %% arguments are needed for each function call that occurs inside the
  7190. %% body of the function and find their maximum. Adding this number to the
  7191. %% number of locals gives us how much the \code{rsp} should be moved at
  7192. %% the beginning of the function. In preparation for a function call, we
  7193. %% offset from \code{rsp} to set up the stack arguments. We put the first
  7194. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  7195. %% so on.
  7196. %% Upon calling the function, the stack arguments are retrieved by the
  7197. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  7198. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  7199. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  7200. %% the layout of the caller and callee frames. Notice how important it is
  7201. %% that we correctly compute the maximum number of arguments needed for
  7202. %% function calls; if that number is too small then the arguments and
  7203. %% local variables will smash into each other!
  7204. \subsection{Efficient Tail Calls}
  7205. \label{sec:tail-call}
  7206. In general, the amount of stack space used by a program is determined
  7207. by the longest chain of nested function calls. That is, if function
  7208. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  7209. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  7210. $n$ can grow quite large in the case of recursive or mutually
  7211. recursive functions. However, in some cases we can arrange to use only
  7212. constant space, i.e. $O(1)$, instead of $O(n)$.
  7213. If a function call is the last action in a function body, then that
  7214. call is said to be a \emph{tail call}\index{tail call}.
  7215. For example, in the following
  7216. program, the recursive call to \code{tail-sum} is a tail call.
  7217. \begin{center}
  7218. \begin{lstlisting}
  7219. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  7220. (if (eq? n 0)
  7221. r
  7222. (tail-sum (- n 1) (+ n r))))
  7223. (+ (tail-sum 5 0) 27)
  7224. \end{lstlisting}
  7225. \end{center}
  7226. At a tail call, the frame of the caller is no longer needed, so we
  7227. can pop the caller's frame before making the tail call. With this
  7228. approach, a recursive function that only makes tail calls will only
  7229. use $O(1)$ stack space. Functional languages like Racket typically
  7230. rely heavily on recursive functions, so they typically guarantee that
  7231. all tail calls will be optimized in this way.
  7232. \index{frame}
  7233. However, some care is needed with regards to argument passing in tail
  7234. calls. As mentioned above, for arguments beyond the sixth, the
  7235. convention is to use space in the caller's frame for passing
  7236. arguments. But for a tail call we pop the caller's frame and can no
  7237. longer use it. Another alternative is to use space in the callee's
  7238. frame for passing arguments. However, this option is also problematic
  7239. because the caller and callee's frame overlap in memory. As we begin
  7240. to copy the arguments from their sources in the caller's frame, the
  7241. target locations in the callee's frame might overlap with the sources
  7242. for later arguments! We solve this problem by not using the stack for
  7243. passing more than six arguments but instead using the heap, as we
  7244. describe in the Section~\ref{sec:limit-functions-r4}.
  7245. As mentioned above, for a tail call we pop the caller's frame prior to
  7246. making the tail call. The instructions for popping a frame are the
  7247. instructions that we usually place in the conclusion of a
  7248. function. Thus, we also need to place such code immediately before
  7249. each tail call. These instructions include restoring the callee-saved
  7250. registers, so it is good that the argument passing registers are all
  7251. caller-saved registers.
  7252. One last note regarding which instruction to use to make the tail
  7253. call. When the callee is finished, it should not return to the current
  7254. function, but it should return to the function that called the current
  7255. one. Thus, the return address that is already on the stack is the
  7256. right one, and we should not use \key{callq} to make the tail call, as
  7257. that would unnecessarily overwrite the return address. Instead we can
  7258. simply use the \key{jmp} instruction. Like the indirect function call,
  7259. we write an \emph{indirect jump}\index{indirect jump} with a register
  7260. prefixed with an asterisk. We recommend using \code{rax} to hold the
  7261. jump target because the preceding conclusion overwrites just about
  7262. everything else.
  7263. \begin{lstlisting}
  7264. jmp *%rax
  7265. \end{lstlisting}
  7266. \section{Shrink \LangFun{}}
  7267. \label{sec:shrink-r4}
  7268. The \code{shrink} pass performs a minor modification to ease the
  7269. later passes. This pass introduces an explicit \code{main} function
  7270. and changes the top \code{ProgramDefsExp} form to
  7271. \code{ProgramDefs} as follows.
  7272. \begin{lstlisting}
  7273. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  7274. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  7275. \end{lstlisting}
  7276. where $\itm{mainDef}$ is
  7277. \begin{lstlisting}
  7278. (Def 'main '() 'Integer '() |$\Exp'$|)
  7279. \end{lstlisting}
  7280. \section{Reveal Functions and the \LangFunRef{} language}
  7281. \label{sec:reveal-functions-r4}
  7282. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  7283. respect: it conflates the use of function names and local
  7284. variables. This is a problem because we need to compile the use of a
  7285. function name differently than the use of a local variable; we need to
  7286. use \code{leaq} to convert the function name (a label in x86) to an
  7287. address in a register. Thus, it is a good idea to create a new pass
  7288. that changes function references from just a symbol $f$ to
  7289. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  7290. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  7291. The concrete syntax for a function reference is $\CFUNREF{f}$.
  7292. \begin{figure}[tp]
  7293. \centering
  7294. \fbox{
  7295. \begin{minipage}{0.96\textwidth}
  7296. \[
  7297. \begin{array}{lcl}
  7298. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  7299. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7300. \LangFunRef{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  7301. \end{array}
  7302. \]
  7303. \end{minipage}
  7304. }
  7305. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  7306. (Figure~\ref{fig:Rfun-syntax}).}
  7307. \label{fig:f1-syntax}
  7308. \end{figure}
  7309. %% Distinguishing between calls in tail position and non-tail position
  7310. %% requires the pass to have some notion of context. We recommend using
  7311. %% two mutually recursive functions, one for processing expressions in
  7312. %% tail position and another for the rest.
  7313. Placing this pass after \code{uniquify} will make sure that there are
  7314. no local variables and functions that share the same name. On the
  7315. other hand, \code{reveal-functions} needs to come before the
  7316. \code{explicate-control} pass because that pass helps us compile
  7317. \code{FunRef} forms into assignment statements.
  7318. \section{Limit Functions}
  7319. \label{sec:limit-functions-r4}
  7320. Recall that we wish to limit the number of function parameters to six
  7321. so that we do not need to use the stack for argument passing, which
  7322. makes it easier to implement efficient tail calls. However, because
  7323. the input language \LangFun{} supports arbitrary numbers of function
  7324. arguments, we have some work to do!
  7325. This pass transforms functions and function calls that involve more
  7326. than six arguments to pass the first five arguments as usual, but it
  7327. packs the rest of the arguments into a vector and passes it as the
  7328. sixth argument.
  7329. Each function definition with too many parameters is transformed as
  7330. follows.
  7331. \begin{lstlisting}
  7332. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  7333. |$\Rightarrow$|
  7334. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  7335. \end{lstlisting}
  7336. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  7337. the occurrences of the later parameters with vector references.
  7338. \begin{lstlisting}
  7339. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  7340. \end{lstlisting}
  7341. For function calls with too many arguments, the \code{limit-functions}
  7342. pass transforms them in the following way.
  7343. \begin{tabular}{lll}
  7344. \begin{minipage}{0.2\textwidth}
  7345. \begin{lstlisting}
  7346. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  7347. \end{lstlisting}
  7348. \end{minipage}
  7349. &
  7350. $\Rightarrow$
  7351. &
  7352. \begin{minipage}{0.4\textwidth}
  7353. \begin{lstlisting}
  7354. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  7355. \end{lstlisting}
  7356. \end{minipage}
  7357. \end{tabular}
  7358. \section{Remove Complex Operands}
  7359. \label{sec:rco-r4}
  7360. The primary decisions to make for this pass is whether to classify
  7361. \code{FunRef} and \code{Apply} as either atomic or complex
  7362. expressions. Recall that a simple expression will eventually end up as
  7363. just an immediate argument of an x86 instruction. Function
  7364. application will be translated to a sequence of instructions, so
  7365. \code{Apply} must be classified as complex expression.
  7366. On the other hand, the arguments of \code{Apply} should be
  7367. atomic expressions.
  7368. %
  7369. Regarding \code{FunRef}, as discussed above, the function label needs
  7370. to be converted to an address using the \code{leaq} instruction. Thus,
  7371. even though \code{FunRef} seems rather simple, it needs to be
  7372. classified as a complex expression so that we generate an assignment
  7373. statement with a left-hand side that can serve as the target of the
  7374. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  7375. output language \LangFunANF{} of this pass.
  7376. \begin{figure}[tp]
  7377. \centering
  7378. \fbox{
  7379. \begin{minipage}{0.96\textwidth}
  7380. \small
  7381. \[
  7382. \begin{array}{rcl}
  7383. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  7384. \mid \VOID{} } \\
  7385. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  7386. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  7387. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7388. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7389. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  7390. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  7391. \mid \LP\key{GlobalValue}~\Var\RP }\\
  7392. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  7393. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7394. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  7395. \end{array}
  7396. \]
  7397. \end{minipage}
  7398. }
  7399. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  7400. \label{fig:Rfun-anf-syntax}
  7401. \end{figure}
  7402. \section{Explicate Control and the \LangCFun{} language}
  7403. \label{sec:explicate-control-r4}
  7404. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  7405. output of \key{explicate-control}. (The concrete syntax is given in
  7406. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  7407. functions for assignment and tail contexts should be updated with
  7408. cases for \code{Apply} and \code{FunRef} and the function for
  7409. predicate context should be updated for \code{Apply} but not
  7410. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  7411. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  7412. tail position \code{Apply} becomes \code{TailCall}. We recommend
  7413. defining a new auxiliary function for processing function definitions.
  7414. This code is similar to the case for \code{Program} in \LangVec{}. The
  7415. top-level \code{explicate-control} function that handles the
  7416. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  7417. all the function definitions.
  7418. \begin{figure}[tp]
  7419. \fbox{
  7420. \begin{minipage}{0.96\textwidth}
  7421. \small
  7422. \[
  7423. \begin{array}{lcl}
  7424. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7425. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7426. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7427. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7428. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7429. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  7430. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  7431. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  7432. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  7433. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  7434. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7435. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7436. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7437. \mid \GOTO{\itm{label}} } \\
  7438. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7439. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  7440. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  7441. \LangCFun{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7442. \end{array}
  7443. \]
  7444. \end{minipage}
  7445. }
  7446. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  7447. \label{fig:c3-syntax}
  7448. \end{figure}
  7449. \section{Select Instructions and the \LangXIndCall{} Language}
  7450. \label{sec:select-r4}
  7451. \index{instruction selection}
  7452. The output of select instructions is a program in the \LangXIndCall{}
  7453. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  7454. \index{x86}
  7455. \begin{figure}[tp]
  7456. \fbox{
  7457. \begin{minipage}{0.96\textwidth}
  7458. \small
  7459. \[
  7460. \begin{array}{lcl}
  7461. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  7462. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  7463. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  7464. \Instr &::=& \ldots
  7465. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  7466. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  7467. \Block &::= & \Instr\ldots \\
  7468. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  7469. \LangXIndCall{} &::= & \Def\ldots
  7470. \end{array}
  7471. \]
  7472. \end{minipage}
  7473. }
  7474. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  7475. \label{fig:x86-3-concrete}
  7476. \end{figure}
  7477. \begin{figure}[tp]
  7478. \fbox{
  7479. \begin{minipage}{0.96\textwidth}
  7480. \small
  7481. \[
  7482. \begin{array}{lcl}
  7483. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7484. \mid \BYTEREG{\Reg} } \\
  7485. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  7486. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  7487. \mid \TAILJMP{\Arg}{\itm{int}}\\
  7488. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  7489. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  7490. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  7491. \LangXIndCall{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7492. \end{array}
  7493. \]
  7494. \end{minipage}
  7495. }
  7496. \caption{The abstract syntax of \LangXIndCall{} (extends
  7497. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  7498. \label{fig:x86-3}
  7499. \end{figure}
  7500. An assignment of a function reference to a variable becomes a
  7501. load-effective-address instruction as follows: \\
  7502. \begin{tabular}{lcl}
  7503. \begin{minipage}{0.35\textwidth}
  7504. \begin{lstlisting}
  7505. |$\itm{lhs}$| = (fun-ref |$f$|);
  7506. \end{lstlisting}
  7507. \end{minipage}
  7508. &
  7509. $\Rightarrow$\qquad\qquad
  7510. &
  7511. \begin{minipage}{0.3\textwidth}
  7512. \begin{lstlisting}
  7513. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  7514. \end{lstlisting}
  7515. \end{minipage}
  7516. \end{tabular} \\
  7517. Regarding function definitions, we need to remove the parameters and
  7518. instead perform parameter passing using the conventions discussed in
  7519. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  7520. registers. We recommend turning the parameters into local variables
  7521. and generating instructions at the beginning of the function to move
  7522. from the argument passing registers to these local variables.
  7523. \begin{lstlisting}
  7524. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  7525. |$\Rightarrow$|
  7526. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  7527. \end{lstlisting}
  7528. The $G'$ control-flow graph is the same as $G$ except that the
  7529. \code{start} block is modified to add the instructions for moving from
  7530. the argument registers to the parameter variables. So the \code{start}
  7531. block of $G$ shown on the left is changed to the code on the right.
  7532. \begin{center}
  7533. \begin{minipage}{0.3\textwidth}
  7534. \begin{lstlisting}
  7535. start:
  7536. |$\itm{instr}_1$|
  7537. |$\vdots$|
  7538. |$\itm{instr}_n$|
  7539. \end{lstlisting}
  7540. \end{minipage}
  7541. $\Rightarrow$
  7542. \begin{minipage}{0.3\textwidth}
  7543. \begin{lstlisting}
  7544. start:
  7545. movq %rdi, |$x_1$|
  7546. movq %rsi, |$x_2$|
  7547. |$\vdots$|
  7548. |$\itm{instr}_1$|
  7549. |$\vdots$|
  7550. |$\itm{instr}_n$|
  7551. \end{lstlisting}
  7552. \end{minipage}
  7553. \end{center}
  7554. By changing the parameters to local variables, we are giving the
  7555. register allocator control over which registers or stack locations to
  7556. use for them. If you implemented the move-biasing challenge
  7557. (Section~\ref{sec:move-biasing}), the register allocator will try to
  7558. assign the parameter variables to the corresponding argument register,
  7559. in which case the \code{patch-instructions} pass will remove the
  7560. \code{movq} instruction. This happens in the example translation in
  7561. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7562. the \code{add} function.
  7563. %
  7564. Also, note that the register allocator will perform liveness analysis
  7565. on this sequence of move instructions and build the interference
  7566. graph. So, for example, $x_1$ will be marked as interfering with
  7567. \code{rsi} and that will prevent the assignment of $x_1$ to
  7568. \code{rsi}, which is good, because that would overwrite the argument
  7569. that needs to move into $x_2$.
  7570. Next, consider the compilation of function calls. In the mirror image
  7571. of handling the parameters of function definitions, the arguments need
  7572. to be moved to the argument passing registers. The function call
  7573. itself is performed with an indirect function call. The return value
  7574. from the function is stored in \code{rax}, so it needs to be moved
  7575. into the \itm{lhs}.
  7576. \begin{lstlisting}
  7577. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7578. |$\Rightarrow$|
  7579. movq |$\itm{arg}_1$|, %rdi
  7580. movq |$\itm{arg}_2$|, %rsi
  7581. |$\vdots$|
  7582. callq *|\itm{fun}|
  7583. movq %rax, |\itm{lhs}|
  7584. \end{lstlisting}
  7585. The \code{IndirectCallq} AST node includes an integer for the arity of
  7586. the function, i.e., the number of parameters. That information is
  7587. useful in the \code{uncover-live} pass for determining which
  7588. argument-passing registers are potentially read during the call.
  7589. For tail calls, the parameter passing is the same as non-tail calls:
  7590. generate instructions to move the arguments into to the argument
  7591. passing registers. After that we need to pop the frame from the
  7592. procedure call stack. However, we do not yet know how big the frame
  7593. is; that gets determined during register allocation. So instead of
  7594. generating those instructions here, we invent a new instruction that
  7595. means ``pop the frame and then do an indirect jump'', which we name
  7596. \code{TailJmp}. The abstract syntax for this instruction includes an
  7597. argument that specifies where to jump and an integer that represents
  7598. the arity of the function being called.
  7599. Recall that in Section~\ref{sec:explicate-control-Rvar} we recommended
  7600. using the label \code{start} for the initial block of a program, and
  7601. in Section~\ref{sec:select-Rvar} we recommended labeling the conclusion
  7602. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7603. can be compiled to an assignment to \code{rax} followed by a jump to
  7604. \code{conclusion}. With the addition of function definitions, we will
  7605. have a starting block and conclusion for each function, but their
  7606. labels need to be unique. We recommend prepending the function's name
  7607. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7608. labels. (Alternatively, one could \code{gensym} labels for the start
  7609. and conclusion and store them in the $\itm{info}$ field of the
  7610. function definition.)
  7611. \section{Register Allocation}
  7612. \label{sec:register-allocation-r4}
  7613. \subsection{Liveness Analysis}
  7614. \label{sec:liveness-analysis-r4}
  7615. \index{liveness analysis}
  7616. %% The rest of the passes need only minor modifications to handle the new
  7617. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7618. %% \code{leaq}.
  7619. The \code{IndirectCallq} instruction should be treated like
  7620. \code{Callq} regarding its written locations $W$, in that they should
  7621. include all the caller-saved registers. Recall that the reason for
  7622. that is to force call-live variables to be assigned to callee-saved
  7623. registers or to be spilled to the stack.
  7624. Regarding the set of read locations $R$ the arity field of
  7625. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  7626. argument-passing registers should be considered as read by those
  7627. instructions.
  7628. \subsection{Build Interference Graph}
  7629. \label{sec:build-interference-r4}
  7630. With the addition of function definitions, we compute an interference
  7631. graph for each function (not just one for the whole program).
  7632. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7633. spill vector-typed variables that are live during a call to the
  7634. \code{collect}. With the addition of functions to our language, we
  7635. need to revisit this issue. Many functions perform allocation and
  7636. therefore have calls to the collector inside of them. Thus, we should
  7637. not only spill a vector-typed variable when it is live during a call
  7638. to \code{collect}, but we should spill the variable if it is live
  7639. during any function call. Thus, in the \code{build-interference} pass,
  7640. we recommend adding interference edges between call-live vector-typed
  7641. variables and the callee-saved registers (in addition to the usual
  7642. addition of edges between call-live variables and the caller-saved
  7643. registers).
  7644. \subsection{Allocate Registers}
  7645. The primary change to the \code{allocate-registers} pass is adding an
  7646. auxiliary function for handling definitions (the \Def{} non-terminal
  7647. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  7648. logic is the same as described in
  7649. Chapter~\ref{ch:register-allocation-Rvar}, except now register
  7650. allocation is performed many times, once for each function definition,
  7651. instead of just once for the whole program.
  7652. \section{Patch Instructions}
  7653. In \code{patch-instructions}, you should deal with the x86
  7654. idiosyncrasy that the destination argument of \code{leaq} must be a
  7655. register. Additionally, you should ensure that the argument of
  7656. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7657. code generation more convenient, because we trample many registers
  7658. before the tail call (as explained in the next section).
  7659. \section{Print x86}
  7660. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7661. \code{IndirectCallq} are straightforward: output their concrete
  7662. syntax.
  7663. \begin{lstlisting}
  7664. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7665. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7666. \end{lstlisting}
  7667. The \code{TailJmp} node requires a bit work. A straightforward
  7668. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7669. before the jump we need to pop the current frame. This sequence of
  7670. instructions is the same as the code for the conclusion of a function,
  7671. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7672. Regarding function definitions, you will need to generate a prelude
  7673. and conclusion for each one. This code is similar to the prelude and
  7674. conclusion that you generated for the \code{main} function in
  7675. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  7676. should carry out the following steps.
  7677. \begin{enumerate}
  7678. \item Start with \code{.global} and \code{.align} directives followed
  7679. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  7680. example.)
  7681. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  7682. pointer.
  7683. \item Push to the stack all of the callee-saved registers that were
  7684. used for register allocation.
  7685. \item Move the stack pointer \code{rsp} down by the size of the stack
  7686. frame for this function, which depends on the number of regular
  7687. spills. (Aligned to 16 bytes.)
  7688. \item Move the root stack pointer \code{r15} up by the size of the
  7689. root-stack frame for this function, which depends on the number of
  7690. spilled vectors. \label{root-stack-init}
  7691. \item Initialize to zero all of the entries in the root-stack frame.
  7692. \item Jump to the start block.
  7693. \end{enumerate}
  7694. The prelude of the \code{main} function has one additional task: call
  7695. the \code{initialize} function to set up the garbage collector and
  7696. move the value of the global \code{rootstack\_begin} in
  7697. \code{r15}. This should happen before step \ref{root-stack-init}
  7698. above, which depends on \code{r15}.
  7699. The conclusion of every function should do the following.
  7700. \begin{enumerate}
  7701. \item Move the stack pointer back up by the size of the stack frame
  7702. for this function.
  7703. \item Restore the callee-saved registers by popping them from the
  7704. stack.
  7705. \item Move the root stack pointer back down by the size of the
  7706. root-stack frame for this function.
  7707. \item Restore \code{rbp} by popping it from the stack.
  7708. \item Return to the caller with the \code{retq} instruction.
  7709. \end{enumerate}
  7710. \begin{exercise}\normalfont
  7711. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  7712. Create 5 new programs that use functions, including examples that pass
  7713. functions and return functions from other functions, recursive
  7714. functions, functions that create vectors, and functions that make tail
  7715. calls. Test your compiler on these new programs and all of your
  7716. previously created test programs.
  7717. \end{exercise}
  7718. \begin{figure}[tbp]
  7719. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7720. \node (Rfun) at (0,2) {\large \LangFun{}};
  7721. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  7722. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  7723. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  7724. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  7725. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  7726. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  7727. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  7728. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  7729. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  7730. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  7731. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  7732. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  7733. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  7734. \path[->,bend left=15] (Rfun) edge [above] node
  7735. {\ttfamily\footnotesize shrink} (Rfun-1);
  7736. \path[->,bend left=15] (Rfun-1) edge [above] node
  7737. {\ttfamily\footnotesize uniquify} (Rfun-2);
  7738. \path[->,bend left=15] (Rfun-2) edge [right] node
  7739. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  7740. \path[->,bend left=15] (F1-1) edge [below] node
  7741. {\ttfamily\footnotesize limit-functions} (F1-2);
  7742. \path[->,bend right=15] (F1-2) edge [above] node
  7743. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7744. \path[->,bend right=15] (F1-3) edge [above] node
  7745. {\ttfamily\footnotesize remove-complex.} (F1-4);
  7746. \path[->,bend left=15] (F1-4) edge [right] node
  7747. {\ttfamily\footnotesize explicate-control} (C3-2);
  7748. \path[->,bend right=15] (C3-2) edge [left] node
  7749. {\ttfamily\footnotesize select-instr.} (x86-2);
  7750. \path[->,bend left=15] (x86-2) edge [left] node
  7751. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7752. \path[->,bend right=15] (x86-2-1) edge [below] node
  7753. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7754. \path[->,bend right=15] (x86-2-2) edge [left] node
  7755. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7756. \path[->,bend left=15] (x86-3) edge [above] node
  7757. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7758. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7759. \end{tikzpicture}
  7760. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  7761. \label{fig:Rfun-passes}
  7762. \end{figure}
  7763. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  7764. compiling \LangFun{} to x86.
  7765. \section{An Example Translation}
  7766. \label{sec:functions-example}
  7767. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7768. function in \LangFun{} to x86. The figure also includes the results of the
  7769. \code{explicate-control} and \code{select-instructions} passes.
  7770. \begin{figure}[htbp]
  7771. \begin{tabular}{ll}
  7772. \begin{minipage}{0.5\textwidth}
  7773. % s3_2.rkt
  7774. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7775. (define (add [x : Integer] [y : Integer])
  7776. : Integer
  7777. (+ x y))
  7778. (add 40 2)
  7779. \end{lstlisting}
  7780. $\Downarrow$
  7781. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7782. (define (add86 [x87 : Integer]
  7783. [y88 : Integer]) : Integer
  7784. add86start:
  7785. return (+ x87 y88);
  7786. )
  7787. (define (main) : Integer ()
  7788. mainstart:
  7789. tmp89 = (fun-ref add86);
  7790. (tail-call tmp89 40 2)
  7791. )
  7792. \end{lstlisting}
  7793. \end{minipage}
  7794. &
  7795. $\Rightarrow$
  7796. \begin{minipage}{0.5\textwidth}
  7797. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7798. (define (add86) : Integer
  7799. add86start:
  7800. movq %rdi, x87
  7801. movq %rsi, y88
  7802. movq x87, %rax
  7803. addq y88, %rax
  7804. jmp add11389conclusion
  7805. )
  7806. (define (main) : Integer
  7807. mainstart:
  7808. leaq (fun-ref add86), tmp89
  7809. movq $40, %rdi
  7810. movq $2, %rsi
  7811. tail-jmp tmp89
  7812. )
  7813. \end{lstlisting}
  7814. $\Downarrow$
  7815. \end{minipage}
  7816. \end{tabular}
  7817. \begin{tabular}{ll}
  7818. \begin{minipage}{0.3\textwidth}
  7819. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7820. .globl add86
  7821. .align 16
  7822. add86:
  7823. pushq %rbp
  7824. movq %rsp, %rbp
  7825. jmp add86start
  7826. add86start:
  7827. movq %rdi, %rax
  7828. addq %rsi, %rax
  7829. jmp add86conclusion
  7830. add86conclusion:
  7831. popq %rbp
  7832. retq
  7833. \end{lstlisting}
  7834. \end{minipage}
  7835. &
  7836. \begin{minipage}{0.5\textwidth}
  7837. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7838. .globl main
  7839. .align 16
  7840. main:
  7841. pushq %rbp
  7842. movq %rsp, %rbp
  7843. movq $16384, %rdi
  7844. movq $16384, %rsi
  7845. callq initialize
  7846. movq rootstack_begin(%rip), %r15
  7847. jmp mainstart
  7848. mainstart:
  7849. leaq add86(%rip), %rcx
  7850. movq $40, %rdi
  7851. movq $2, %rsi
  7852. movq %rcx, %rax
  7853. popq %rbp
  7854. jmp *%rax
  7855. mainconclusion:
  7856. popq %rbp
  7857. retq
  7858. \end{lstlisting}
  7859. \end{minipage}
  7860. \end{tabular}
  7861. \caption{Example compilation of a simple function to x86.}
  7862. \label{fig:add-fun}
  7863. \end{figure}
  7864. % Challenge idea: inlining! (simple version)
  7865. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7866. \chapter{Lexically Scoped Functions}
  7867. \label{ch:Rlam}
  7868. \index{lambda}
  7869. \index{lexical scoping}
  7870. This chapter studies lexically scoped functions as they appear in
  7871. functional languages such as Racket. By lexical scoping we mean that a
  7872. function's body may refer to variables whose binding site is outside
  7873. of the function, in an enclosing scope.
  7874. %
  7875. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7876. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  7877. \key{lambda} form. The body of the \key{lambda}, refers to three
  7878. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7879. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7880. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7881. parameter of function \code{f}. The \key{lambda} is returned from the
  7882. function \code{f}. The main expression of the program includes two
  7883. calls to \code{f} with different arguments for \code{x}, first
  7884. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7885. to variables \code{g} and \code{h}. Even though these two functions
  7886. were created by the same \code{lambda}, they are really different
  7887. functions because they use different values for \code{x}. Applying
  7888. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7889. \code{15} produces \code{22}. The result of this program is \code{42}.
  7890. \begin{figure}[btp]
  7891. % s4_6.rkt
  7892. \begin{lstlisting}
  7893. (define (f [x : Integer]) : (Integer -> Integer)
  7894. (let ([y 4])
  7895. (lambda: ([z : Integer]) : Integer
  7896. (+ x (+ y z)))))
  7897. (let ([g (f 5)])
  7898. (let ([h (f 3)])
  7899. (+ (g 11) (h 15))))
  7900. \end{lstlisting}
  7901. \caption{Example of a lexically scoped function.}
  7902. \label{fig:lexical-scoping}
  7903. \end{figure}
  7904. The approach that we take for implementing lexically scoped
  7905. functions is to compile them into top-level function definitions,
  7906. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  7907. provide special treatment for variable occurrences such as \code{x}
  7908. and \code{y} in the body of the \code{lambda} of
  7909. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  7910. refer to variables defined outside of it. To identify such variable
  7911. occurrences, we review the standard notion of free variable.
  7912. \begin{definition}
  7913. A variable is \emph{free in expression} $e$ if the variable occurs
  7914. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7915. variable}
  7916. \end{definition}
  7917. For example, in the expression \code{(+ x (+ y z))} the variables
  7918. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7919. only \code{x} and \code{y} are free in the following expression
  7920. because \code{z} is bound by the \code{lambda}.
  7921. \begin{lstlisting}
  7922. (lambda: ([z : Integer]) : Integer
  7923. (+ x (+ y z)))
  7924. \end{lstlisting}
  7925. So the free variables of a \code{lambda} are the ones that will need
  7926. special treatment. We need to arrange for some way to transport, at
  7927. runtime, the values of those variables from the point where the
  7928. \code{lambda} was created to the point where the \code{lambda} is
  7929. applied. An efficient solution to the problem, due to
  7930. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7931. free variables together with the function pointer for the lambda's
  7932. code, an arrangement called a \emph{flat closure} (which we shorten to
  7933. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7934. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  7935. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  7936. pointers. The function pointer resides at index $0$ and the
  7937. values for the free variables will fill in the rest of the vector.
  7938. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7939. how closures work. It's a three-step dance. The program first calls
  7940. function \code{f}, which creates a closure for the \code{lambda}. The
  7941. closure is a vector whose first element is a pointer to the top-level
  7942. function that we will generate for the \code{lambda}, the second
  7943. element is the value of \code{x}, which is \code{5}, and the third
  7944. element is \code{4}, the value of \code{y}. The closure does not
  7945. contain an element for \code{z} because \code{z} is not a free
  7946. variable of the \code{lambda}. Creating the closure is step 1 of the
  7947. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7948. shown in Figure~\ref{fig:closures}.
  7949. %
  7950. The second call to \code{f} creates another closure, this time with
  7951. \code{3} in the second slot (for \code{x}). This closure is also
  7952. returned from \code{f} but bound to \code{h}, which is also shown in
  7953. Figure~\ref{fig:closures}.
  7954. \begin{figure}[tbp]
  7955. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7956. \caption{Example closure representation for the \key{lambda}'s
  7957. in Figure~\ref{fig:lexical-scoping}.}
  7958. \label{fig:closures}
  7959. \end{figure}
  7960. Continuing with the example, consider the application of \code{g} to
  7961. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7962. obtain the function pointer in the first element of the closure and
  7963. call it, passing in the closure itself and then the regular arguments,
  7964. in this case \code{11}. This technique for applying a closure is step
  7965. 2 of the dance.
  7966. %
  7967. But doesn't this \code{lambda} only take 1 argument, for parameter
  7968. \code{z}? The third and final step of the dance is generating a
  7969. top-level function for a \code{lambda}. We add an additional
  7970. parameter for the closure and we insert a \code{let} at the beginning
  7971. of the function for each free variable, to bind those variables to the
  7972. appropriate elements from the closure parameter.
  7973. %
  7974. This three-step dance is known as \emph{closure conversion}. We
  7975. discuss the details of closure conversion in
  7976. Section~\ref{sec:closure-conversion} and the code generated from the
  7977. example in Section~\ref{sec:example-lambda}. But first we define the
  7978. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  7979. \section{The \LangLam{} Language}
  7980. \label{sec:r5}
  7981. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  7982. functions and lexical scoping, is defined in
  7983. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  7984. the \key{lambda} form to the grammar for \LangFun{}, which already has
  7985. syntax for function application.
  7986. \begin{figure}[tp]
  7987. \centering
  7988. \fbox{
  7989. \begin{minipage}{0.96\textwidth}
  7990. \small
  7991. \[
  7992. \begin{array}{lcl}
  7993. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7994. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7995. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7996. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7997. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7998. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7999. &\mid& \gray{\key{\#t} \mid \key{\#f}
  8000. \mid (\key{and}\;\Exp\;\Exp)
  8001. \mid (\key{or}\;\Exp\;\Exp)
  8002. \mid (\key{not}\;\Exp) } \\
  8003. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  8004. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  8005. (\key{vector-ref}\;\Exp\;\Int)} \\
  8006. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  8007. \mid (\Exp \; \Exp\ldots) } \\
  8008. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  8009. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  8010. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  8011. \LangLam{} &::=& \gray{\Def\ldots \; \Exp}
  8012. \end{array}
  8013. \]
  8014. \end{minipage}
  8015. }
  8016. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  8017. with \key{lambda}.}
  8018. \label{fig:Rlam-concrete-syntax}
  8019. \end{figure}
  8020. \begin{figure}[tp]
  8021. \centering
  8022. \fbox{
  8023. \begin{minipage}{0.96\textwidth}
  8024. \small
  8025. \[
  8026. \begin{array}{lcl}
  8027. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  8028. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  8029. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8030. &\mid& \gray{ \BOOL{\itm{bool}}
  8031. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  8032. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  8033. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  8034. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  8035. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8036. \LangLam{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8037. \end{array}
  8038. \]
  8039. \end{minipage}
  8040. }
  8041. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  8042. \label{fig:Rlam-syntax}
  8043. \end{figure}
  8044. \index{interpreter}
  8045. \label{sec:interp-Rlambda}
  8046. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  8047. \LangLam{}. The case for \key{lambda} saves the current environment
  8048. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  8049. the environment from the \key{lambda}, the \code{lam-env}, when
  8050. interpreting the body of the \key{lambda}. The \code{lam-env}
  8051. environment is extended with the mapping of parameters to argument
  8052. values.
  8053. \begin{figure}[tbp]
  8054. \begin{lstlisting}
  8055. (define interp-Rlambda-class
  8056. (class interp-Rfun-class
  8057. (super-new)
  8058. (define/override (interp-op op)
  8059. (match op
  8060. ['procedure-arity
  8061. (lambda (v)
  8062. (match v
  8063. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  8064. [else (error 'interp-op "expected a function, not ~a" v)]))]
  8065. [else (super interp-op op)]))
  8066. (define/override ((interp-exp env) e)
  8067. (define recur (interp-exp env))
  8068. (match e
  8069. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  8070. `(function ,xs ,body ,env)]
  8071. [else ((super interp-exp env) e)]))
  8072. ))
  8073. (define (interp-Rlambda p)
  8074. (send (new interp-Rlambda-class) interp-program p))
  8075. \end{lstlisting}
  8076. \caption{Interpreter for \LangLam{}.}
  8077. \label{fig:interp-Rlambda}
  8078. \end{figure}
  8079. \label{sec:type-check-r5}
  8080. \index{type checking}
  8081. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  8082. \key{lambda} form. The body of the \key{lambda} is checked in an
  8083. environment that includes the current environment (because it is
  8084. lexically scoped) and also includes the \key{lambda}'s parameters. We
  8085. require the body's type to match the declared return type.
  8086. \begin{figure}[tbp]
  8087. \begin{lstlisting}
  8088. (define (type-check-Rlambda env)
  8089. (lambda (e)
  8090. (match e
  8091. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  8092. (define-values (new-body bodyT)
  8093. ((type-check-exp (append (map cons xs Ts) env)) body))
  8094. (define ty `(,@Ts -> ,rT))
  8095. (cond
  8096. [(equal? rT bodyT)
  8097. (values (HasType (Lambda params rT new-body) ty) ty)]
  8098. [else
  8099. (error "mismatch in return type" bodyT rT)])]
  8100. ...
  8101. )))
  8102. \end{lstlisting}
  8103. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  8104. \label{fig:type-check-Rlambda}
  8105. \end{figure}
  8106. \section{Reveal Functions and the $F_2$ language}
  8107. \label{sec:reveal-functions-r5}
  8108. To support the \code{procedure-arity} operator we need to communicate
  8109. the arity of a function to the point of closure creation. We can
  8110. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  8111. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  8112. output of this pass is the language $F_2$, whose syntax is defined in
  8113. Figure~\ref{fig:f2-syntax}.
  8114. \begin{figure}[tp]
  8115. \centering
  8116. \fbox{
  8117. \begin{minipage}{0.96\textwidth}
  8118. \[
  8119. \begin{array}{lcl}
  8120. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  8121. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8122. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  8123. \end{array}
  8124. \]
  8125. \end{minipage}
  8126. }
  8127. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  8128. (Figure~\ref{fig:Rlam-syntax}).}
  8129. \label{fig:f2-syntax}
  8130. \end{figure}
  8131. \section{Closure Conversion}
  8132. \label{sec:closure-conversion}
  8133. \index{closure conversion}
  8134. The compiling of lexically-scoped functions into top-level function
  8135. definitions is accomplished in the pass \code{convert-to-closures}
  8136. that comes after \code{reveal-functions} and before
  8137. \code{limit-functions}.
  8138. As usual, we implement the pass as a recursive function over the
  8139. AST. All of the action is in the cases for \key{Lambda} and
  8140. \key{Apply}. We transform a \key{Lambda} expression into an expression
  8141. that creates a closure, that is, a vector whose first element is a
  8142. function pointer and the rest of the elements are the free variables
  8143. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  8144. using \code{vector} so that we can distinguish closures from vectors
  8145. in Section~\ref{sec:optimize-closures} and to record the arity. In
  8146. the generated code below, the \itm{name} is a unique symbol generated
  8147. to identify the function and the \itm{arity} is the number of
  8148. parameters (the length of \itm{ps}).
  8149. \begin{lstlisting}
  8150. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  8151. |$\Rightarrow$|
  8152. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  8153. \end{lstlisting}
  8154. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  8155. create a top-level function definition for each \key{Lambda}, as
  8156. shown below.\\
  8157. \begin{minipage}{0.8\textwidth}
  8158. \begin{lstlisting}
  8159. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  8160. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  8161. ...
  8162. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  8163. |\itm{body'}|)...))
  8164. \end{lstlisting}
  8165. \end{minipage}\\
  8166. The \code{clos} parameter refers to the closure. Translate the type
  8167. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  8168. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  8169. $\itm{fvts}$ are the types of the free variables in the lambda and the
  8170. underscore \code{\_} is a dummy type that we use because it is rather
  8171. difficult to give a type to the function in the closure's
  8172. type.\footnote{To give an accurate type to a closure, we would need to
  8173. add existential types to the type checker~\citep{Minamide:1996ys}.}
  8174. The dummy type is considered to be equal to any other type during type
  8175. checking. The sequence of \key{Let} forms bind the free variables to
  8176. their values obtained from the closure.
  8177. Closure conversion turns functions into vectors, so the type
  8178. annotations in the program must also be translated. We recommend
  8179. defining a auxiliary recursive function for this purpose. Function
  8180. types should be translated as follows.
  8181. \begin{lstlisting}
  8182. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  8183. |$\Rightarrow$|
  8184. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  8185. \end{lstlisting}
  8186. The above type says that the first thing in the vector is a function
  8187. pointer. The first parameter of the function pointer is a vector (a
  8188. closure) and the rest of the parameters are the ones from the original
  8189. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  8190. the closure omits the types of the free variables because 1) those
  8191. types are not available in this context and 2) we do not need them in
  8192. the code that is generated for function application.
  8193. We transform function application into code that retrieves the
  8194. function pointer from the closure and then calls the function, passing
  8195. in the closure as the first argument. We bind $e'$ to a temporary
  8196. variable to avoid code duplication.
  8197. \begin{lstlisting}
  8198. (Apply |$e$| |\itm{es}|)
  8199. |$\Rightarrow$|
  8200. (Let |\itm{tmp}| |$e'$|
  8201. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  8202. \end{lstlisting}
  8203. There is also the question of what to do with references top-level
  8204. function definitions. To maintain a uniform translation of function
  8205. application, we turn function references into closures.
  8206. \begin{tabular}{lll}
  8207. \begin{minipage}{0.3\textwidth}
  8208. \begin{lstlisting}
  8209. (FunRefArity |$f$| |$n$|)
  8210. \end{lstlisting}
  8211. \end{minipage}
  8212. &
  8213. $\Rightarrow$
  8214. &
  8215. \begin{minipage}{0.5\textwidth}
  8216. \begin{lstlisting}
  8217. (Closure |$n$| (FunRef |$f$|) '())
  8218. \end{lstlisting}
  8219. \end{minipage}
  8220. \end{tabular} \\
  8221. %
  8222. The top-level function definitions need to be updated as well to take
  8223. an extra closure parameter.
  8224. \section{An Example Translation}
  8225. \label{sec:example-lambda}
  8226. Figure~\ref{fig:lexical-functions-example} shows the result of
  8227. \code{reveal-functions} and \code{convert-to-closures} for the example
  8228. program demonstrating lexical scoping that we discussed at the
  8229. beginning of this chapter.
  8230. \begin{figure}[tbp]
  8231. \begin{minipage}{0.8\textwidth}
  8232. % tests/lambda_test_6.rkt
  8233. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8234. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  8235. (let ([y8 4])
  8236. (lambda: ([z9 : Integer]) : Integer
  8237. (+ x7 (+ y8 z9)))))
  8238. (define (main) : Integer
  8239. (let ([g0 ((fun-ref-arity f6 1) 5)])
  8240. (let ([h1 ((fun-ref-arity f6 1) 3)])
  8241. (+ (g0 11) (h1 15)))))
  8242. \end{lstlisting}
  8243. $\Rightarrow$
  8244. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8245. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  8246. (let ([y8 4])
  8247. (closure 1 (list (fun-ref lambda2) x7 y8))))
  8248. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  8249. (let ([x7 (vector-ref fvs3 1)])
  8250. (let ([y8 (vector-ref fvs3 2)])
  8251. (+ x7 (+ y8 z9)))))
  8252. (define (main) : Integer
  8253. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  8254. ((vector-ref clos5 0) clos5 5))])
  8255. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  8256. ((vector-ref clos6 0) clos6 3))])
  8257. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  8258. \end{lstlisting}
  8259. \end{minipage}
  8260. \caption{Example of closure conversion.}
  8261. \label{fig:lexical-functions-example}
  8262. \end{figure}
  8263. \begin{exercise}\normalfont
  8264. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  8265. Create 5 new programs that use \key{lambda} functions and make use of
  8266. lexical scoping. Test your compiler on these new programs and all of
  8267. your previously created test programs.
  8268. \end{exercise}
  8269. \section{Expose Allocation}
  8270. \label{sec:expose-allocation-r5}
  8271. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  8272. that allocates and initializes a vector, similar to the translation of
  8273. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  8274. The only difference is replacing the use of
  8275. \ALLOC{\itm{len}}{\itm{type}} with
  8276. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  8277. \section{Explicate Control and \LangCLam{}}
  8278. \label{sec:explicate-r5}
  8279. The output language of \code{explicate-control} is \LangCLam{} whose
  8280. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  8281. difference with respect to \LangCFun{} is the addition of the
  8282. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  8283. of \code{AllocateClosure} in the \code{explicate-control} pass is
  8284. similar to the handling of other expressions such as primitive
  8285. operators.
  8286. \begin{figure}[tp]
  8287. \fbox{
  8288. \begin{minipage}{0.96\textwidth}
  8289. \small
  8290. \[
  8291. \begin{array}{lcl}
  8292. \Exp &::= & \ldots
  8293. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  8294. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8295. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  8296. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8297. \mid \GOTO{\itm{label}} } \\
  8298. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8299. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  8300. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  8301. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  8302. \end{array}
  8303. \]
  8304. \end{minipage}
  8305. }
  8306. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  8307. \label{fig:c4-syntax}
  8308. \end{figure}
  8309. \section{Select Instructions}
  8310. \label{sec:select-instructions-Rlambda}
  8311. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  8312. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  8313. (Section~\ref{sec:select-instructions-gc}). The only difference is
  8314. that you should place the \itm{arity} in the tag that is stored at
  8315. position $0$ of the vector. Recall that in
  8316. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  8317. was not used. We store the arity in the $5$ bits starting at position
  8318. $58$.
  8319. Compile the \code{procedure-arity} operator into a sequence of
  8320. instructions that access the tag from position $0$ of the vector and
  8321. extract the $5$-bits starting at position $58$ from the tag.
  8322. \begin{figure}[p]
  8323. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8324. \node (Rfun) at (0,2) {\large \LangFun{}};
  8325. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  8326. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  8327. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8328. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8329. \node (F1-3) at (6,0) {\large $F_1$};
  8330. \node (F1-4) at (3,0) {\large $F_1$};
  8331. \node (F1-5) at (0,0) {\large $F_1$};
  8332. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8333. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8334. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8335. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8336. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8337. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8338. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8339. \path[->,bend left=15] (Rfun) edge [above] node
  8340. {\ttfamily\footnotesize shrink} (Rfun-2);
  8341. \path[->,bend left=15] (Rfun-2) edge [above] node
  8342. {\ttfamily\footnotesize uniquify} (Rfun-3);
  8343. \path[->,bend left=15] (Rfun-3) edge [right] node
  8344. {\ttfamily\footnotesize reveal-functions} (F1-1);
  8345. \path[->,bend left=15] (F1-1) edge [below] node
  8346. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  8347. \path[->,bend right=15] (F1-2) edge [above] node
  8348. {\ttfamily\footnotesize limit-fun.} (F1-3);
  8349. \path[->,bend right=15] (F1-3) edge [above] node
  8350. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  8351. \path[->,bend right=15] (F1-4) edge [above] node
  8352. {\ttfamily\footnotesize remove-complex.} (F1-5);
  8353. \path[->,bend right=15] (F1-5) edge [right] node
  8354. {\ttfamily\footnotesize explicate-control} (C3-2);
  8355. \path[->,bend left=15] (C3-2) edge [left] node
  8356. {\ttfamily\footnotesize select-instr.} (x86-2);
  8357. \path[->,bend right=15] (x86-2) edge [left] node
  8358. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8359. \path[->,bend right=15] (x86-2-1) edge [below] node
  8360. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8361. \path[->,bend right=15] (x86-2-2) edge [left] node
  8362. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8363. \path[->,bend left=15] (x86-3) edge [above] node
  8364. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8365. \path[->,bend left=15] (x86-4) edge [right] node
  8366. {\ttfamily\footnotesize print-x86} (x86-5);
  8367. \end{tikzpicture}
  8368. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  8369. functions.}
  8370. \label{fig:Rlambda-passes}
  8371. \end{figure}
  8372. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  8373. for the compilation of \LangLam{}.
  8374. \clearpage
  8375. \section{Challenge: Optimize Closures}
  8376. \label{sec:optimize-closures}
  8377. In this chapter we compiled lexically-scoped functions into a
  8378. relatively efficient representation: flat closures. However, even this
  8379. representation comes with some overhead. For example, consider the
  8380. following program with a function \code{tail-sum} that does not have
  8381. any free variables and where all the uses of \code{tail-sum} are in
  8382. applications where we know that only \code{tail-sum} is being applied
  8383. (and not any other functions).
  8384. \begin{center}
  8385. \begin{minipage}{0.95\textwidth}
  8386. \begin{lstlisting}
  8387. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  8388. (if (eq? n 0)
  8389. r
  8390. (tail-sum (- n 1) (+ n r))))
  8391. (+ (tail-sum 5 0) 27)
  8392. \end{lstlisting}
  8393. \end{minipage}
  8394. \end{center}
  8395. As described in this chapter, we uniformly apply closure conversion to
  8396. all functions, obtaining the following output for this program.
  8397. \begin{center}
  8398. \begin{minipage}{0.95\textwidth}
  8399. \begin{lstlisting}
  8400. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  8401. (if (eq? n2 0)
  8402. r3
  8403. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  8404. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  8405. (define (main) : Integer
  8406. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  8407. ((vector-ref clos6 0) clos6 5 0)) 27))
  8408. \end{lstlisting}
  8409. \end{minipage}
  8410. \end{center}
  8411. In the previous Chapter, there would be no allocation in the program
  8412. and the calls to \code{tail-sum} would be direct calls. In contrast,
  8413. the above program allocates memory for each \code{closure} and the
  8414. calls to \code{tail-sum} are indirect. These two differences incur
  8415. considerable overhead in a program such as this one, where the
  8416. allocations and indirect calls occur inside a tight loop.
  8417. One might think that this problem is trivial to solve: can't we just
  8418. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  8419. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  8420. e'_n$)} instead of treating it like a call to a closure? We would
  8421. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  8422. %
  8423. However, this problem is not so trivial because a global function may
  8424. ``escape'' and become involved in applications that also involve
  8425. closures. Consider the following example in which the application
  8426. \code{(f 41)} needs to be compiled into a closure application, because
  8427. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  8428. function might also get bound to \code{f}.
  8429. \begin{lstlisting}
  8430. (define (add1 [x : Integer]) : Integer
  8431. (+ x 1))
  8432. (let ([y (read)])
  8433. (let ([f (if (eq? (read) 0)
  8434. add1
  8435. (lambda: ([x : Integer]) : Integer (- x y)))])
  8436. (f 41)))
  8437. \end{lstlisting}
  8438. If a global function name is used in any way other than as the
  8439. operator in a direct call, then we say that the function
  8440. \emph{escapes}. If a global function does not escape, then we do not
  8441. need to perform closure conversion on the function.
  8442. \begin{exercise}\normalfont
  8443. Implement an auxiliary function for detecting which global
  8444. functions escape. Using that function, implement an improved version
  8445. of closure conversion that does not apply closure conversion to
  8446. global functions that do not escape but instead compiles them as
  8447. regular functions. Create several new test cases that check whether
  8448. you properly detect whether global functions escape or not.
  8449. \end{exercise}
  8450. So far we have reduced the overhead of calling global functions, but
  8451. it would also be nice to reduce the overhead of calling a
  8452. \code{lambda} when we can determine at compile time which
  8453. \code{lambda} will be called. We refer to such calls as \emph{known
  8454. calls}. Consider the following example in which a \code{lambda} is
  8455. bound to \code{f} and then applied.
  8456. \begin{lstlisting}
  8457. (let ([y (read)])
  8458. (let ([f (lambda: ([x : Integer]) : Integer
  8459. (+ x y))])
  8460. (f 21)))
  8461. \end{lstlisting}
  8462. Closure conversion compiles \code{(f 21)} into an indirect call:
  8463. \begin{lstlisting}
  8464. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  8465. (let ([y2 (vector-ref fvs6 1)])
  8466. (+ x3 y2)))
  8467. (define (main) : Integer
  8468. (let ([y2 (read)])
  8469. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8470. ((vector-ref f4 0) f4 21))))
  8471. \end{lstlisting}
  8472. but we can instead compile the application \code{(f 21)} into a direct call
  8473. to \code{lambda5}:
  8474. \begin{lstlisting}
  8475. (define (main) : Integer
  8476. (let ([y2 (read)])
  8477. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8478. ((fun-ref lambda5) f4 21))))
  8479. \end{lstlisting}
  8480. The problem of determining which lambda will be called from a
  8481. particular application is quite challenging in general and the topic
  8482. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  8483. following exercise we recommend that you compile an application to a
  8484. direct call when the operator is a variable and the variable is
  8485. \code{let}-bound to a closure. This can be accomplished by maintaining
  8486. an environment mapping \code{let}-bound variables to function names.
  8487. Extend the environment whenever you encounter a closure on the
  8488. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  8489. to the name of the global function for the closure. This pass should
  8490. come after closure conversion.
  8491. \begin{exercise}\normalfont
  8492. Implement a compiler pass, named \code{optimize-known-calls}, that
  8493. compiles known calls into direct calls. Verify that your compiler is
  8494. successful in this regard on several example programs.
  8495. \end{exercise}
  8496. These exercises only scratches the surface of optimizing of
  8497. closures. A good next step for the interested reader is to look at the
  8498. work of \citet{Keep:2012ab}.
  8499. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8500. \chapter{Dynamic Typing}
  8501. \label{ch:Rdyn}
  8502. \index{dynamic typing}
  8503. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  8504. typed language that is a subset of Racket. This is in contrast to the
  8505. previous chapters, which have studied the compilation of Typed
  8506. Racket. In dynamically typed languages such as \LangDyn{}, a given
  8507. expression may produce a value of a different type each time it is
  8508. executed. Consider the following example with a conditional \code{if}
  8509. expression that may return a Boolean or an integer depending on the
  8510. input to the program.
  8511. % part of dynamic_test_25.rkt
  8512. \begin{lstlisting}
  8513. (not (if (eq? (read) 1) #f 0))
  8514. \end{lstlisting}
  8515. Languages that allow expressions to produce different kinds of values
  8516. are called \emph{polymorphic}, a word composed of the Greek roots
  8517. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  8518. are several kinds of polymorphism in programming languages, such as
  8519. subtype polymorphism and parametric
  8520. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  8521. study in this chapter does not have a special name but it is the kind
  8522. that arises in dynamically typed languages.
  8523. Another characteristic of dynamically typed languages is that
  8524. primitive operations, such as \code{not}, are often defined to operate
  8525. on many different types of values. In fact, in Racket, the \code{not}
  8526. operator produces a result for any kind of value: given \code{\#f} it
  8527. returns \code{\#t} and given anything else it returns \code{\#f}.
  8528. Furthermore, even when primitive operations restrict their inputs to
  8529. values of a certain type, this restriction is enforced at runtime
  8530. instead of during compilation. For example, the following vector
  8531. reference results in a run-time contract violation because the index
  8532. must be in integer, not a Boolean such as \code{\#t}.
  8533. \begin{lstlisting}
  8534. (vector-ref (vector 42) #t)
  8535. \end{lstlisting}
  8536. \begin{figure}[tp]
  8537. \centering
  8538. \fbox{
  8539. \begin{minipage}{0.97\textwidth}
  8540. \[
  8541. \begin{array}{rcl}
  8542. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  8543. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8544. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  8545. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  8546. &\mid& \key{\#t} \mid \key{\#f}
  8547. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  8548. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  8549. \mid \CUNIOP{\key{not}}{\Exp} \\
  8550. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  8551. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  8552. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  8553. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  8554. &\mid& \LP\Exp \; \Exp\ldots\RP
  8555. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  8556. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  8557. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  8558. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  8559. \LangDyn{} &::=& \Def\ldots\; \Exp
  8560. \end{array}
  8561. \]
  8562. \end{minipage}
  8563. }
  8564. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  8565. \label{fig:r7-concrete-syntax}
  8566. \end{figure}
  8567. \begin{figure}[tp]
  8568. \centering
  8569. \fbox{
  8570. \begin{minipage}{0.96\textwidth}
  8571. \small
  8572. \[
  8573. \begin{array}{lcl}
  8574. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  8575. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  8576. &\mid& \BOOL{\itm{bool}}
  8577. \mid \IF{\Exp}{\Exp}{\Exp} \\
  8578. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  8579. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  8580. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  8581. \LangDyn{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  8582. \end{array}
  8583. \]
  8584. \end{minipage}
  8585. }
  8586. \caption{The abstract syntax of \LangDyn{}.}
  8587. \label{fig:r7-syntax}
  8588. \end{figure}
  8589. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  8590. defined in Figures~\ref{fig:r7-concrete-syntax} and
  8591. \ref{fig:r7-syntax}.
  8592. %
  8593. There is no type checker for \LangDyn{} because it is not a statically
  8594. typed language (it's dynamically typed!).
  8595. The definitional interpreter for \LangDyn{} is presented in
  8596. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  8597. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  8598. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  8599. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  8600. interpreter for \LangDyn{} creates a \emph{tagged value}\index{tagged
  8601. value} that combines an underlying value with a tag that identifies
  8602. what kind of value it is. We define the following struct
  8603. to represented tagged values.
  8604. \begin{lstlisting}
  8605. (struct Tagged (value tag) #:transparent)
  8606. \end{lstlisting}
  8607. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  8608. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  8609. but don't always capture all the information that a type does. For
  8610. example, a vector of type \code{(Vector Any Any)} is tagged with
  8611. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  8612. is tagged with \code{Procedure}.
  8613. Next consider the match case for \code{vector-ref}. The
  8614. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  8615. is used to ensure that the first argument is a vector and the second
  8616. is an integer. If they are not, a \code{trapped-error} is raised.
  8617. Recall from Section~\ref{sec:interp-Rint} that when a definition
  8618. interpreter raises a \code{trapped-error} error, the compiled code
  8619. must also signal an error by exiting with return code \code{255}. A
  8620. \code{trapped-error} is also raised if the index is not less than
  8621. length of the vector.
  8622. \begin{figure}[tbp]
  8623. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8624. (define ((interp-Rdyn-exp env) ast)
  8625. (define recur (interp-Rdyn-exp env))
  8626. (match ast
  8627. [(Var x) (lookup x env)]
  8628. [(Int n) (Tagged n 'Integer)]
  8629. [(Bool b) (Tagged b 'Boolean)]
  8630. [(Lambda xs rt body)
  8631. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  8632. [(Prim 'vector es)
  8633. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  8634. [(Prim 'vector-ref (list e1 e2))
  8635. (define vec (recur e1)) (define i (recur e2))
  8636. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8637. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8638. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8639. (vector-ref (Tagged-value vec) (Tagged-value i))]
  8640. [(Prim 'vector-set! (list e1 e2 e3))
  8641. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  8642. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8643. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8644. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8645. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  8646. (Tagged (void) 'Void)]
  8647. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  8648. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  8649. [(Prim 'or (list e1 e2))
  8650. (define v1 (recur e1))
  8651. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  8652. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  8653. [(Prim op (list e1))
  8654. #:when (set-member? type-predicates op)
  8655. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  8656. [(Prim op es)
  8657. (define args (map recur es))
  8658. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  8659. (unless (for/or ([expected-tags (op-tags op)])
  8660. (equal? expected-tags tags))
  8661. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  8662. (tag-value
  8663. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  8664. [(If q t f)
  8665. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  8666. [(Apply f es)
  8667. (define new-f (recur f)) (define args (map recur es))
  8668. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  8669. (match f-val
  8670. [`(function ,xs ,body ,lam-env)
  8671. (unless (eq? (length xs) (length args))
  8672. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  8673. (define new-env (append (map cons xs args) lam-env))
  8674. ((interp-Rdyn-exp new-env) body)]
  8675. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  8676. \end{lstlisting}
  8677. \caption{Interpreter for the \LangDyn{} language.}
  8678. \label{fig:interp-Rdyn}
  8679. \end{figure}
  8680. \begin{figure}[tbp]
  8681. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8682. (define (interp-op op)
  8683. (match op
  8684. ['+ fx+]
  8685. ['- fx-]
  8686. ['read read-fixnum]
  8687. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  8688. ['< (lambda (v1 v2)
  8689. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  8690. ['<= (lambda (v1 v2)
  8691. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  8692. ['> (lambda (v1 v2)
  8693. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  8694. ['>= (lambda (v1 v2)
  8695. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  8696. ['boolean? boolean?]
  8697. ['integer? fixnum?]
  8698. ['void? void?]
  8699. ['vector? vector?]
  8700. ['vector-length vector-length]
  8701. ['procedure? (match-lambda
  8702. [`(functions ,xs ,body ,env) #t] [else #f])]
  8703. [else (error 'interp-op "unknown operator" op)]))
  8704. (define (op-tags op)
  8705. (match op
  8706. ['+ '((Integer Integer))]
  8707. ['- '((Integer Integer) (Integer))]
  8708. ['read '(())]
  8709. ['not '((Boolean))]
  8710. ['< '((Integer Integer))]
  8711. ['<= '((Integer Integer))]
  8712. ['> '((Integer Integer))]
  8713. ['>= '((Integer Integer))]
  8714. ['vector-length '((Vector))]))
  8715. (define type-predicates
  8716. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8717. (define (tag-value v)
  8718. (cond [(boolean? v) (Tagged v 'Boolean)]
  8719. [(fixnum? v) (Tagged v 'Integer)]
  8720. [(procedure? v) (Tagged v 'Procedure)]
  8721. [(vector? v) (Tagged v 'Vector)]
  8722. [(void? v) (Tagged v 'Void)]
  8723. [else (error 'tag-value "unidentified value ~a" v)]))
  8724. (define (check-tag val expected ast)
  8725. (define tag (Tagged-tag val))
  8726. (unless (eq? tag expected)
  8727. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  8728. \end{lstlisting}
  8729. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  8730. \label{fig:interp-Rdyn-aux}
  8731. \end{figure}
  8732. \clearpage
  8733. \section{Representation of Tagged Values}
  8734. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  8735. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  8736. values at the bit level. Because almost every operation in \LangDyn{}
  8737. involves manipulating tagged values, the representation must be
  8738. efficient. Recall that all of our values are 64 bits. We shall steal
  8739. the 3 right-most bits to encode the tag. We use $001$ to identify
  8740. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  8741. and $101$ for the void value. We define the following auxiliary
  8742. function for mapping types to tag codes.
  8743. \begin{align*}
  8744. \itm{tagof}(\key{Integer}) &= 001 \\
  8745. \itm{tagof}(\key{Boolean}) &= 100 \\
  8746. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  8747. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  8748. \itm{tagof}(\key{Void}) &= 101
  8749. \end{align*}
  8750. This stealing of 3 bits comes at some price: our integers are reduced
  8751. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  8752. affect vectors and procedures because those values are addresses, and
  8753. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  8754. they are always $000$. Thus, we do not lose information by overwriting
  8755. the rightmost 3 bits with the tag and we can simply zero-out the tag
  8756. to recover the original address.
  8757. To make tagged values into first-class entities, we can give them a
  8758. type, called \code{Any}, and define operations such as \code{Inject}
  8759. and \code{Project} for creating and using them, yielding the \LangAny{}
  8760. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  8761. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  8762. in greater detail.
  8763. \section{The \LangAny{} Language}
  8764. \label{sec:Rany-lang}
  8765. \begin{figure}[tp]
  8766. \centering
  8767. \fbox{
  8768. \begin{minipage}{0.96\textwidth}
  8769. \small
  8770. \[
  8771. \begin{array}{lcl}
  8772. \Type &::= & \ldots \mid \key{Any} \\
  8773. \itm{op} &::= & \ldots \mid \code{any-vector-length}
  8774. \mid \code{any-vector-ref} \mid \code{any-vector-set!}\\
  8775. &\mid& \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  8776. \mid \code{procedure?} \mid \code{void?} \\
  8777. \Exp &::=& \ldots
  8778. \mid \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  8779. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  8780. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8781. \LangAny{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8782. \end{array}
  8783. \]
  8784. \end{minipage}
  8785. }
  8786. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  8787. \label{fig:Rany-syntax}
  8788. \end{figure}
  8789. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  8790. (The concrete syntax of \LangAny{} is in the Appendix,
  8791. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  8792. converts the value produced by expression $e$ of type $T$ into a
  8793. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  8794. produced by expression $e$ into a value of type $T$ or else halts the
  8795. program if the type tag is not equivalent to $T$.
  8796. %
  8797. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  8798. restricted to a flat type $\FType$, which simplifies the
  8799. implementation and corresponds with what is needed for compiling \LangDyn{}.
  8800. The \code{any-vector} operators adapt the vector operations so that
  8801. they can be applied to a value of type \code{Any}. They also
  8802. generalize the vector operations in that the index is not restricted
  8803. to be a literal integer in the grammar but is allowed to be any
  8804. expression.
  8805. The type predicates such as \key{boolean?} expect their argument to
  8806. produce a tagged value; they return \key{\#t} if the tag corresponds
  8807. to the predicate and they return \key{\#f} otherwise.
  8808. The type checker for \LangAny{} is shown in
  8809. Figures~\ref{fig:type-check-Rany-part-1} and
  8810. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  8811. Figure~\ref{fig:type-check-Rany-aux}.
  8812. %
  8813. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  8814. auxiliary functions \code{apply-inject} and \code{apply-project} are
  8815. in Figure~\ref{fig:apply-project}.
  8816. \begin{figure}[btp]
  8817. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8818. (define type-check-Rany-class
  8819. (class type-check-Rlambda-class
  8820. (super-new)
  8821. (inherit check-type-equal?)
  8822. (define/override (type-check-exp env)
  8823. (lambda (e)
  8824. (define recur (type-check-exp env))
  8825. (match e
  8826. [(Inject e1 ty)
  8827. (unless (flat-ty? ty)
  8828. (error 'type-check "may only inject from flat type, not ~a" ty))
  8829. (define-values (new-e1 e-ty) (recur e1))
  8830. (check-type-equal? e-ty ty e)
  8831. (values (Inject new-e1 ty) 'Any)]
  8832. [(Project e1 ty)
  8833. (unless (flat-ty? ty)
  8834. (error 'type-check "may only project to flat type, not ~a" ty))
  8835. (define-values (new-e1 e-ty) (recur e1))
  8836. (check-type-equal? e-ty 'Any e)
  8837. (values (Project new-e1 ty) ty)]
  8838. [(Prim 'any-vector-length (list e1))
  8839. (define-values (e1^ t1) (recur e1))
  8840. (check-type-equal? t1 'Any e)
  8841. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  8842. [(Prim 'any-vector-ref (list e1 e2))
  8843. (define-values (e1^ t1) (recur e1))
  8844. (define-values (e2^ t2) (recur e2))
  8845. (check-type-equal? t1 'Any e)
  8846. (check-type-equal? t2 'Integer e)
  8847. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  8848. [(Prim 'any-vector-set! (list e1 e2 e3))
  8849. (define-values (e1^ t1) (recur e1))
  8850. (define-values (e2^ t2) (recur e2))
  8851. (define-values (e3^ t3) (recur e3))
  8852. (check-type-equal? t1 'Any e)
  8853. (check-type-equal? t2 'Integer e)
  8854. (check-type-equal? t3 'Any e)
  8855. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  8856. \end{lstlisting}
  8857. \caption{Type checker for the \LangAny{} language, part 1.}
  8858. \label{fig:type-check-Rany-part-1}
  8859. \end{figure}
  8860. \begin{figure}[btp]
  8861. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8862. [(ValueOf e ty)
  8863. (define-values (new-e e-ty) (recur e))
  8864. (values (ValueOf new-e ty) ty)]
  8865. [(Prim pred (list e1))
  8866. #:when (set-member? (type-predicates) pred)
  8867. (define-values (new-e1 e-ty) (recur e1))
  8868. (check-type-equal? e-ty 'Any e)
  8869. (values (Prim pred (list new-e1)) 'Boolean)]
  8870. [(If cnd thn els)
  8871. (define-values (cnd^ Tc) (recur cnd))
  8872. (define-values (thn^ Tt) (recur thn))
  8873. (define-values (els^ Te) (recur els))
  8874. (check-type-equal? Tc 'Boolean cnd)
  8875. (check-type-equal? Tt Te e)
  8876. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  8877. [(Exit) (values (Exit) '_)]
  8878. [(Prim 'eq? (list arg1 arg2))
  8879. (define-values (e1 t1) (recur arg1))
  8880. (define-values (e2 t2) (recur arg2))
  8881. (match* (t1 t2)
  8882. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  8883. [(other wise) (check-type-equal? t1 t2 e)])
  8884. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  8885. [else ((super type-check-exp env) e)])))
  8886. ))
  8887. \end{lstlisting}
  8888. \caption{Type checker for the \LangAny{} language, part 2.}
  8889. \label{fig:type-check-Rany-part-2}
  8890. \end{figure}
  8891. \begin{figure}[tbp]
  8892. \begin{lstlisting}
  8893. (define/override (operator-types)
  8894. (append
  8895. '((integer? . ((Any) . Boolean))
  8896. (vector? . ((Any) . Boolean))
  8897. (procedure? . ((Any) . Boolean))
  8898. (void? . ((Any) . Boolean))
  8899. (tag-of-any . ((Any) . Integer))
  8900. (make-any . ((_ Integer) . Any))
  8901. )
  8902. (super operator-types)))
  8903. (define/public (type-predicates)
  8904. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8905. (define/public (combine-types t1 t2)
  8906. (match (list t1 t2)
  8907. [(list '_ t2) t2]
  8908. [(list t1 '_) t1]
  8909. [(list `(Vector ,ts1 ...)
  8910. `(Vector ,ts2 ...))
  8911. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  8912. (combine-types t1 t2)))]
  8913. [(list `(,ts1 ... -> ,rt1)
  8914. `(,ts2 ... -> ,rt2))
  8915. `(,@(for/list ([t1 ts1] [t2 ts2])
  8916. (combine-types t1 t2))
  8917. -> ,(combine-types rt1 rt2))]
  8918. [else t1]))
  8919. (define/public (flat-ty? ty)
  8920. (match ty
  8921. [(or `Integer `Boolean '_ `Void) #t]
  8922. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  8923. [`(,ts ... -> ,rt)
  8924. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  8925. [else #f]))
  8926. \end{lstlisting}
  8927. \caption{Auxiliary methods for type checking \LangAny{}.}
  8928. \label{fig:type-check-Rany-aux}
  8929. \end{figure}
  8930. \begin{figure}[btp]
  8931. \begin{lstlisting}
  8932. (define interp-Rany-class
  8933. (class interp-Rlambda-class
  8934. (super-new)
  8935. (define/override (interp-op op)
  8936. (match op
  8937. ['boolean? (match-lambda
  8938. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  8939. [else #f])]
  8940. ['integer? (match-lambda
  8941. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  8942. [else #f])]
  8943. ['vector? (match-lambda
  8944. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  8945. [else #f])]
  8946. ['procedure? (match-lambda
  8947. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  8948. [else #f])]
  8949. ['eq? (match-lambda*
  8950. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  8951. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  8952. [ls (apply (super interp-op op) ls)])]
  8953. ['any-vector-ref (lambda (v i)
  8954. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  8955. ['any-vector-set! (lambda (v i a)
  8956. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  8957. ['any-vector-length (lambda (v)
  8958. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  8959. [else (super interp-op op)]))
  8960. (define/override ((interp-exp env) e)
  8961. (define recur (interp-exp env))
  8962. (match e
  8963. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  8964. [(Project e ty2) (apply-project (recur e) ty2)]
  8965. [else ((super interp-exp env) e)]))
  8966. ))
  8967. (define (interp-Rany p)
  8968. (send (new interp-Rany-class) interp-program p))
  8969. \end{lstlisting}
  8970. \caption{Interpreter for \LangAny{}.}
  8971. \label{fig:interp-Rany}
  8972. \end{figure}
  8973. \begin{figure}[tbp]
  8974. \begin{lstlisting}
  8975. (define/public (apply-inject v tg) (Tagged v tg))
  8976. (define/public (apply-project v ty2)
  8977. (define tag2 (any-tag ty2))
  8978. (match v
  8979. [(Tagged v1 tag1)
  8980. (cond
  8981. [(eq? tag1 tag2)
  8982. (match ty2
  8983. [`(Vector ,ts ...)
  8984. (define l1 ((interp-op 'vector-length) v1))
  8985. (cond
  8986. [(eq? l1 (length ts)) v1]
  8987. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  8988. l1 (length ts))])]
  8989. [`(,ts ... -> ,rt)
  8990. (match v1
  8991. [`(function ,xs ,body ,env)
  8992. (cond [(eq? (length xs) (length ts)) v1]
  8993. [else
  8994. (error 'apply-project "arity mismatch ~a != ~a"
  8995. (length xs) (length ts))])]
  8996. [else (error 'apply-project "expected function not ~a" v1)])]
  8997. [else v1])]
  8998. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  8999. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  9000. \end{lstlisting}
  9001. \caption{Auxiliary functions for injection and projection.}
  9002. \label{fig:apply-project}
  9003. \end{figure}
  9004. \clearpage
  9005. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  9006. \label{sec:compile-r7}
  9007. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  9008. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  9009. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  9010. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  9011. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  9012. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  9013. the Boolean \code{\#t}, which must be injected to produce an
  9014. expression of type \key{Any}.
  9015. %
  9016. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  9017. addition, is representative of compilation for many primitive
  9018. operations: the arguments have type \key{Any} and must be projected to
  9019. \key{Integer} before the addition can be performed.
  9020. The compilation of \key{lambda} (third row of
  9021. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  9022. produce type annotations: we simply use \key{Any}.
  9023. %
  9024. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  9025. has to account for some differences in behavior between \LangDyn{} and
  9026. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  9027. kind of values can be used in various places. For example, the
  9028. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  9029. the arguments need not be of the same type (in that case the
  9030. result is \code{\#f}).
  9031. \begin{figure}[btp]
  9032. \centering
  9033. \begin{tabular}{|lll|} \hline
  9034. \begin{minipage}{0.27\textwidth}
  9035. \begin{lstlisting}
  9036. #t
  9037. \end{lstlisting}
  9038. \end{minipage}
  9039. &
  9040. $\Rightarrow$
  9041. &
  9042. \begin{minipage}{0.65\textwidth}
  9043. \begin{lstlisting}
  9044. (inject #t Boolean)
  9045. \end{lstlisting}
  9046. \end{minipage}
  9047. \\[2ex]\hline
  9048. \begin{minipage}{0.27\textwidth}
  9049. \begin{lstlisting}
  9050. (+ |$e_1$| |$e_2$|)
  9051. \end{lstlisting}
  9052. \end{minipage}
  9053. &
  9054. $\Rightarrow$
  9055. &
  9056. \begin{minipage}{0.65\textwidth}
  9057. \begin{lstlisting}
  9058. (inject
  9059. (+ (project |$e'_1$| Integer)
  9060. (project |$e'_2$| Integer))
  9061. Integer)
  9062. \end{lstlisting}
  9063. \end{minipage}
  9064. \\[2ex]\hline
  9065. \begin{minipage}{0.27\textwidth}
  9066. \begin{lstlisting}
  9067. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  9068. \end{lstlisting}
  9069. \end{minipage}
  9070. &
  9071. $\Rightarrow$
  9072. &
  9073. \begin{minipage}{0.65\textwidth}
  9074. \begin{lstlisting}
  9075. (inject
  9076. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  9077. (Any|$\ldots$|Any -> Any))
  9078. \end{lstlisting}
  9079. \end{minipage}
  9080. \\[2ex]\hline
  9081. \begin{minipage}{0.27\textwidth}
  9082. \begin{lstlisting}
  9083. (|$e_0$| |$e_1 \ldots e_n$|)
  9084. \end{lstlisting}
  9085. \end{minipage}
  9086. &
  9087. $\Rightarrow$
  9088. &
  9089. \begin{minipage}{0.65\textwidth}
  9090. \begin{lstlisting}
  9091. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  9092. \end{lstlisting}
  9093. \end{minipage}
  9094. \\[2ex]\hline
  9095. \begin{minipage}{0.27\textwidth}
  9096. \begin{lstlisting}
  9097. (vector-ref |$e_1$| |$e_2$|)
  9098. \end{lstlisting}
  9099. \end{minipage}
  9100. &
  9101. $\Rightarrow$
  9102. &
  9103. \begin{minipage}{0.65\textwidth}
  9104. \begin{lstlisting}
  9105. (any-vector-ref |$e_1'$| |$e_2'$|)
  9106. \end{lstlisting}
  9107. \end{minipage}
  9108. \\[2ex]\hline
  9109. \begin{minipage}{0.27\textwidth}
  9110. \begin{lstlisting}
  9111. (if |$e_1$| |$e_2$| |$e_3$|)
  9112. \end{lstlisting}
  9113. \end{minipage}
  9114. &
  9115. $\Rightarrow$
  9116. &
  9117. \begin{minipage}{0.65\textwidth}
  9118. \begin{lstlisting}
  9119. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  9120. \end{lstlisting}
  9121. \end{minipage}
  9122. \\[2ex]\hline
  9123. \begin{minipage}{0.27\textwidth}
  9124. \begin{lstlisting}
  9125. (eq? |$e_1$| |$e_2$|)
  9126. \end{lstlisting}
  9127. \end{minipage}
  9128. &
  9129. $\Rightarrow$
  9130. &
  9131. \begin{minipage}{0.65\textwidth}
  9132. \begin{lstlisting}
  9133. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  9134. \end{lstlisting}
  9135. \end{minipage}
  9136. \\[2ex]\hline
  9137. \begin{minipage}{0.27\textwidth}
  9138. \begin{lstlisting}
  9139. (not |$e_1$|)
  9140. \end{lstlisting}
  9141. \end{minipage}
  9142. &
  9143. $\Rightarrow$
  9144. &
  9145. \begin{minipage}{0.65\textwidth}
  9146. \begin{lstlisting}
  9147. (if (eq? |$e'_1$| (inject #f Boolean))
  9148. (inject #t Boolean) (inject #f Boolean))
  9149. \end{lstlisting}
  9150. \end{minipage}
  9151. \\[2ex]\hline
  9152. \end{tabular}
  9153. \caption{Cast Insertion}
  9154. \label{fig:compile-r7-Rany}
  9155. \end{figure}
  9156. \section{Reveal Casts}
  9157. \label{sec:reveal-casts-Rany}
  9158. % TODO: define R'_6
  9159. In the \code{reveal-casts} pass we recommend compiling \code{project}
  9160. into an \code{if} expression that checks whether the value's tag
  9161. matches the target type; if it does, the value is converted to a value
  9162. of the target type by removing the tag; if it does not, the program
  9163. exits. To perform these actions we need a new primitive operation,
  9164. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  9165. The \code{tag-of-any} operation retrieves the type tag from a tagged
  9166. value of type \code{Any}. The \code{ValueOf} form retrieves the
  9167. underlying value from a tagged value. The \code{ValueOf} form
  9168. includes the type for the underlying value which is used by the type
  9169. checker. Finally, the \code{Exit} form ends the execution of the
  9170. program.
  9171. If the target type of the projection is \code{Boolean} or
  9172. \code{Integer}, then \code{Project} can be translated as follows.
  9173. \begin{center}
  9174. \begin{minipage}{1.0\textwidth}
  9175. \begin{lstlisting}
  9176. (Project |$e$| |$\FType$|)
  9177. |$\Rightarrow$|
  9178. (Let |$\itm{tmp}$| |$e'$|
  9179. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  9180. (Int |$\itm{tagof}(\FType)$|)))
  9181. (ValueOf |$\itm{tmp}$| |$\FType$|)
  9182. (Exit)))
  9183. \end{lstlisting}
  9184. \end{minipage}
  9185. \end{center}
  9186. If the target type of the projection is a vector or function type,
  9187. then there is a bit more work to do. For vectors, check that the
  9188. length of the vector type matches the length of the vector (using the
  9189. \code{vector-length} primitive). For functions, check that the number
  9190. of parameters in the function type matches the function's arity (using
  9191. \code{procedure-arity}).
  9192. Regarding \code{inject}, we recommend compiling it to a slightly
  9193. lower-level primitive operation named \code{make-any}. This operation
  9194. takes a tag instead of a type.
  9195. \begin{center}
  9196. \begin{minipage}{1.0\textwidth}
  9197. \begin{lstlisting}
  9198. (Inject |$e$| |$\FType$|)
  9199. |$\Rightarrow$|
  9200. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  9201. \end{lstlisting}
  9202. \end{minipage}
  9203. \end{center}
  9204. The type predicates (\code{boolean?}, etc.) can be translated into
  9205. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  9206. translation of \code{Project}.
  9207. The \code{any-vector-ref} and \code{any-vector-set!} operations
  9208. combine the projection action with the vector operation. Also, the
  9209. read and write operations allow arbitrary expressions for the index so
  9210. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  9211. cannot guarantee that the index is within bounds. Thus, we insert code
  9212. to perform bounds checking at runtime. The translation for
  9213. \code{any-vector-ref} is as follows and the other two operations are
  9214. translated in a similar way.
  9215. \begin{lstlisting}
  9216. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  9217. |$\Rightarrow$|
  9218. (Let |$v$| |$e'_1$|
  9219. (Let |$i$| |$e'_2$|
  9220. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  9221. (If (Prim '< (list (Var |$i$|)
  9222. (Prim 'any-vector-length (list (Var |$v$|)))))
  9223. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  9224. (Exit))))
  9225. \end{lstlisting}
  9226. \section{Remove Complex Operands}
  9227. \label{sec:rco-Rany}
  9228. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  9229. The subexpression of \code{ValueOf} must be atomic.
  9230. \section{Explicate Control and \LangCAny{}}
  9231. \label{sec:explicate-Rany}
  9232. The output of \code{explicate-control} is the \LangCAny{} language whose
  9233. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  9234. form that we added to \LangAny{} remains an expression and the \code{Exit}
  9235. expression becomes a $\Tail$. Also, note that the index argument of
  9236. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  9237. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  9238. \begin{figure}[tp]
  9239. \fbox{
  9240. \begin{minipage}{0.96\textwidth}
  9241. \small
  9242. \[
  9243. \begin{array}{lcl}
  9244. \Exp &::= & \ldots
  9245. \mid \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  9246. &\mid& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  9247. &\mid& \VALUEOF{\Exp}{\FType} \\
  9248. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9249. \mid \LP\key{Collect} \,\itm{int}\RP }\\
  9250. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  9251. \mid \GOTO{\itm{label}} } \\
  9252. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9253. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  9254. \mid \LP\key{Exit}\RP \\
  9255. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  9256. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  9257. \end{array}
  9258. \]
  9259. \end{minipage}
  9260. }
  9261. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9262. \label{fig:c5-syntax}
  9263. \end{figure}
  9264. \section{Select Instructions}
  9265. \label{sec:select-Rany}
  9266. In the \code{select-instructions} pass we translate the primitive
  9267. operations on the \code{Any} type to x86 instructions that involve
  9268. manipulating the 3 tag bits of the tagged value.
  9269. \paragraph{Make-any}
  9270. We recommend compiling the \key{make-any} primitive as follows if the
  9271. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  9272. shifts the destination to the left by the number of bits specified its
  9273. source argument (in this case $3$, the length of the tag) and it
  9274. preserves the sign of the integer. We use the \key{orq} instruction to
  9275. combine the tag and the value to form the tagged value. \\
  9276. \begin{lstlisting}
  9277. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9278. |$\Rightarrow$|
  9279. movq |$e'$|, |\itm{lhs'}|
  9280. salq $3, |\itm{lhs'}|
  9281. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9282. \end{lstlisting}
  9283. The instruction selection for vectors and procedures is different
  9284. because their is no need to shift them to the left. The rightmost 3
  9285. bits are already zeros as described at the beginning of this
  9286. chapter. So we just combine the value and the tag using \key{orq}. \\
  9287. \begin{lstlisting}
  9288. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9289. |$\Rightarrow$|
  9290. movq |$e'$|, |\itm{lhs'}|
  9291. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9292. \end{lstlisting}
  9293. \paragraph{Tag-of-any}
  9294. Recall that the \code{tag-of-any} operation extracts the type tag from
  9295. a value of type \code{Any}. The type tag is the bottom three bits, so
  9296. we obtain the tag by taking the bitwise-and of the value with $111$
  9297. ($7$ in decimal).
  9298. \begin{lstlisting}
  9299. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  9300. |$\Rightarrow$|
  9301. movq |$e'$|, |\itm{lhs'}|
  9302. andq $7, |\itm{lhs'}|
  9303. \end{lstlisting}
  9304. \paragraph{ValueOf}
  9305. Like \key{make-any}, the instructions for \key{ValueOf} are different
  9306. depending on whether the type $T$ is a pointer (vector or procedure)
  9307. or not (Integer or Boolean). The following shows the instruction
  9308. selection for Integer and Boolean. We produce an untagged value by
  9309. shifting it to the right by 3 bits.
  9310. \begin{lstlisting}
  9311. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9312. |$\Rightarrow$|
  9313. movq |$e'$|, |\itm{lhs'}|
  9314. sarq $3, |\itm{lhs'}|
  9315. \end{lstlisting}
  9316. %
  9317. In the case for vectors and procedures, there is no need to
  9318. shift. Instead we just need to zero-out the rightmost 3 bits. We
  9319. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  9320. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  9321. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  9322. then apply \code{andq} with the tagged value to get the desired
  9323. result. \\
  9324. \begin{lstlisting}
  9325. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9326. |$\Rightarrow$|
  9327. movq $|$-8$|, |\itm{lhs'}|
  9328. andq |$e'$|, |\itm{lhs'}|
  9329. \end{lstlisting}
  9330. %% \paragraph{Type Predicates} We leave it to the reader to
  9331. %% devise a sequence of instructions to implement the type predicates
  9332. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  9333. \paragraph{Any-vector-length}
  9334. \begin{lstlisting}
  9335. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  9336. |$\Longrightarrow$|
  9337. movq |$\neg 111$|, %r11
  9338. andq |$a_1'$|, %r11
  9339. movq 0(%r11), %r11
  9340. andq $126, %r11
  9341. sarq $1, %r11
  9342. movq %r11, |$\itm{lhs'}$|
  9343. \end{lstlisting}
  9344. \paragraph{Any-vector-ref}
  9345. The index may be an arbitrary atom so instead of computing the offset
  9346. at compile time, instructions need to be generated to compute the
  9347. offset at runtime as follows. Note the use of the new instruction
  9348. \code{imulq}.
  9349. \begin{center}
  9350. \begin{minipage}{0.96\textwidth}
  9351. \begin{lstlisting}
  9352. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  9353. |$\Longrightarrow$|
  9354. movq |$\neg 111$|, %r11
  9355. andq |$a_1'$|, %r11
  9356. movq |$a_2'$|, %rax
  9357. addq $1, %rax
  9358. imulq $8, %rax
  9359. addq %rax, %r11
  9360. movq 0(%r11) |$\itm{lhs'}$|
  9361. \end{lstlisting}
  9362. \end{minipage}
  9363. \end{center}
  9364. \paragraph{Any-vector-set!}
  9365. The code generation for \code{any-vector-set!} is similar to the other
  9366. \code{any-vector} operations.
  9367. \section{Register Allocation for \LangAny{}}
  9368. \label{sec:register-allocation-Rany}
  9369. \index{register allocation}
  9370. There is an interesting interaction between tagged values and garbage
  9371. collection that has an impact on register allocation. A variable of
  9372. type \code{Any} might refer to a vector and therefore it might be a
  9373. root that needs to be inspected and copied during garbage
  9374. collection. Thus, we need to treat variables of type \code{Any} in a
  9375. similar way to variables of type \code{Vector} for purposes of
  9376. register allocation. In particular,
  9377. \begin{itemize}
  9378. \item If a variable of type \code{Any} is live during a function call,
  9379. then it must be spilled. This can be accomplished by changing
  9380. \code{build-interference} to mark all variables of type \code{Any}
  9381. that are live after a \code{callq} as interfering with all the
  9382. registers.
  9383. \item If a variable of type \code{Any} is spilled, it must be spilled
  9384. to the root stack instead of the normal procedure call stack.
  9385. \end{itemize}
  9386. Another concern regarding the root stack is that the garbage collector
  9387. needs to differentiate between (1) plain old pointers to tuples, (2) a
  9388. tagged value that points to a tuple, and (3) a tagged value that is
  9389. not a tuple. We enable this differentiation by choosing not to use the
  9390. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  9391. reserved for identifying plain old pointers to tuples. That way, if
  9392. one of the first three bits is set, then we have a tagged value and
  9393. inspecting the tag can differentiation between vectors ($010$) and the
  9394. other kinds of values.
  9395. \begin{exercise}\normalfont
  9396. Expand your compiler to handle \LangAny{} as discussed in the last few
  9397. sections. Create 5 new programs that use the \code{Any} type and the
  9398. new operations (\code{inject}, \code{project}, \code{boolean?},
  9399. etc.). Test your compiler on these new programs and all of your
  9400. previously created test programs.
  9401. \end{exercise}
  9402. \begin{exercise}\normalfont
  9403. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  9404. Create tests for \LangDyn{} by adapting ten of your previous test programs
  9405. by removing type annotations. Add 5 more tests programs that
  9406. specifically rely on the language being dynamically typed. That is,
  9407. they should not be legal programs in a statically typed language, but
  9408. nevertheless, they should be valid \LangDyn{} programs that run to
  9409. completion without error.
  9410. \end{exercise}
  9411. \begin{figure}[p]
  9412. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9413. \node (Rfun) at (0,4) {\large \LangDyn{}};
  9414. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  9415. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  9416. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  9417. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  9418. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  9419. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  9420. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  9421. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  9422. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  9423. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  9424. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  9425. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9426. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9427. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9428. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9429. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9430. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9431. \path[->,bend left=15] (Rfun) edge [above] node
  9432. {\ttfamily\footnotesize shrink} (Rfun-2);
  9433. \path[->,bend left=15] (Rfun-2) edge [above] node
  9434. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9435. \path[->,bend left=15] (Rfun-3) edge [above] node
  9436. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  9437. \path[->,bend right=15] (Rfun-4) edge [left] node
  9438. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  9439. \path[->,bend left=15] (Rfun-5) edge [above] node
  9440. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  9441. \path[->,bend left=15] (Rfun-6) edge [left] node
  9442. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  9443. \path[->,bend left=15] (Rfun-7) edge [below] node
  9444. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9445. \path[->,bend right=15] (F1-2) edge [above] node
  9446. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9447. \path[->,bend right=15] (F1-3) edge [above] node
  9448. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9449. \path[->,bend right=15] (F1-4) edge [above] node
  9450. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9451. \path[->,bend right=15] (F1-5) edge [right] node
  9452. {\ttfamily\footnotesize explicate-control} (C3-2);
  9453. \path[->,bend left=15] (C3-2) edge [left] node
  9454. {\ttfamily\footnotesize select-instr.} (x86-2);
  9455. \path[->,bend right=15] (x86-2) edge [left] node
  9456. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9457. \path[->,bend right=15] (x86-2-1) edge [below] node
  9458. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9459. \path[->,bend right=15] (x86-2-2) edge [left] node
  9460. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9461. \path[->,bend left=15] (x86-3) edge [above] node
  9462. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9463. \path[->,bend left=15] (x86-4) edge [right] node
  9464. {\ttfamily\footnotesize print-x86} (x86-5);
  9465. \end{tikzpicture}
  9466. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  9467. \label{fig:Rdyn-passes}
  9468. \end{figure}
  9469. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  9470. for the compilation of \LangDyn{}.
  9471. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9472. \chapter{Loops and Assignment}
  9473. \label{ch:Rwhile}
  9474. % TODO: define R'_8
  9475. % TODO: multi-graph
  9476. In this chapter we study two features that are the hallmarks of
  9477. imperative programming languages: loops and assignments to local
  9478. variables. The following example demonstrates these new features by
  9479. computing the sum of the first five positive integers.
  9480. % similar to loop_test_1.rkt
  9481. \begin{lstlisting}
  9482. (let ([sum 0])
  9483. (let ([i 5])
  9484. (begin
  9485. (while (> i 0)
  9486. (begin
  9487. (set! sum (+ sum i))
  9488. (set! i (- i 1))))
  9489. sum)))
  9490. \end{lstlisting}
  9491. The \code{while} loop consists of a condition and a body.
  9492. %
  9493. The \code{set!} consists of a variable and a right-hand-side expression.
  9494. %
  9495. The primary purpose of both the \code{while} loop and \code{set!} is
  9496. to cause side effects, so it is convenient to also include in a
  9497. language feature for sequencing side effects: the \code{begin}
  9498. expression. It consists of one or more subexpressions that are
  9499. evaluated left-to-right.
  9500. \section{The \LangLoop{} Language}
  9501. \begin{figure}[tp]
  9502. \centering
  9503. \fbox{
  9504. \begin{minipage}{0.96\textwidth}
  9505. \small
  9506. \[
  9507. \begin{array}{lcl}
  9508. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  9509. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  9510. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  9511. &\mid& \gray{\key{\#t} \mid \key{\#f}
  9512. \mid (\key{and}\;\Exp\;\Exp)
  9513. \mid (\key{or}\;\Exp\;\Exp)
  9514. \mid (\key{not}\;\Exp) } \\
  9515. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  9516. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  9517. (\key{vector-ref}\;\Exp\;\Int)} \\
  9518. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  9519. \mid (\Exp \; \Exp\ldots) } \\
  9520. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  9521. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  9522. &\mid& \CSETBANG{\Var}{\Exp}
  9523. \mid \CBEGIN{\Exp\ldots}{\Exp}
  9524. \mid \CWHILE{\Exp}{\Exp} \\
  9525. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9526. \LangLoop{} &::=& \gray{\Def\ldots \; \Exp}
  9527. \end{array}
  9528. \]
  9529. \end{minipage}
  9530. }
  9531. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-concrete-syntax}).}
  9532. \label{fig:Rwhile-concrete-syntax}
  9533. \end{figure}
  9534. \begin{figure}[tp]
  9535. \centering
  9536. \fbox{
  9537. \begin{minipage}{0.96\textwidth}
  9538. \small
  9539. \[
  9540. \begin{array}{lcl}
  9541. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  9542. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  9543. &\mid& \gray{ \BOOL{\itm{bool}}
  9544. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  9545. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  9546. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  9547. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  9548. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9549. \mid \WHILE{\Exp}{\Exp} \\
  9550. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9551. \LangLoop{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9552. \end{array}
  9553. \]
  9554. \end{minipage}
  9555. }
  9556. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-syntax}).}
  9557. \label{fig:Rwhile-syntax}
  9558. \end{figure}
  9559. The concrete syntax of \LangLoop{} is defined in
  9560. Figure~\ref{fig:Rwhile-concrete-syntax} and its abstract syntax is defined
  9561. in Figure~\ref{fig:Rwhile-syntax}.
  9562. %
  9563. The definitional interpreter for \LangLoop{} is shown in
  9564. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  9565. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  9566. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  9567. support assignment to variables and to make their lifetimes indefinite
  9568. (see the second example in Section~\ref{sec:assignment-scoping}), we
  9569. box the value that is bound to each variable (in \code{Let}) and
  9570. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  9571. the value.
  9572. %
  9573. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9574. variable in the environment to obtain a boxed value and then we change
  9575. it using \code{set-box!} to the result of evaluating the right-hand
  9576. side. The result value of a \code{SetBang} is \code{void}.
  9577. %
  9578. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9579. if the result is true, 2) evaluate the body.
  9580. The result value of a \code{while} loop is also \code{void}.
  9581. %
  9582. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9583. subexpressions \itm{es} for their effects and then evaluates
  9584. and returns the result from \itm{body}.
  9585. \begin{figure}[tbp]
  9586. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9587. (define interp-Rwhile-class
  9588. (class interp-Rany-class
  9589. (super-new)
  9590. (define/override ((interp-exp env) e)
  9591. (define recur (interp-exp env))
  9592. (match e
  9593. [(SetBang x rhs)
  9594. (set-box! (lookup x env) (recur rhs))]
  9595. [(WhileLoop cnd body)
  9596. (define (loop)
  9597. (cond [(recur cnd) (recur body) (loop)]
  9598. [else (void)]))
  9599. (loop)]
  9600. [(Begin es body)
  9601. (for ([e es]) (recur e))
  9602. (recur body)]
  9603. [else ((super interp-exp env) e)]))
  9604. ))
  9605. (define (interp-Rwhile p)
  9606. (send (new interp-Rwhile-class) interp-program p))
  9607. \end{lstlisting}
  9608. \caption{Interpreter for \LangLoop{}.}
  9609. \label{fig:interp-Rwhile}
  9610. \end{figure}
  9611. The type checker for \LangLoop{} is define in
  9612. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  9613. variable and the right-hand-side must agree. The result type is
  9614. \code{Void}. For the \code{WhileLoop}, the condition must be a
  9615. \code{Boolean}. The result type is also \code{Void}. For
  9616. \code{Begin}, the result type is the type of its last subexpression.
  9617. \begin{figure}[tbp]
  9618. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9619. (define type-check-Rwhile-class
  9620. (class type-check-Rany-class
  9621. (super-new)
  9622. (inherit check-type-equal?)
  9623. (define/override (type-check-exp env)
  9624. (lambda (e)
  9625. (define recur (type-check-exp env))
  9626. (match e
  9627. [(SetBang x rhs)
  9628. (define-values (rhs^ rhsT) (recur rhs))
  9629. (define varT (dict-ref env x))
  9630. (check-type-equal? rhsT varT e)
  9631. (values (SetBang x rhs^) 'Void)]
  9632. [(WhileLoop cnd body)
  9633. (define-values (cnd^ Tc) (recur cnd))
  9634. (check-type-equal? Tc 'Boolean e)
  9635. (define-values (body^ Tbody) ((type-check-exp env) body))
  9636. (values (WhileLoop cnd^ body^) 'Void)]
  9637. [(Begin es body)
  9638. (define-values (es^ ts)
  9639. (for/lists (l1 l2) ([e es]) (recur e)))
  9640. (define-values (body^ Tbody) (recur body))
  9641. (values (Begin es^ body^) Tbody)]
  9642. [else ((super type-check-exp env) e)])))
  9643. ))
  9644. (define (type-check-Rwhile p)
  9645. (send (new type-check-Rwhile-class) type-check-program p))
  9646. \end{lstlisting}
  9647. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  9648. and \code{Begin} in \LangLoop{}.}
  9649. \label{fig:type-check-Rwhile}
  9650. \end{figure}
  9651. At first glance, the translation of these language features to x86
  9652. seems straightforward because the \LangCFun{} intermediate language already
  9653. supports all of the ingredients that we need: assignment, \code{goto},
  9654. conditional branching, and sequencing. However, there are two
  9655. complications that arise which we discuss in the next two
  9656. sections. After that we introduce one new compiler pass and the
  9657. changes necessary to the existing passes.
  9658. \section{Assignment and Lexically Scoped Functions}
  9659. \label{sec:assignment-scoping}
  9660. The addition of assignment raises a problem with our approach to
  9661. implementing lexically-scoped functions. Consider the following
  9662. example in which function \code{f} has a free variable \code{x} that
  9663. is changed after \code{f} is created but before the call to \code{f}.
  9664. % loop_test_11.rkt
  9665. \begin{lstlisting}
  9666. (let ([x 0])
  9667. (let ([y 0])
  9668. (let ([z 20])
  9669. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9670. (begin
  9671. (set! x 10)
  9672. (set! y 12)
  9673. (f y))))))
  9674. \end{lstlisting}
  9675. The correct output for this example is \code{42} because the call to
  9676. \code{f} is required to use the current value of \code{x} (which is
  9677. \code{10}). Unfortunately, the closure conversion pass
  9678. (Section~\ref{sec:closure-conversion}) generates code for the
  9679. \code{lambda} that copies the old value of \code{x} into a
  9680. closure. Thus, if we naively add support for assignment to our current
  9681. compiler, the output of this program would be \code{32}.
  9682. A first attempt at solving this problem would be to save a pointer to
  9683. \code{x} in the closure and change the occurrences of \code{x} inside
  9684. the lambda to dereference the pointer. Of course, this would require
  9685. assigning \code{x} to the stack and not to a register. However, the
  9686. problem goes a bit deeper. Consider the following example in which we
  9687. create a counter abstraction by creating a pair of functions that
  9688. share the free variable \code{x}.
  9689. % similar to loop_test_10.rkt
  9690. \begin{lstlisting}
  9691. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  9692. (vector
  9693. (lambda: () : Integer x)
  9694. (lambda: () : Void (set! x (+ 1 x)))))
  9695. (let ([counter (f 0)])
  9696. (let ([get (vector-ref counter 0)])
  9697. (let ([inc (vector-ref counter 1)])
  9698. (begin
  9699. (inc)
  9700. (get)))))
  9701. \end{lstlisting}
  9702. In this example, the lifetime of \code{x} extends beyond the lifetime
  9703. of the call to \code{f}. Thus, if we were to store \code{x} on the
  9704. stack frame for the call to \code{f}, it would be gone by the time we
  9705. call \code{inc} and \code{get}, leaving us with dangling pointers for
  9706. \code{x}. This example demonstrates that when a variable occurs free
  9707. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  9708. value of the variable needs to live on the heap. The verb ``box'' is
  9709. often used for allocating a single value on the heap, producing a
  9710. pointer, and ``unbox'' for dereferencing the pointer.
  9711. We recommend solving these problems by ``boxing'' the local variables
  9712. that are in the intersection of 1) variables that appear on the
  9713. left-hand-side of a \code{set!} and 2) variables that occur free
  9714. inside a \code{lambda}. We shall introduce a new pass named
  9715. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  9716. perform this translation. But before diving into the compiler passes,
  9717. we one more problem to discuss.
  9718. \section{Cyclic Control Flow and Dataflow Analysis}
  9719. \label{sec:dataflow-analysis}
  9720. Up until this point the control-flow graphs generated in
  9721. \code{explicate-control} were guaranteed to be acyclic. However, each
  9722. \code{while} loop introduces a cycle in the control-flow graph.
  9723. But does that matter?
  9724. %
  9725. Indeed it does. Recall that for register allocation, the compiler
  9726. performs liveness analysis to determine which variables can share the
  9727. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  9728. the control-flow graph in reverse topological order, but topological
  9729. order is only well-defined for acyclic graphs.
  9730. Let us return to the example of computing the sum of the first five
  9731. positive integers. Here is the program after instruction selection but
  9732. before register allocation.
  9733. \begin{center}
  9734. \begin{minipage}{0.45\textwidth}
  9735. \begin{lstlisting}
  9736. (define (main) : Integer
  9737. mainstart:
  9738. movq $0, sum1
  9739. movq $5, i2
  9740. jmp block5
  9741. block5:
  9742. movq i2, tmp3
  9743. cmpq tmp3, $0
  9744. jl block7
  9745. jmp block8
  9746. \end{lstlisting}
  9747. \end{minipage}
  9748. \begin{minipage}{0.45\textwidth}
  9749. \begin{lstlisting}
  9750. block7:
  9751. addq i2, sum1
  9752. movq $1, tmp4
  9753. negq tmp4
  9754. addq tmp4, i2
  9755. jmp block5
  9756. block8:
  9757. movq $27, %rax
  9758. addq sum1, %rax
  9759. jmp mainconclusion
  9760. )
  9761. \end{lstlisting}
  9762. \end{minipage}
  9763. \end{center}
  9764. Recall that liveness analysis works backwards, starting at the end
  9765. of each function. For this example we could start with \code{block8}
  9766. because we know what is live at the beginning of the conclusion,
  9767. just \code{rax} and \code{rsp}. So the live-before set
  9768. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  9769. %
  9770. Next we might try to analyze \code{block5} or \code{block7}, but
  9771. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9772. we are stuck.
  9773. The way out of this impasse comes from the realization that one can
  9774. perform liveness analysis starting with an empty live-after set to
  9775. compute an under-approximation of the live-before set. By
  9776. \emph{under-approximation}, we mean that the set only contains
  9777. variables that are really live, but it may be missing some. Next, the
  9778. under-approximations for each block can be improved by 1) updating the
  9779. live-after set for each block using the approximate live-before sets
  9780. from the other blocks and 2) perform liveness analysis again on each
  9781. block. In fact, by iterating this process, the under-approximations
  9782. eventually become the correct solutions!
  9783. %
  9784. This approach of iteratively analyzing a control-flow graph is
  9785. applicable to many static analysis problems and goes by the name
  9786. \emph{dataflow analysis}\index{dataflow analysis}. It was invented by
  9787. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9788. Washington.
  9789. Let us apply this approach to the above example. We use the empty set
  9790. for the initial live-before set for each block. Let $m_0$ be the
  9791. following mapping from label names to sets of locations (variables and
  9792. registers).
  9793. \begin{center}
  9794. \begin{lstlisting}
  9795. mainstart: {}
  9796. block5: {}
  9797. block7: {}
  9798. block8: {}
  9799. \end{lstlisting}
  9800. \end{center}
  9801. Using the above live-before approximations, we determine the
  9802. live-after for each block and then apply liveness analysis to each
  9803. block. This produces our next approximation $m_1$ of the live-before
  9804. sets.
  9805. \begin{center}
  9806. \begin{lstlisting}
  9807. mainstart: {}
  9808. block5: {i2}
  9809. block7: {i2, sum1}
  9810. block8: {rsp, sum1}
  9811. \end{lstlisting}
  9812. \end{center}
  9813. For the second round, the live-after for \code{mainstart} is the
  9814. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  9815. liveness analysis for \code{mainstart} computes the empty set. The
  9816. live-after for \code{block5} is the union of the live-before sets for
  9817. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  9818. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  9819. sum1\}}. The live-after for \code{block7} is the live-before for
  9820. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  9821. So the liveness analysis for \code{block7} remains \code{\{i2,
  9822. sum1\}}. Together these yield the following approximation $m_2$ of
  9823. the live-before sets.
  9824. \begin{center}
  9825. \begin{lstlisting}
  9826. mainstart: {}
  9827. block5: {i2, rsp, sum1}
  9828. block7: {i2, sum1}
  9829. block8: {rsp, sum1}
  9830. \end{lstlisting}
  9831. \end{center}
  9832. In the preceding iteration, only \code{block5} changed, so we can
  9833. limit our attention to \code{mainstart} and \code{block7}, the two
  9834. blocks that jump to \code{block5}. As a result, the live-before sets
  9835. for \code{mainstart} and \code{block7} are updated to include
  9836. \code{rsp}, yielding the following approximation $m_3$.
  9837. \begin{center}
  9838. \begin{lstlisting}
  9839. mainstart: {rsp}
  9840. block5: {i2, rsp, sum1}
  9841. block7: {i2, rsp, sum1}
  9842. block8: {rsp, sum1}
  9843. \end{lstlisting}
  9844. \end{center}
  9845. Because \code{block7} changed, we analyze \code{block5} once more, but
  9846. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  9847. our approximations have converged, so $m_3$ is the solution.
  9848. This iteration process is guaranteed to converge to a solution by the
  9849. Kleene Fixed-Point Theorem, a general theorem about functions on
  9850. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9851. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9852. elements, a least element $\bot$ (pronounced bottom), and a join
  9853. operator $\sqcup$.\index{lattice}\index{bottom}\index{partial
  9854. ordering}\index{join}\footnote{Technically speaking, we will be
  9855. working with join semi-lattices.} When two elements are ordered $m_i
  9856. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9857. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9858. approximation than $m_i$. The bottom element $\bot$ represents the
  9859. complete lack of information, i.e., the worst approximation. The join
  9860. operator takes two lattice elements and combines their information,
  9861. i.e., it produces the least upper bound of the two.\index{least upper
  9862. bound}
  9863. A dataflow analysis typically involves two lattices: one lattice to
  9864. represent abstract states and another lattice that aggregates the
  9865. abstract states of all the blocks in the control-flow graph. For
  9866. liveness analysis, an abstract state is a set of locations. We form
  9867. the lattice $L$ by taking its elements to be sets of locations, the
  9868. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9869. set, and the join operator to be set union.
  9870. %
  9871. We form a second lattice $M$ by taking its elements to be mappings
  9872. from the block labels to sets of locations (elements of $L$). We
  9873. order the mappings point-wise, using the ordering of $L$. So given any
  9874. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9875. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9876. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9877. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9878. We can think of one iteration of liveness analysis as being a function
  9879. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  9880. mapping.
  9881. \[
  9882. f(m_i) = m_{i+1}
  9883. \]
  9884. Next let us think for a moment about what a final solution $m_s$
  9885. should look like. If we perform liveness analysis using the solution
  9886. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9887. solution should be a \emph{fixed point} of the function $f$.\index{fixed point}
  9888. \[
  9889. f(m_s) = m_s
  9890. \]
  9891. Furthermore, the solution should only include locations that are
  9892. forced to be there by performing liveness analysis on the program, so
  9893. the solution should be the \emph{least} fixed point.\index{least fixed point}
  9894. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9895. monotone (better inputs produce better outputs), then the least fixed
  9896. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9897. chain} obtained by starting at $\bot$ and iterating $f$ as
  9898. follows.\index{Kleene Fixed-Point Theorem}
  9899. \[
  9900. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9901. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9902. \]
  9903. When a lattice contains only finitely-long ascending chains, then
  9904. every Kleene chain tops out at some fixed point after a number of
  9905. iterations of $f$. So that fixed point is also a least upper
  9906. bound of the chain.
  9907. \[
  9908. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9909. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9910. \]
  9911. The liveness analysis is indeed a monotone function and the lattice
  9912. $M$ only has finitely-long ascending chains because there are only a
  9913. finite number of variables and blocks in the program. Thus we are
  9914. guaranteed that iteratively applying liveness analysis to all blocks
  9915. in the program will eventually produce the least fixed point solution.
  9916. Next let us consider dataflow analysis in general and discuss the
  9917. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9918. %
  9919. The algorithm has four parameters: the control-flow graph \code{G}, a
  9920. function \code{transfer} that applies the analysis to one block, the
  9921. \code{bottom} and \code{join} operator for the lattice of abstract
  9922. states. The algorithm begins by creating the bottom mapping,
  9923. represented by a hash table. It then pushes all of the nodes in the
  9924. control-flow graph onto the work list (a queue). The algorithm repeats
  9925. the \code{while} loop as long as there are items in the work list. In
  9926. each iteration, a node is popped from the work list and processed. The
  9927. \code{input} for the node is computed by taking the join of the
  9928. abstract states of all the predecessor nodes. The \code{transfer}
  9929. function is then applied to obtain the \code{output} abstract
  9930. state. If the output differs from the previous state for this block,
  9931. the mapping for this block is updated and its successor nodes are
  9932. pushed onto the work list.
  9933. \begin{figure}[tb]
  9934. \begin{lstlisting}
  9935. (define (analyze-dataflow G transfer bottom join)
  9936. (define mapping (make-hash))
  9937. (for ([v (in-vertices G)])
  9938. (dict-set! mapping v bottom))
  9939. (define worklist (make-queue))
  9940. (for ([v (in-vertices G)])
  9941. (enqueue! worklist v))
  9942. (define trans-G (transpose G))
  9943. (while (not (queue-empty? worklist))
  9944. (define node (dequeue! worklist))
  9945. (define input (for/fold ([state bottom])
  9946. ([pred (in-neighbors trans-G node)])
  9947. (join state (dict-ref mapping pred))))
  9948. (define output (transfer node input))
  9949. (cond [(not (equal? output (dict-ref mapping node)))
  9950. (dict-set! mapping node output)
  9951. (for ([v (in-neighbors G node)])
  9952. (enqueue! worklist v))]))
  9953. mapping)
  9954. \end{lstlisting}
  9955. \caption{Generic work list algorithm for dataflow analysis}
  9956. \label{fig:generic-dataflow}
  9957. \end{figure}
  9958. Having discussed the two complications that arise from adding support
  9959. for assignment and loops, we turn to discussing the one new compiler
  9960. pass and the significant changes to existing passes.
  9961. \section{Convert Assignments}
  9962. \label{sec:convert-assignments}
  9963. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  9964. the combination of assignments and lexically-scoped functions requires
  9965. that we box those variables that are both assigned-to and that appear
  9966. free inside a \code{lambda}. The purpose of the
  9967. \code{convert-assignments} pass is to carry out that transformation.
  9968. We recommend placing this pass after \code{uniquify} but before
  9969. \code{reveal-functions}.
  9970. Consider again the first example from
  9971. Section~\ref{sec:assignment-scoping}:
  9972. \begin{lstlisting}
  9973. (let ([x 0])
  9974. (let ([y 0])
  9975. (let ([z 20])
  9976. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9977. (begin
  9978. (set! x 10)
  9979. (set! y 12)
  9980. (f y))))))
  9981. \end{lstlisting}
  9982. The variables \code{x} and \code{y} are assigned-to. The variables
  9983. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  9984. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  9985. The boxing of \code{x} consists of three transformations: initialize
  9986. \code{x} with a vector, replace reads from \code{x} with
  9987. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  9988. \code{vector-set!}. The output of \code{convert-assignments} for this
  9989. example is as follows.
  9990. \begin{lstlisting}
  9991. (define (main) : Integer
  9992. (let ([x0 (vector 0)])
  9993. (let ([y1 0])
  9994. (let ([z2 20])
  9995. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  9996. (+ a3 (+ (vector-ref x0 0) z2)))])
  9997. (begin
  9998. (vector-set! x0 0 10)
  9999. (set! y1 12)
  10000. (f4 y1)))))))
  10001. \end{lstlisting}
  10002. \paragraph{Assigned \& Free}
  10003. We recommend defining an auxiliary function named
  10004. \code{assigned\&free} that takes an expression and simultaneously
  10005. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  10006. that occur free within lambda's, and 3) a new version of the
  10007. expression that records which bound variables occurred in the
  10008. intersection of $A$ and $F$. You can use the struct
  10009. \code{AssignedFree} to do this. Consider the case for
  10010. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  10011. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  10012. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  10013. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  10014. \begin{lstlisting}
  10015. (Let |$x$| |$rhs$| |$body$|)
  10016. |$\Rightarrow$|
  10017. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  10018. \end{lstlisting}
  10019. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  10020. The set of assigned variables for this \code{Let} is
  10021. $A_r \cup (A_b - \{x\})$
  10022. and the set of variables free in lambda's is
  10023. $F_r \cup (F_b - \{x\})$.
  10024. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  10025. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  10026. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  10027. and $F_r$.
  10028. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  10029. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  10030. recursively processing \itm{body}. Wrap each of parameter that occurs
  10031. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  10032. Let $P$ be the set of parameter names in \itm{params}. The result is
  10033. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  10034. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  10035. variables of an expression (see Chapter~\ref{ch:Rlam}).
  10036. \paragraph{Convert Assignments}
  10037. Next we discuss the \code{convert-assignment} pass with its auxiliary
  10038. functions for expressions and definitions. The function for
  10039. expressions, \code{cnvt-assign-exp}, should take an expression and a
  10040. set of assigned-and-free variables (obtained from the result of
  10041. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  10042. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  10043. \code{vector-ref}.
  10044. \begin{lstlisting}
  10045. (Var |$x$|)
  10046. |$\Rightarrow$|
  10047. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  10048. \end{lstlisting}
  10049. %
  10050. In the case for $\LET{\LP\code{AssignedFree}\,
  10051. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  10052. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  10053. \itm{body'} but with $x$ added to the set of assigned-and-free
  10054. variables. Translate the let-expression as follows to bind $x$ to a
  10055. boxed value.
  10056. \begin{lstlisting}
  10057. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  10058. |$\Rightarrow$|
  10059. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  10060. \end{lstlisting}
  10061. %
  10062. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  10063. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  10064. variables, translate the \code{set!} into a \code{vector-set!}
  10065. as follows.
  10066. \begin{lstlisting}
  10067. (SetBang |$x$| |$\itm{rhs}$|)
  10068. |$\Rightarrow$|
  10069. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  10070. \end{lstlisting}
  10071. %
  10072. The case for \code{Lambda} is non-trivial, but it is similar to the
  10073. case for function definitions, which we discuss next.
  10074. The auxiliary function for definitions, \code{cnvt-assign-def},
  10075. applies assignment conversion to function definitions.
  10076. We translate a function definition as follows.
  10077. \begin{lstlisting}
  10078. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  10079. |$\Rightarrow$|
  10080. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  10081. \end{lstlisting}
  10082. So it remains to explain \itm{params'} and $\itm{body}_4$.
  10083. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  10084. \code{assigned\&free} on $\itm{body_1}$.
  10085. Let $P$ be the parameter names in \itm{params}.
  10086. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  10087. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  10088. as the set of assigned-and-free variables.
  10089. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  10090. in a sequence of let-expressions that box the parameters
  10091. that are in $A_b \cap F_b$.
  10092. %
  10093. Regarding \itm{params'}, change the names of the parameters that are
  10094. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  10095. variables can retain the original names). Recall the second example in
  10096. Section~\ref{sec:assignment-scoping} involving a counter
  10097. abstraction. The following is the output of assignment version for
  10098. function \code{f}.
  10099. \begin{lstlisting}
  10100. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  10101. (vector
  10102. (lambda: () : Integer x1)
  10103. (lambda: () : Void (set! x1 (+ 1 x1)))))
  10104. |$\Rightarrow$|
  10105. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  10106. (let ([x1 (vector param_x1)])
  10107. (vector (lambda: () : Integer (vector-ref x1 0))
  10108. (lambda: () : Void
  10109. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  10110. \end{lstlisting}
  10111. \section{Remove Complex Operands}
  10112. \label{sec:rco-loop}
  10113. The three new language forms, \code{while}, \code{set!}, and
  10114. \code{begin} are all complex expressions and their subexpressions are
  10115. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  10116. output language \LangFunANF{} of this pass.
  10117. \begin{figure}[tp]
  10118. \centering
  10119. \fbox{
  10120. \begin{minipage}{0.96\textwidth}
  10121. \small
  10122. \[
  10123. \begin{array}{rcl}
  10124. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  10125. \mid \VOID{} } \\
  10126. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10127. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  10128. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10129. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  10130. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  10131. \end{array}
  10132. \]
  10133. \end{minipage}
  10134. }
  10135. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  10136. \label{fig:Rwhile-anf-syntax}
  10137. \end{figure}
  10138. As usual, when a complex expression appears in a grammar position that
  10139. needs to be atomic, such as the argument of a primitive operator, we
  10140. must introduce a temporary variable and bind it to the complex
  10141. expression. This approach applies, unchanged, to handle the new
  10142. language forms. For example, in the following code there are two
  10143. \code{begin} expressions appearing as arguments to \code{+}. The
  10144. output of \code{rco-exp} is shown below, in which the \code{begin}
  10145. expressions have been bound to temporary variables. Recall that
  10146. \code{let} expressions in \LangLoopANF{} are allowed to have
  10147. arbitrary expressions in their right-hand-side expression, so it is
  10148. fine to place \code{begin} there.
  10149. \begin{lstlisting}
  10150. (let ([x0 10])
  10151. (let ([y1 0])
  10152. (+ (+ (begin (set! y1 (read)) x0)
  10153. (begin (set! x0 (read)) y1))
  10154. x0)))
  10155. |$\Rightarrow$|
  10156. (let ([x0 10])
  10157. (let ([y1 0])
  10158. (let ([tmp2 (begin (set! y1 (read)) x0)])
  10159. (let ([tmp3 (begin (set! x0 (read)) y1)])
  10160. (let ([tmp4 (+ tmp2 tmp3)])
  10161. (+ tmp4 x0))))))
  10162. \end{lstlisting}
  10163. \section{Explicate Control and \LangCLoop{}}
  10164. \label{sec:explicate-loop}
  10165. Recall that in the \code{explicate-control} pass we define one helper
  10166. function for each kind of position in the program. For the \LangVar{}
  10167. language of integers and variables we needed kinds of positions:
  10168. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  10169. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  10170. yet another kind of position: effect position. Except for the last
  10171. subexpression, the subexpressions inside a \code{begin} are evaluated
  10172. only for their effect. Their result values are discarded. We can
  10173. generate better code by taking this fact into account.
  10174. The output language of \code{explicate-control} is \LangCLoop{}
  10175. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  10176. \LangCLam{}. The only syntactic difference is that \code{Call},
  10177. \code{vector-set!}, and \code{read} may also appear as statements.
  10178. The most significant difference between \LangCLam{} and \LangCLoop{}
  10179. is that the control-flow graphs of the later may contain cycles.
  10180. \begin{figure}[tp]
  10181. \fbox{
  10182. \begin{minipage}{0.96\textwidth}
  10183. \small
  10184. \[
  10185. \begin{array}{lcl}
  10186. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10187. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  10188. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  10189. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  10190. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  10191. \LangCLoop{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  10192. \end{array}
  10193. \]
  10194. \end{minipage}
  10195. }
  10196. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  10197. \label{fig:c7-syntax}
  10198. \end{figure}
  10199. The new auxiliary function \code{explicate-effect} takes an expression
  10200. (in an effect position) and a promise of a continuation block. The
  10201. function returns a promise for a $\Tail$ that includes the generated
  10202. code for the input expression followed by the continuation block. If
  10203. the expression is obviously pure, that is, never causes side effects,
  10204. then the expression can be removed, so the result is just the
  10205. continuation block.
  10206. %
  10207. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  10208. case. First, you will need a fresh label $\itm{loop}$ for the top of
  10209. the loop. Recursively process the \itm{body} (in effect position)
  10210. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  10211. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  10212. \itm{body'} as the then-branch and the continuation block as the
  10213. else-branch. The result should be added to the control-flow graph with
  10214. the label \itm{loop}. The result for the whole \code{while} loop is a
  10215. \code{goto} to the \itm{loop} label. Note that the loop should only be
  10216. added to the control-flow graph if the loop is indeed used, which can
  10217. be accomplished using \code{delay}.
  10218. The auxiliary functions for tail, assignment, and predicate positions
  10219. need to be updated. The three new language forms, \code{while},
  10220. \code{set!}, and \code{begin}, can appear in assignment and tail
  10221. positions. Only \code{begin} may appear in predicate positions; the
  10222. other two have result type \code{Void}.
  10223. \section{Select Instructions}
  10224. \label{sec:select-instructions-loop}
  10225. Only three small additions are needed in the
  10226. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  10227. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  10228. stand-alone statements instead of only appearing on the right-hand
  10229. side of an assignment statement. The code generation is nearly
  10230. identical; just leave off the instruction for moving the result into
  10231. the left-hand side.
  10232. \section{Register Allocation}
  10233. \label{sec:register-allocation-loop}
  10234. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  10235. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10236. which complicates the liveness analysis needed for register
  10237. allocation.
  10238. \subsection{Liveness Analysis}
  10239. \label{sec:liveness-analysis-r8}
  10240. We recommend using the generic \code{analyze-dataflow} function that
  10241. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  10242. perform liveness analysis, replacing the code in
  10243. \code{uncover-live-CFG} that processed the basic blocks in topological
  10244. order (Section~\ref{sec:liveness-analysis-Rif}).
  10245. The \code{analyze-dataflow} function has four parameters.
  10246. \begin{enumerate}
  10247. \item The first parameter \code{G} should be a directed graph from the
  10248. \code{racket/graph} package (see the sidebar in
  10249. Section~\ref{sec:build-interference}) that represents the
  10250. control-flow graph.
  10251. \item The second parameter \code{transfer} is a function that applies
  10252. liveness analysis to a basic block. It takes two parameters: the
  10253. label for the block to analyze and the live-after set for that
  10254. block. The transfer function should return the live-before set for
  10255. the block. Also, as a side-effect, it should update the block's
  10256. $\itm{info}$ with the liveness information for each instruction. To
  10257. implement the \code{transfer} function, you should be able to reuse
  10258. the code you already have for analyzing basic blocks.
  10259. \item The third and fourth parameters of \code{analyze-dataflow} are
  10260. \code{bottom} and \code{join} for the lattice of abstract states,
  10261. i.e. sets of locations. The bottom of the lattice is the empty set
  10262. \code{(set)} and the join operator is \code{set-union}.
  10263. \end{enumerate}
  10264. \begin{figure}[p]
  10265. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10266. \node (Rfun) at (0,2) {\large \LangLoop{}};
  10267. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  10268. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  10269. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10270. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10271. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10272. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10273. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  10274. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  10275. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  10276. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10277. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10278. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10279. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10280. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10281. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10282. %% \path[->,bend left=15] (Rfun) edge [above] node
  10283. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  10284. \path[->,bend left=15] (Rfun) edge [above] node
  10285. {\ttfamily\footnotesize shrink} (Rfun-2);
  10286. \path[->,bend left=15] (Rfun-2) edge [above] node
  10287. {\ttfamily\footnotesize uniquify} (Rfun-3);
  10288. \path[->,bend left=15] (Rfun-3) edge [above] node
  10289. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  10290. \path[->,bend left=15] (Rfun-4) edge [right] node
  10291. {\ttfamily\footnotesize convert-assignments} (F1-1);
  10292. \path[->,bend left=15] (F1-1) edge [below] node
  10293. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  10294. \path[->,bend right=15] (F1-2) edge [above] node
  10295. {\ttfamily\footnotesize limit-fun.} (F1-3);
  10296. \path[->,bend right=15] (F1-3) edge [above] node
  10297. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10298. \path[->,bend right=15] (F1-4) edge [above] node
  10299. {\ttfamily\footnotesize remove-complex.} (F1-5);
  10300. \path[->,bend right=15] (F1-5) edge [right] node
  10301. {\ttfamily\footnotesize explicate-control} (C3-2);
  10302. \path[->,bend left=15] (C3-2) edge [left] node
  10303. {\ttfamily\footnotesize select-instr.} (x86-2);
  10304. \path[->,bend right=15] (x86-2) edge [left] node
  10305. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10306. \path[->,bend right=15] (x86-2-1) edge [below] node
  10307. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10308. \path[->,bend right=15] (x86-2-2) edge [left] node
  10309. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10310. \path[->,bend left=15] (x86-3) edge [above] node
  10311. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10312. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  10313. \end{tikzpicture}
  10314. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  10315. \label{fig:Rwhile-passes}
  10316. \end{figure}
  10317. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  10318. for the compilation of \LangLoop{}.
  10319. \section{Challenge: Arrays}
  10320. \label{sec:arrays}
  10321. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  10322. elements whose length is determined at compile-time and where each
  10323. element of a tuple may have a different type (they are
  10324. heterogeous). This challenge is also about sequences, but this time
  10325. the length is determined at run-time and all the elements have the same
  10326. type (they are homogeneous). We use the term ``array'' for this later
  10327. kind of sequence.
  10328. The Racket language does not distinguish between tuples and arrays,
  10329. they are both represented by vectors. However, Typed Racket
  10330. distinguishes between tuples and arrays: the \code{Vector} type is for
  10331. tuples and the \code{Vectorof} type is for arrays.
  10332. %
  10333. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  10334. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  10335. and the \code{make-vector} primitive operator for creating an array,
  10336. whose arguments are the length of the array and an initial value for
  10337. all the elements in the array. The \code{vector-length},
  10338. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  10339. for tuples become overloaded for use with arrays.
  10340. %
  10341. We also include integer multiplication in \LangArray{}, as it is
  10342. useful in many examples involving arrays such as computing the
  10343. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  10344. \begin{figure}[tp]
  10345. \centering
  10346. \fbox{
  10347. \begin{minipage}{0.96\textwidth}
  10348. \small
  10349. \[
  10350. \begin{array}{lcl}
  10351. \Type &::=& \ldots \mid \LP \key{Vectorof}~\Type \RP \\
  10352. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10353. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \mid \CMUL{\Exp}{\Exp}\\
  10354. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10355. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10356. \mid \LP\key{and}\;\Exp\;\Exp\RP
  10357. \mid \LP\key{or}\;\Exp\;\Exp\RP
  10358. \mid \LP\key{not}\;\Exp\RP } \\
  10359. &\mid& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10360. &\mid& \gray{ \LP\key{vector}\;\Exp\ldots\RP \mid
  10361. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  10362. &\mid& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\mid \LP\key{void}\RP
  10363. \mid \LP\Exp \; \Exp\ldots\RP } \\
  10364. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  10365. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  10366. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10367. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10368. \mid \CWHILE{\Exp}{\Exp} } \\
  10369. &\mid& \CMAKEVEC{\Exp}{\Exp} \\
  10370. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  10371. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  10372. \end{array}
  10373. \]
  10374. \end{minipage}
  10375. }
  10376. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10377. \label{fig:Rvecof-concrete-syntax}
  10378. \end{figure}
  10379. \begin{figure}[tp]
  10380. \begin{lstlisting}
  10381. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  10382. [n : Integer]) : Integer
  10383. (let ([i 0])
  10384. (let ([prod 0])
  10385. (begin
  10386. (while (< i n)
  10387. (begin
  10388. (set! prod (+ prod (* (vector-ref A i)
  10389. (vector-ref B i))))
  10390. (set! i (+ i 1))
  10391. ))
  10392. prod))))
  10393. (let ([A (make-vector 2 2)])
  10394. (let ([B (make-vector 2 3)])
  10395. (+ (inner-product A B 2)
  10396. 30)))
  10397. \end{lstlisting}
  10398. \caption{Example program that computes the inner-product
  10399. of two arrays.}
  10400. \label{fig:inner-product}
  10401. \end{figure}
  10402. The type checker for \LangArray{} is define in
  10403. Figure~\ref{fig:type-check-Rvecof}. The result type of
  10404. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  10405. of the intializing expression. The length expression is required to
  10406. have type \code{Integer}. The type checking of the operators
  10407. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  10408. updated to handle the situation where the vector has type
  10409. \code{Vectorof}. In these cases we translate the operators to their
  10410. \code{vectorof} form so that later passes can easily distinguish
  10411. between operations on tuples versus arrays. We override the
  10412. \code{operator-types} method to provide the type signature for
  10413. multiplication: it takes two integers and returns an integer. To
  10414. support injection and projection of arrays to the \code{Any} type
  10415. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  10416. predicate.
  10417. \begin{figure}[tbp]
  10418. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10419. (define type-check-Rvecof-class
  10420. (class type-check-Rwhile-class
  10421. (super-new)
  10422. (inherit check-type-equal?)
  10423. (define/override (flat-ty? ty)
  10424. (match ty
  10425. ['(Vectorof Any) #t]
  10426. [else (super flat-ty? ty)]))
  10427. (define/override (operator-types)
  10428. (append '((* . ((Integer Integer) . Integer)))
  10429. (super operator-types)))
  10430. (define/override (type-check-exp env)
  10431. (lambda (e)
  10432. (define recur (type-check-exp env))
  10433. (match e
  10434. [(Prim 'make-vector (list e1 e2))
  10435. (define-values (e1^ t1) (recur e1))
  10436. (define-values (e2^ elt-type) (recur e2))
  10437. (define vec-type `(Vectorof ,elt-type))
  10438. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  10439. vec-type)]
  10440. [(Prim 'vector-ref (list e1 e2))
  10441. (define-values (e1^ t1) (recur e1))
  10442. (define-values (e2^ t2) (recur e2))
  10443. (match* (t1 t2)
  10444. [(`(Vectorof ,elt-type) 'Integer)
  10445. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  10446. [(other wise) ((super type-check-exp env) e)])]
  10447. [(Prim 'vector-set! (list e1 e2 e3) )
  10448. (define-values (e-vec t-vec) (recur e1))
  10449. (define-values (e2^ t2) (recur e2))
  10450. (define-values (e-arg^ t-arg) (recur e3))
  10451. (match t-vec
  10452. [`(Vectorof ,elt-type)
  10453. (check-type-equal? elt-type t-arg e)
  10454. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  10455. [else ((super type-check-exp env) e)])]
  10456. [(Prim 'vector-length (list e1))
  10457. (define-values (e1^ t1) (recur e1))
  10458. (match t1
  10459. [`(Vectorof ,t)
  10460. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  10461. [else ((super type-check-exp env) e)])]
  10462. [else ((super type-check-exp env) e)])))
  10463. ))
  10464. (define (type-check-Rvecof p)
  10465. (send (new type-check-Rvecof-class) type-check-program p))
  10466. \end{lstlisting}
  10467. \caption{Type checker for the \LangArray{} language.}
  10468. \label{fig:type-check-Rvecof}
  10469. \end{figure}
  10470. The interpreter for \LangArray{} is defined in
  10471. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  10472. implemented with Racket's \code{make-vector} function and
  10473. multiplication is \code{fx*}, multiplication for \code{fixnum}
  10474. integers.
  10475. \begin{figure}[tbp]
  10476. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10477. (define interp-Rvecof-class
  10478. (class interp-Rwhile-class
  10479. (super-new)
  10480. (define/override (interp-op op)
  10481. (verbose "Rvecof/interp-op" op)
  10482. (match op
  10483. ['make-vector make-vector]
  10484. ['* fx*]
  10485. [else (super interp-op op)]))
  10486. ))
  10487. (define (interp-Rvecof p)
  10488. (send (new interp-Rvecof-class) interp-program p))
  10489. \end{lstlisting}
  10490. \caption{Interpreter for \LangArray{}.}
  10491. \label{fig:interp-Rvecof}
  10492. \end{figure}
  10493. \subsection{Data Representation}
  10494. \label{sec:array-rep}
  10495. Just like tuples, we store arrays on the heap which means that the
  10496. garbage collector will need to inspect arrays. An immediate thought is
  10497. to use the same representation for arrays that we use for tuples.
  10498. However, we limit tuples to a length of $50$ so that their length and
  10499. pointer mask can fit into the 64-bit tag at the beginning of each
  10500. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  10501. millions of elements, so we need more bits to store the length.
  10502. However, because arrays are homogeneous, we only need $1$ bit for the
  10503. pointer mask instead of one bit per array elements. Finally, the
  10504. garbage collector will need to be able to distinguish between tuples
  10505. and arrays, so we need to reserve $1$ bit for that purpose. So we
  10506. arrive at the following layout for the 64-bit tag at the beginning of
  10507. an array:
  10508. \begin{itemize}
  10509. \item The right-most bit is the forwarding bit, just like in a tuple.
  10510. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  10511. it is not.
  10512. \item The next bit to the left is the pointer mask. A $0$ indicates
  10513. that none of the elements are pointers to the heap and a $1$
  10514. indicates that all of the elements are pointers.
  10515. \item The next $61$ bits store the length of the array.
  10516. \item The left-most bit distinguishes between a tuple ($0$) versus an
  10517. array ($1$).
  10518. \end{itemize}
  10519. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  10520. differentiate the kinds of values that have been injected into the
  10521. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  10522. to indicate that the value is an array.
  10523. In the following subsections we provide hints regarding how to update
  10524. the passes to handle arrays.
  10525. \subsection{Reveal Casts}
  10526. The array-access operators \code{vectorof-ref} and
  10527. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  10528. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  10529. that the type checker cannot tell whether the index will be in bounds,
  10530. so the bounds check must be performed at run time. Recall that the
  10531. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  10532. an \code{If} arround a vector reference for update to check whether
  10533. the index is less than the length. You should do the same for
  10534. \code{vectorof-ref} and \code{vectorof-set!} .
  10535. In addition, the handling of the \code{any-vector} operators in
  10536. \code{reveal-casts} needs to be updated to account for arrays that are
  10537. injected to \code{Any}. For the \code{any-vector-length} operator, the
  10538. generated code should test whether the tag is for tuples (\code{010})
  10539. or arrays (\code{110}) and then dispatch to either
  10540. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  10541. we add a case in \code{select-instructions} to generate the
  10542. appropriate instructions for accessing the array length from the
  10543. header of an array.
  10544. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  10545. the generated code needs to check that the index is less than the
  10546. vector length, so like the code for \code{any-vector-length}, check
  10547. the tag to determine whether to use \code{any-vector-length} or
  10548. \code{any-vectorof-length} for this purpose. Once the bounds checking
  10549. is complete, the generated code can use \code{any-vector-ref} and
  10550. \code{any-vector-set!} for both tuples and arrays because the
  10551. instructions used for those operators do not look at the tag at the
  10552. front of the tuple or array.
  10553. \subsection{Expose Allocation}
  10554. This pass should translate the \code{make-vector} operator into
  10555. lower-level operations. In particular, the new AST node
  10556. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  10557. length specified by the $\Exp$, but does not initialize the elements
  10558. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  10559. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  10560. element type for the array. Regarding the initialization of the array,
  10561. we recommend generated a \code{while} loop that uses
  10562. \code{vector-set!} to put the initializing value into every element of
  10563. the array.
  10564. \subsection{Remove Complex Operands}
  10565. Add cases in the \code{rco-atom} and \code{rco-exp} for
  10566. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  10567. complex and its subexpression must be atomic.
  10568. \subsection{Explicate Control}
  10569. Add cases for \code{AllocateArray} to \code{explicate-tail} and
  10570. \code{explicate-assign}.
  10571. \subsection{Select Instructions}
  10572. Generate instructions for \code{AllocateArray} similar to those for
  10573. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  10574. that the tag at the front of the array should instead use the
  10575. representation discussed in Section~\ref{sec:array-rep}.
  10576. Regarding \code{vectorof-length}, extract the length from the tag
  10577. according to the representation discussed in
  10578. Section~\ref{sec:array-rep}.
  10579. The instructions generated for \code{vectorof-ref} differ from those
  10580. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  10581. that the index is not a constant so the offset must be computed at
  10582. runtime, similar to the instructions generated for
  10583. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  10584. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  10585. appear in an assignment and as a stand-alone statement, so make sure
  10586. to handle both situations in this pass.
  10587. Finally, the instructions for \code{any-vectorof-length} should be
  10588. similar to those for \code{vectorof-length}, except that one must
  10589. first project the array by writing zeroes into the $3$-bit tag
  10590. \begin{exercise}\normalfont
  10591. Implement a compiler for the \LangArray{} language by extending your
  10592. compiler for \LangLoop{}. Test your compiler on a half dozen new
  10593. programs, including the one in Figure~\ref{fig:inner-product} and also
  10594. a program that multiplies two matrices. Note that matrices are
  10595. 2-dimensional arrays, but those can be encoded into 1-dimensional
  10596. arrays by laying out each row in the array, one after the next.
  10597. \end{exercise}
  10598. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10599. \chapter{Gradual Typing}
  10600. \label{ch:Rgrad}
  10601. \index{gradual typing}
  10602. This chapter studies a language, \LangGrad{}, in which the programmer
  10603. can choose between static and dynamic type checking in different parts
  10604. of a program, thereby mixing the statically typed \LangLoop{} language
  10605. with the dynamically typed \LangDyn{}. There are several approaches to
  10606. mixing static and dynamic typing, including multi-language
  10607. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  10608. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  10609. we focus on \emph{gradual typing}\index{gradual typing}, in which the
  10610. programmer controls the amount of static versus dynamic checking by
  10611. adding or removing type annotations on parameters and
  10612. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  10613. %
  10614. The concrete syntax of \LangGrad{} is defined in
  10615. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  10616. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  10617. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  10618. non-terminals that make type annotations optional. The return types
  10619. are not optional in the abstract syntax; the parser fills in
  10620. \code{Any} when the return type is not specified in the concrete
  10621. syntax.
  10622. \begin{figure}[tp]
  10623. \centering
  10624. \fbox{
  10625. \begin{minipage}{0.96\textwidth}
  10626. \small
  10627. \[
  10628. \begin{array}{lcl}
  10629. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10630. \itm{ret} &::=& \epsilon \mid \key{:} \Type \\
  10631. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10632. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  10633. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10634. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10635. \mid (\key{and}\;\Exp\;\Exp)
  10636. \mid (\key{or}\;\Exp\;\Exp)
  10637. \mid (\key{not}\;\Exp) } \\
  10638. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10639. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  10640. (\key{vector-ref}\;\Exp\;\Int)} \\
  10641. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  10642. \mid (\Exp \; \Exp\ldots) } \\
  10643. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  10644. \mid \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  10645. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10646. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10647. \mid \CWHILE{\Exp}{\Exp} } \\
  10648. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  10649. \LangGrad{} &::=& \gray{\Def\ldots \; \Exp}
  10650. \end{array}
  10651. \]
  10652. \end{minipage}
  10653. }
  10654. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10655. \label{fig:Rgrad-concrete-syntax}
  10656. \end{figure}
  10657. \begin{figure}[tp]
  10658. \centering
  10659. \fbox{
  10660. \begin{minipage}{0.96\textwidth}
  10661. \small
  10662. \[
  10663. \begin{array}{lcl}
  10664. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10665. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  10666. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10667. &\mid& \gray{ \BOOL{\itm{bool}}
  10668. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  10669. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  10670. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  10671. &\mid& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  10672. &\mid& \gray{ \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  10673. &\mid& \gray{ \WHILE{\Exp}{\Exp} } \\
  10674. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  10675. \LangGrad{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10676. \end{array}
  10677. \]
  10678. \end{minipage}
  10679. }
  10680. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  10681. \label{fig:Rgrad-syntax}
  10682. \end{figure}
  10683. Both the type checker and the interpreter for \LangGrad{} require some
  10684. interesting changes to enable gradual typing, which we discuss in the
  10685. next two sections in the context of the \code{map-vec} example from
  10686. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  10687. revised the \code{map-vec} example, omitting the type annotations from
  10688. the \code{add1} function.
  10689. \begin{figure}[btp]
  10690. % gradual_test_9.rkt
  10691. \begin{lstlisting}
  10692. (define (map-vec [f : (Integer -> Integer)]
  10693. [v : (Vector Integer Integer)])
  10694. : (Vector Integer Integer)
  10695. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10696. (define (add1 x) (+ x 1))
  10697. (vector-ref (map-vec add1 (vector 0 41)) 1)
  10698. \end{lstlisting}
  10699. \caption{A partially-typed version of the \code{map-vec} example.}
  10700. \label{fig:gradual-map-vec}
  10701. \end{figure}
  10702. \section{Type Checking \LangGrad{}, Casts, and \LangCast{}}
  10703. \label{sec:gradual-type-check}
  10704. The type checker for \LangGrad{} uses the \code{Any} type for missing
  10705. parameter and return types. For example, the \code{x} parameter of
  10706. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  10707. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  10708. consider the \code{+} operator inside \code{add1}. It expects both
  10709. arguments to have type \code{Integer}, but its first argument \code{x}
  10710. has type \code{Any}. In a gradually typed language, such differences
  10711. are allowed so long as the types are \emph{consistent}, that is, they
  10712. are equal except in places where there is an \code{Any} type. The type
  10713. \code{Any} is consistent with every other type.
  10714. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  10715. \begin{figure}[tbp]
  10716. \begin{lstlisting}
  10717. (define/public (consistent? t1 t2)
  10718. (match* (t1 t2)
  10719. [('Integer 'Integer) #t]
  10720. [('Boolean 'Boolean) #t]
  10721. [('Void 'Void) #t]
  10722. [('Any t2) #t]
  10723. [(t1 'Any) #t]
  10724. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10725. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  10726. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10727. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  10728. (consistent? rt1 rt2))]
  10729. [(other wise) #f]))
  10730. \end{lstlisting}
  10731. \caption{The consistency predicate on types, a method in
  10732. \code{type-check-gradual-class}.}
  10733. \label{fig:consistent}
  10734. \end{figure}
  10735. Returning to the \code{map-vec} example of
  10736. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  10737. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  10738. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  10739. because the two types are consistent. In particular, \code{->} is
  10740. equal to \code{->} and because \code{Any} is consistent with
  10741. \code{Integer}.
  10742. Next consider a program with an error, such as applying the
  10743. \code{map-vec} to a function that sometimes returns a Boolean, as
  10744. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  10745. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  10746. consistent with the type of parameter \code{f} of \code{map-vec}, that
  10747. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  10748. Integer)}. One might say that a gradual type checker is optimistic
  10749. in that it accepts programs that might execute without a runtime type
  10750. error.
  10751. %
  10752. Unfortunately, running this program with input \code{1} triggers an
  10753. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  10754. performs checking at runtime to ensure the integrity of the static
  10755. types, such as the \code{(Integer -> Integer)} annotation on parameter
  10756. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  10757. new \code{Cast} form that is inserted by the type checker. Thus, the
  10758. output of the type checker is a program in the \LangCast{} language, which
  10759. adds \code{Cast} to \LangLoop{}, as shown in
  10760. Figure~\ref{fig:Rgrad-prime-syntax}.
  10761. \begin{figure}[tp]
  10762. \centering
  10763. \fbox{
  10764. \begin{minipage}{0.96\textwidth}
  10765. \small
  10766. \[
  10767. \begin{array}{lcl}
  10768. \Exp &::=& \ldots \mid \CAST{\Exp}{\Type}{\Type} \\
  10769. \LangCast{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10770. \end{array}
  10771. \]
  10772. \end{minipage}
  10773. }
  10774. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  10775. \label{fig:Rgrad-prime-syntax}
  10776. \end{figure}
  10777. \begin{figure}[tbp]
  10778. \begin{lstlisting}
  10779. (define (map-vec [f : (Integer -> Integer)]
  10780. [v : (Vector Integer Integer)])
  10781. : (Vector Integer Integer)
  10782. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10783. (define (add1 x) (+ x 1))
  10784. (define (true) #t)
  10785. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  10786. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  10787. \end{lstlisting}
  10788. \caption{A variant of the \code{map-vec} example with an error.}
  10789. \label{fig:map-vec-maybe-add1}
  10790. \end{figure}
  10791. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  10792. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  10793. inserted every time the type checker sees two types that are
  10794. consistent but not equal. In the \code{add1} function, \code{x} is
  10795. cast to \code{Integer} and the result of the \code{+} is cast to
  10796. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  10797. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  10798. \begin{figure}[btp]
  10799. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10800. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  10801. : (Vector Integer Integer)
  10802. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10803. (define (add1 [x : Any]) : Any
  10804. (cast (+ (cast x Any Integer) 1) Integer Any))
  10805. (define (true) : Any (cast #t Boolean Any))
  10806. (define (maybe-add1 [x : Any]) : Any
  10807. (if (eq? 0 (read)) (add1 x) (true)))
  10808. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  10809. (vector 0 41)) 0)
  10810. \end{lstlisting}
  10811. \caption{Output of type checking \code{map-vec}
  10812. and \code{maybe-add1}.}
  10813. \label{fig:map-vec-cast}
  10814. \end{figure}
  10815. The type checker for \LangGrad{} is defined in
  10816. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  10817. and \ref{fig:type-check-Rgradual-3}.
  10818. \begin{figure}[tbp]
  10819. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10820. (define type-check-gradual-class
  10821. (class type-check-Rwhile-class
  10822. (super-new)
  10823. (inherit operator-types type-predicates)
  10824. (define/override (type-check-exp env)
  10825. (lambda (e)
  10826. (define recur (type-check-exp env))
  10827. (match e
  10828. [(Prim 'vector-length (list e1))
  10829. (define-values (e1^ t) (recur e1))
  10830. (match t
  10831. [`(Vector ,ts ...)
  10832. (values (Prim 'vector-length (list e1^)) 'Integer)]
  10833. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  10834. [(Prim 'vector-ref (list e1 e2))
  10835. (define-values (e1^ t1) (recur e1))
  10836. (define-values (e2^ t2) (recur e2))
  10837. (check-consistent? t2 'Integer e)
  10838. (match t1
  10839. [`(Vector ,ts ...)
  10840. (match e2^
  10841. [(Int i)
  10842. (unless (and (0 . <= . i) (i . < . (length ts)))
  10843. (error 'type-check "invalid index ~a in ~a" i e))
  10844. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10845. [else (define e1^^ (make-cast e1^ t1 'Any))
  10846. (define e2^^ (make-cast e2^ t2 'Integer))
  10847. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  10848. ['Any
  10849. (define e2^^ (make-cast e2^ t2 'Integer))
  10850. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  10851. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10852. [(Prim 'vector-set! (list e1 e2 e3) )
  10853. (define-values (e1^ t1) (recur e1))
  10854. (define-values (e2^ t2) (recur e2))
  10855. (define-values (e3^ t3) (recur e3))
  10856. (check-consistent? t2 'Integer e)
  10857. (match t1
  10858. [`(Vector ,ts ...)
  10859. (match e2^
  10860. [(Int i)
  10861. (unless (and (0 . <= . i) (i . < . (length ts)))
  10862. (error 'type-check "invalid index ~a in ~a" i e))
  10863. (check-consistent? (list-ref ts i) t3 e)
  10864. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  10865. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  10866. [else
  10867. (define e1^^ (make-cast e1^ t1 'Any))
  10868. (define e2^^ (make-cast e2^ t2 'Integer))
  10869. (define e3^^ (make-cast e3^ t3 'Any))
  10870. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  10871. ['Any
  10872. (define e2^^ (make-cast e2^ t2 'Integer))
  10873. (define e3^^ (make-cast e3^ t3 'Any))
  10874. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  10875. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10876. \end{lstlisting}
  10877. \caption{Type checker for the \LangGrad{} language, part 1.}
  10878. \label{fig:type-check-Rgradual-1}
  10879. \end{figure}
  10880. \begin{figure}[tbp]
  10881. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10882. [(Prim 'eq? (list e1 e2))
  10883. (define-values (e1^ t1) (recur e1))
  10884. (define-values (e2^ t2) (recur e2))
  10885. (check-consistent? t1 t2 e)
  10886. (define T (meet t1 t2))
  10887. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  10888. 'Boolean)]
  10889. [(Prim 'not (list e1))
  10890. (define-values (e1^ t1) (recur e1))
  10891. (match t1
  10892. ['Any
  10893. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  10894. (Bool #t) (Bool #f)))]
  10895. [else
  10896. (define-values (t-ret new-es^)
  10897. (type-check-op 'not (list t1) (list e1^) e))
  10898. (values (Prim 'not new-es^) t-ret)])]
  10899. [(Prim 'and (list e1 e2))
  10900. (recur (If e1 e2 (Bool #f)))]
  10901. [(Prim 'or (list e1 e2))
  10902. (define tmp (gensym 'tmp))
  10903. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  10904. [(Prim op es)
  10905. #:when (not (set-member? explicit-prim-ops op))
  10906. (define-values (new-es ts)
  10907. (for/lists (exprs types) ([e es])
  10908. (recur e)))
  10909. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  10910. (values (Prim op new-es^) t-ret)]
  10911. [(If e1 e2 e3)
  10912. (define-values (e1^ T1) (recur e1))
  10913. (define-values (e2^ T2) (recur e2))
  10914. (define-values (e3^ T3) (recur e3))
  10915. (check-consistent? T2 T3 e)
  10916. (match T1
  10917. ['Boolean
  10918. (define Tif (join T2 T3))
  10919. (values (If e1^ (make-cast e2^ T2 Tif)
  10920. (make-cast e3^ T3 Tif)) Tif)]
  10921. ['Any
  10922. (define Tif (meet T2 T3))
  10923. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  10924. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  10925. Tif)]
  10926. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  10927. [(HasType e1 T)
  10928. (define-values (e1^ T1) (recur e1))
  10929. (check-consistent? T1 T)
  10930. (values (make-cast e1^ T1 T) T)]
  10931. [(SetBang x e1)
  10932. (define-values (e1^ T1) (recur e1))
  10933. (define varT (dict-ref env x))
  10934. (check-consistent? T1 varT e)
  10935. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  10936. [(WhileLoop e1 e2)
  10937. (define-values (e1^ T1) (recur e1))
  10938. (check-consistent? T1 'Boolean e)
  10939. (define-values (e2^ T2) ((type-check-exp env) e2))
  10940. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  10941. \end{lstlisting}
  10942. \caption{Type checker for the \LangGrad{} language, part 2.}
  10943. \label{fig:type-check-Rgradual-2}
  10944. \end{figure}
  10945. \begin{figure}[tbp]
  10946. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10947. [(Apply e1 e2s)
  10948. (define-values (e1^ T1) (recur e1))
  10949. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  10950. (match T1
  10951. [`(,T1ps ... -> ,T1rt)
  10952. (for ([T2 T2s] [Tp T1ps])
  10953. (check-consistent? T2 Tp e))
  10954. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  10955. (make-cast e2 src tgt)))
  10956. (values (Apply e1^ e2s^^) T1rt)]
  10957. [`Any
  10958. (define e1^^ (make-cast e1^ 'Any
  10959. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  10960. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  10961. (make-cast e2 src 'Any)))
  10962. (values (Apply e1^^ e2s^^) 'Any)]
  10963. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  10964. [(Lambda params Tr e1)
  10965. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  10966. (match p
  10967. [`[,x : ,T] (values x T)]
  10968. [(? symbol? x) (values x 'Any)])))
  10969. (define-values (e1^ T1)
  10970. ((type-check-exp (append (map cons xs Ts) env)) e1))
  10971. (check-consistent? Tr T1 e)
  10972. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  10973. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  10974. [else ((super type-check-exp env) e)]
  10975. )))
  10976. \end{lstlisting}
  10977. \caption{Type checker for the \LangGrad{} language, part 3.}
  10978. \label{fig:type-check-Rgradual-3}
  10979. \end{figure}
  10980. \begin{figure}[tbp]
  10981. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10982. (define/public (join t1 t2)
  10983. (match* (t1 t2)
  10984. [('Integer 'Integer) 'Integer]
  10985. [('Boolean 'Boolean) 'Boolean]
  10986. [('Void 'Void) 'Void]
  10987. [('Any t2) t2]
  10988. [(t1 'Any) t1]
  10989. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10990. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  10991. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10992. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  10993. -> ,(join rt1 rt2))]))
  10994. (define/public (meet t1 t2)
  10995. (match* (t1 t2)
  10996. [('Integer 'Integer) 'Integer]
  10997. [('Boolean 'Boolean) 'Boolean]
  10998. [('Void 'Void) 'Void]
  10999. [('Any t2) 'Any]
  11000. [(t1 'Any) 'Any]
  11001. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11002. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  11003. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11004. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  11005. -> ,(meet rt1 rt2))]))
  11006. (define/public (make-cast e src tgt)
  11007. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  11008. (define/public (check-consistent? t1 t2 e)
  11009. (unless (consistent? t1 t2)
  11010. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  11011. (define/override (type-check-op op arg-types args e)
  11012. (match (dict-ref (operator-types) op)
  11013. [`(,param-types . ,return-type)
  11014. (for ([at arg-types] [pt param-types])
  11015. (check-consistent? at pt e))
  11016. (values return-type
  11017. (for/list ([e args] [s arg-types] [t param-types])
  11018. (make-cast e s t)))]
  11019. [else (error 'type-check-op "unrecognized ~a" op)]))
  11020. (define explicit-prim-ops
  11021. (set-union
  11022. (type-predicates)
  11023. (set 'procedure-arity 'eq?
  11024. 'vector 'vector-length 'vector-ref 'vector-set!
  11025. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  11026. (define/override (fun-def-type d)
  11027. (match d
  11028. [(Def f params rt info body)
  11029. (define ps
  11030. (for/list ([p params])
  11031. (match p
  11032. [`[,x : ,T] T]
  11033. [(? symbol?) 'Any]
  11034. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  11035. `(,@ps -> ,rt)]
  11036. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  11037. \end{lstlisting}
  11038. \caption{Auxiliary functions for type checking \LangGrad{}.}
  11039. \label{fig:type-check-Rgradual-aux}
  11040. \end{figure}
  11041. \clearpage
  11042. \section{Interpreting \LangCast{}}
  11043. \label{sec:interp-casts}
  11044. The runtime behavior of first-order casts is straightforward, that is,
  11045. casts involving simple types such as \code{Integer} and
  11046. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  11047. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  11048. puts the integer into a tagged value
  11049. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  11050. \code{Integer} is accomplished with the \code{Project} operator, that
  11051. is, by checking the value's tag and either retrieving the underlying
  11052. integer or signaling an error if it the tag is not the one for
  11053. integers (Figure~\ref{fig:apply-project}).
  11054. %
  11055. Things get more interesting for higher-order casts, that is, casts
  11056. involving function or vector types.
  11057. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  11058. Any)} to \code{(Integer -> Integer)}. When a function flows through
  11059. this cast at runtime, we can't know in general whether the function
  11060. will always return an integer.\footnote{Predicting the return value of
  11061. a function is equivalent to the halting problem, which is
  11062. undecidable.} The \LangCast{} interpreter therefore delays the checking
  11063. of the cast until the function is applied. This is accomplished by
  11064. wrapping \code{maybe-add1} in a new function that casts its parameter
  11065. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  11066. casts the return value from \code{Any} to \code{Integer}.
  11067. Turning our attention to casts involving vector types, we consider the
  11068. example in Figure~\ref{fig:map-vec-bang} that defines a
  11069. partially-typed version of \code{map-vec} whose parameter \code{v} has
  11070. type \code{(Vector Any Any)} and that updates \code{v} in place
  11071. instead of returning a new vector. So we name this function
  11072. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  11073. the type checker inserts a cast from \code{(Vector Integer Integer)}
  11074. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  11075. cast between vector types would be a build a new vector whose elements
  11076. are the result of casting each of the original elements to the
  11077. appropriate target type. However, this approach is only valid for
  11078. immutable vectors; and our vectors are mutable. In the example of
  11079. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  11080. the updates inside of \code{map-vec!} would happen to the new vector
  11081. and not the original one.
  11082. \begin{figure}[tbp]
  11083. % gradual_test_11.rkt
  11084. \begin{lstlisting}
  11085. (define (map-vec! [f : (Any -> Any)]
  11086. [v : (Vector Any Any)]) : Void
  11087. (begin
  11088. (vector-set! v 0 (f (vector-ref v 0)))
  11089. (vector-set! v 1 (f (vector-ref v 1)))))
  11090. (define (add1 x) (+ x 1))
  11091. (let ([v (vector 0 41)])
  11092. (begin (map-vec! add1 v) (vector-ref v 1)))
  11093. \end{lstlisting}
  11094. \caption{An example involving casts on vectors.}
  11095. \label{fig:map-vec-bang}
  11096. \end{figure}
  11097. Instead the interpreter needs to create a new kind of value, a
  11098. \emph{vector proxy}, that intercepts every vector operation. On a
  11099. read, the proxy reads from the underlying vector and then applies a
  11100. cast to the resulting value. On a write, the proxy casts the argument
  11101. value and then performs the write to the underlying vector. For the
  11102. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  11103. \code{0} from \code{Integer} to \code{Any}. For the first
  11104. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  11105. to \code{Integer}.
  11106. The final category of cast that we need to consider are casts between
  11107. the \code{Any} type and either a function or a vector
  11108. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  11109. in which parameter \code{v} does not have a type annotation, so it is
  11110. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  11111. type \code{(Vector Integer Integer)} so the type checker inserts a
  11112. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  11113. thought is to use \code{Inject}, but that doesn't work because
  11114. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  11115. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  11116. to \code{Any}.
  11117. \begin{figure}[tbp]
  11118. \begin{lstlisting}
  11119. (define (map-vec! [f : (Any -> Any)] v) : Void
  11120. (begin
  11121. (vector-set! v 0 (f (vector-ref v 0)))
  11122. (vector-set! v 1 (f (vector-ref v 1)))))
  11123. (define (add1 x) (+ x 1))
  11124. (let ([v (vector 0 41)])
  11125. (begin (map-vec! add1 v) (vector-ref v 1)))
  11126. \end{lstlisting}
  11127. \caption{Casting a vector to \code{Any}.}
  11128. \label{fig:map-vec-any}
  11129. \end{figure}
  11130. The \LangCast{} interpreter uses an auxiliary function named
  11131. \code{apply-cast} to cast a value from a source type to a target type,
  11132. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  11133. of the kinds of casts that we've discussed in this section.
  11134. \begin{figure}[tbp]
  11135. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11136. (define/public (apply-cast v s t)
  11137. (match* (s t)
  11138. [(t1 t2) #:when (equal? t1 t2) v]
  11139. [('Any t2)
  11140. (match t2
  11141. [`(,ts ... -> ,rt)
  11142. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11143. (define v^ (apply-project v any->any))
  11144. (apply-cast v^ any->any `(,@ts -> ,rt))]
  11145. [`(Vector ,ts ...)
  11146. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11147. (define v^ (apply-project v vec-any))
  11148. (apply-cast v^ vec-any `(Vector ,@ts))]
  11149. [else (apply-project v t2)])]
  11150. [(t1 'Any)
  11151. (match t1
  11152. [`(,ts ... -> ,rt)
  11153. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11154. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  11155. (apply-inject v^ (any-tag any->any))]
  11156. [`(Vector ,ts ...)
  11157. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11158. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  11159. (apply-inject v^ (any-tag vec-any))]
  11160. [else (apply-inject v (any-tag t1))])]
  11161. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11162. (define x (gensym 'x))
  11163. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  11164. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  11165. (define cast-writes
  11166. (for/list ([t1 ts1] [t2 ts2])
  11167. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  11168. `(vector-proxy ,(vector v (apply vector cast-reads)
  11169. (apply vector cast-writes)))]
  11170. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11171. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  11172. `(function ,xs ,(Cast
  11173. (Apply (Value v)
  11174. (for/list ([x xs][t1 ts1][t2 ts2])
  11175. (Cast (Var x) t2 t1)))
  11176. rt1 rt2) ())]
  11177. ))
  11178. \end{lstlisting}
  11179. \caption{The \code{apply-cast} auxiliary method.}
  11180. \label{fig:apply-cast}
  11181. \end{figure}
  11182. The interpreter for \LangCast{} is defined in
  11183. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  11184. dispatching to \code{apply-cast}. To handle the addition of vector
  11185. proxies, we update the vector primitives in \code{interp-op} using the
  11186. functions in Figure~\ref{fig:guarded-vector}.
  11187. \begin{figure}[tbp]
  11188. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11189. (define interp-Rcast-class
  11190. (class interp-Rwhile-class
  11191. (super-new)
  11192. (inherit apply-fun apply-inject apply-project)
  11193. (define/override (interp-op op)
  11194. (match op
  11195. ['vector-length guarded-vector-length]
  11196. ['vector-ref guarded-vector-ref]
  11197. ['vector-set! guarded-vector-set!]
  11198. ['any-vector-ref (lambda (v i)
  11199. (match v [`(tagged ,v^ ,tg)
  11200. (guarded-vector-ref v^ i)]))]
  11201. ['any-vector-set! (lambda (v i a)
  11202. (match v [`(tagged ,v^ ,tg)
  11203. (guarded-vector-set! v^ i a)]))]
  11204. ['any-vector-length (lambda (v)
  11205. (match v [`(tagged ,v^ ,tg)
  11206. (guarded-vector-length v^)]))]
  11207. [else (super interp-op op)]
  11208. ))
  11209. (define/override ((interp-exp env) e)
  11210. (define (recur e) ((interp-exp env) e))
  11211. (match e
  11212. [(Value v) v]
  11213. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  11214. [else ((super interp-exp env) e)]))
  11215. ))
  11216. (define (interp-Rcast p)
  11217. (send (new interp-Rcast-class) interp-program p))
  11218. \end{lstlisting}
  11219. \caption{The interpreter for \LangCast{}.}
  11220. \label{fig:interp-Rcast}
  11221. \end{figure}
  11222. \begin{figure}[tbp]
  11223. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11224. (define (guarded-vector-ref vec i)
  11225. (match vec
  11226. [`(vector-proxy ,proxy)
  11227. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  11228. (define rd (vector-ref (vector-ref proxy 1) i))
  11229. (apply-fun rd (list val) 'guarded-vector-ref)]
  11230. [else (vector-ref vec i)]))
  11231. (define (guarded-vector-set! vec i arg)
  11232. (match vec
  11233. [`(vector-proxy ,proxy)
  11234. (define wr (vector-ref (vector-ref proxy 2) i))
  11235. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  11236. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  11237. [else (vector-set! vec i arg)]))
  11238. (define (guarded-vector-length vec)
  11239. (match vec
  11240. [`(vector-proxy ,proxy)
  11241. (guarded-vector-length (vector-ref proxy 0))]
  11242. [else (vector-length vec)]))
  11243. \end{lstlisting}
  11244. \caption{The guarded-vector auxiliary functions.}
  11245. \label{fig:guarded-vector}
  11246. \end{figure}
  11247. \section{Lower Casts}
  11248. \label{sec:lower-casts}
  11249. The next step in the journey towards x86 is the \code{lower-casts}
  11250. pass that translates the casts in \LangCast{} to the lower-level
  11251. \code{Inject} and \code{Project} operators and a new operator for
  11252. creating vector proxies, extending the \LangLoop{} language to create
  11253. \LangProxy{}. We recommend creating an auxiliary function named
  11254. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  11255. and a target type, and translates it to expression in \LangProxy{} that has
  11256. the same behavior as casting the expression from the source to the
  11257. target type in the interpreter.
  11258. The \code{lower-cast} function can follow a code structure similar to
  11259. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  11260. the interpreter for \LangCast{} because it must handle the same cases as
  11261. \code{apply-cast} and it needs to mimic the behavior of
  11262. \code{apply-cast}. The most interesting cases are those concerning the
  11263. casts between two vector types and between two function types.
  11264. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  11265. type to another vector type is accomplished by creating a proxy that
  11266. intercepts the operations on the underlying vector. Here we make the
  11267. creation of the proxy explicit with the \code{vector-proxy} primitive
  11268. operation. It takes three arguments, the first is an expression for
  11269. the vector, the second is a vector of functions for casting an element
  11270. that is being read from the vector, and the third is a vector of
  11271. functions for casting an element that is being written to the vector.
  11272. You can create the functions using \code{Lambda}. Also, as we shall
  11273. see in the next section, we need to differentiate these vectors from
  11274. the user-created ones, so we recommend using a new primitive operator
  11275. named \code{raw-vector} instead of \code{vector} to create these
  11276. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  11277. the output of \code{lower-casts} on the example in
  11278. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  11279. integers to a vector of \code{Any}.
  11280. \begin{figure}[tbp]
  11281. \begin{lstlisting}
  11282. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  11283. (begin
  11284. (vector-set! v 0 (f (vector-ref v 0)))
  11285. (vector-set! v 1 (f (vector-ref v 1)))))
  11286. (define (add1 [x : Any]) : Any
  11287. (inject (+ (project x Integer) 1) Integer))
  11288. (let ([v (vector 0 41)])
  11289. (begin
  11290. (map-vec! add1 (vector-proxy v
  11291. (raw-vector (lambda: ([x9 : Integer]) : Any
  11292. (inject x9 Integer))
  11293. (lambda: ([x9 : Integer]) : Any
  11294. (inject x9 Integer)))
  11295. (raw-vector (lambda: ([x9 : Any]) : Integer
  11296. (project x9 Integer))
  11297. (lambda: ([x9 : Any]) : Integer
  11298. (project x9 Integer)))))
  11299. (vector-ref v 1)))
  11300. \end{lstlisting}
  11301. \caption{Output of \code{lower-casts} on the example in
  11302. Figure~\ref{fig:map-vec-bang}.}
  11303. \label{fig:map-vec-bang-lower-cast}
  11304. \end{figure}
  11305. A cast from one function type to another function type is accomplished
  11306. by generating a \code{Lambda} whose parameter and return types match
  11307. the target function type. The body of the \code{Lambda} should cast
  11308. the parameters from the target type to the source type (yes,
  11309. backwards! functions are contravariant\index{contravariant} in the
  11310. parameters), then call the underlying function, and finally cast the
  11311. result from the source return type to the target return type.
  11312. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  11313. \code{lower-casts} pass on the \code{map-vec} example in
  11314. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  11315. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  11316. \begin{figure}[tbp]
  11317. \begin{lstlisting}
  11318. (define (map-vec [f : (Integer -> Integer)]
  11319. [v : (Vector Integer Integer)])
  11320. : (Vector Integer Integer)
  11321. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11322. (define (add1 [x : Any]) : Any
  11323. (inject (+ (project x Integer) 1) Integer))
  11324. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  11325. (project (add1 (inject x9 Integer)) Integer))
  11326. (vector 0 41)) 1)
  11327. \end{lstlisting}
  11328. \caption{Output of \code{lower-casts} on the example in
  11329. Figure~\ref{fig:gradual-map-vec}.}
  11330. \label{fig:map-vec-lower-cast}
  11331. \end{figure}
  11332. \section{Differentiate Proxies}
  11333. \label{sec:differentiate-proxies}
  11334. So far the job of differentiating vectors and vector proxies has been
  11335. the job of the interpreter. For example, the interpreter for \LangCast{}
  11336. implements \code{vector-ref} using the \code{guarded-vector-ref}
  11337. function in Figure~\ref{fig:guarded-vector}. In the
  11338. \code{differentiate-proxies} pass we shift this responsibility to the
  11339. generated code.
  11340. We begin by designing the output language $R^p_8$. In
  11341. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  11342. proxies. In $R^p_8$ we return the \code{Vector} type to
  11343. its original meaning, as the type of real vectors, and we introduce a
  11344. new type, \code{PVector}, whose values can be either real vectors or
  11345. vector proxies. This new type comes with a suite of new primitive
  11346. operations for creating and using values of type \code{PVector}. We
  11347. don't need to introduce a new type to represent vector proxies. A
  11348. proxy is represented by a vector containing three things: 1) the
  11349. underlying vector, 2) a vector of functions for casting elements that
  11350. are read from the vector, and 3) a vector of functions for casting
  11351. values to be written to the vector. So we define the following
  11352. abbreviation for the type of a vector proxy:
  11353. \[
  11354. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  11355. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  11356. \to (\key{PVector}~ T' \ldots)
  11357. \]
  11358. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  11359. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  11360. %
  11361. Next we describe each of the new primitive operations.
  11362. \begin{description}
  11363. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  11364. (\key{PVector} $T \ldots$)]\ \\
  11365. %
  11366. This operation brands a vector as a value of the \code{PVector} type.
  11367. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  11368. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  11369. %
  11370. This operation brands a vector proxy as value of the \code{PVector} type.
  11371. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  11372. \code{Boolean}] \ \\
  11373. %
  11374. returns true if the value is a vector proxy and false if it is a
  11375. real vector.
  11376. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  11377. (\key{Vector} $T \ldots$)]\ \\
  11378. %
  11379. Assuming that the input is a vector (and not a proxy), this
  11380. operation returns the vector.
  11381. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  11382. $\to$ \code{Boolean}]\ \\
  11383. %
  11384. Given a vector proxy, this operation returns the length of the
  11385. underlying vector.
  11386. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  11387. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  11388. %
  11389. Given a vector proxy, this operation returns the $i$th element of
  11390. the underlying vector.
  11391. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  11392. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  11393. proxy, this operation writes a value to the $i$th element of the
  11394. underlying vector.
  11395. \end{description}
  11396. Now to discuss the translation that differentiates vectors from
  11397. proxies. First, every type annotation in the program must be
  11398. translated (recursively) to replace \code{Vector} with \code{PVector}.
  11399. Next, we must insert uses of \code{PVector} operations in the
  11400. appropriate places. For example, we wrap every vector creation with an
  11401. \code{inject-vector}.
  11402. \begin{lstlisting}
  11403. (vector |$e_1 \ldots e_n$|)
  11404. |$\Rightarrow$|
  11405. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  11406. \end{lstlisting}
  11407. The \code{raw-vector} operator that we introduced in the previous
  11408. section does not get injected.
  11409. \begin{lstlisting}
  11410. (raw-vector |$e_1 \ldots e_n$|)
  11411. |$\Rightarrow$|
  11412. (vector |$e'_1 \ldots e'_n$|)
  11413. \end{lstlisting}
  11414. The \code{vector-proxy} primitive translates as follows.
  11415. \begin{lstlisting}
  11416. (vector-proxy |$e_1~e_2~e_3$|)
  11417. |$\Rightarrow$|
  11418. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  11419. \end{lstlisting}
  11420. We translate the vector operations into conditional expressions that
  11421. check whether the value is a proxy and then dispatch to either the
  11422. appropriate proxy vector operation or the regular vector operation.
  11423. For example, the following is the translation for \code{vector-ref}.
  11424. \begin{lstlisting}
  11425. (vector-ref |$e_1$| |$i$|)
  11426. |$\Rightarrow$|
  11427. (let ([|$v~e_1$|])
  11428. (if (proxy? |$v$|)
  11429. (proxy-vector-ref |$v$| |$i$|)
  11430. (vector-ref (project-vector |$v$|) |$i$|)
  11431. \end{lstlisting}
  11432. Note in the case of a real vector, we must apply \code{project-vector}
  11433. before the \code{vector-ref}.
  11434. \section{Reveal Casts}
  11435. \label{sec:reveal-casts-gradual}
  11436. Recall that the \code{reveal-casts} pass
  11437. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  11438. \code{Inject} and \code{Project} into lower-level operations. In
  11439. particular, \code{Project} turns into a conditional expression that
  11440. inspects the tag and retrieves the underlying value. Here we need to
  11441. augment the translation of \code{Project} to handle the situation when
  11442. the target type is \code{PVector}. Instead of using
  11443. \code{vector-length} we need to use \code{proxy-vector-length}.
  11444. \begin{lstlisting}
  11445. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  11446. |$\Rightarrow$|
  11447. (let |$\itm{tmp}$| |$e'$|
  11448. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  11449. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  11450. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  11451. (exit)))
  11452. \end{lstlisting}
  11453. \section{Closure Conversion}
  11454. \label{sec:closure-conversion-gradual}
  11455. The closure conversion pass only requires one minor adjustment. The
  11456. auxiliary function that translates type annotations needs to be
  11457. updated to handle the \code{PVector} type.
  11458. \section{Explicate Control}
  11459. \label{sec:explicate-control-gradual}
  11460. Update the \code{explicate-control} pass to handle the new primitive
  11461. operations on the \code{PVector} type.
  11462. \section{Select Instructions}
  11463. \label{sec:select-instructions-gradual}
  11464. Recall that the \code{select-instructions} pass is responsible for
  11465. lowering the primitive operations into x86 instructions. So we need
  11466. to translate the new \code{PVector} operations to x86. To do so, the
  11467. first question we need to answer is how will we differentiate the two
  11468. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  11469. We need just one bit to accomplish this, and use the bit in position
  11470. $57$ of the 64-bit tag at the front of every vector (see
  11471. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  11472. for \code{inject-vector} we leave it that way.
  11473. \begin{lstlisting}
  11474. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  11475. |$\Rightarrow$|
  11476. movq |$e'_1$|, |$\itm{lhs'}$|
  11477. \end{lstlisting}
  11478. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  11479. \begin{lstlisting}
  11480. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  11481. |$\Rightarrow$|
  11482. movq |$e'_1$|, %r11
  11483. movq |$(1 << 57)$|, %rax
  11484. orq 0(%r11), %rax
  11485. movq %rax, 0(%r11)
  11486. movq %r11, |$\itm{lhs'}$|
  11487. \end{lstlisting}
  11488. The \code{proxy?} operation consumes the information so carefully
  11489. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  11490. isolates the $57$th bit to tell whether the value is a real vector or
  11491. a proxy.
  11492. \begin{lstlisting}
  11493. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  11494. |$\Rightarrow$|
  11495. movq |$e_1'$|, %r11
  11496. movq 0(%r11), %rax
  11497. sarq $57, %rax
  11498. andq $1, %rax
  11499. movq %rax, |$\itm{lhs'}$|
  11500. \end{lstlisting}
  11501. The \code{project-vector} operation is straightforward to translate,
  11502. so we leave it up to the reader.
  11503. Regarding the \code{proxy-vector} operations, the runtime provides
  11504. procedures that implement them (they are recursive functions!) so
  11505. here we simply need to translate these vector operations into the
  11506. appropriate function call. For example, here is the translation for
  11507. \code{proxy-vector-ref}.
  11508. \begin{lstlisting}
  11509. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  11510. |$\Rightarrow$|
  11511. movq |$e_1'$|, %rdi
  11512. movq |$e_2'$|, %rsi
  11513. callq proxy_vector_ref
  11514. movq %rax, |$\itm{lhs'}$|
  11515. \end{lstlisting}
  11516. We have another batch of vector operations to deal with, those for the
  11517. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  11518. \code{any-vector-ref} when there is a \code{vector-ref} on something
  11519. of type \code{Any}, and similarly for \code{any-vector-set!} and
  11520. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  11521. Section~\ref{sec:select-Rany} we selected instructions for these
  11522. operations based on the idea that the underlying value was a real
  11523. vector. But in the current setting, the underlying value is of type
  11524. \code{PVector}. So \code{any-vector-ref} can be translates to
  11525. pseudo-x86 as follows. We begin by projecting the underlying value out
  11526. of the tagged value and then call the \code{proxy\_vector\_ref}
  11527. procedure in the runtime.
  11528. \begin{lstlisting}
  11529. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  11530. movq |$\neg 111$|, %rdi
  11531. andq |$e_1'$|, %rdi
  11532. movq |$e_2'$|, %rsi
  11533. callq proxy_vector_ref
  11534. movq %rax, |$\itm{lhs'}$|
  11535. \end{lstlisting}
  11536. The \code{any-vector-set!} and \code{any-vector-length} operators can
  11537. be translated in a similar way.
  11538. \begin{exercise}\normalfont
  11539. Implement a compiler for the gradually-typed \LangGrad{} language by
  11540. extending and adapting your compiler for \LangLoop{}. Create 10 new
  11541. partially-typed test programs. In addition to testing with these
  11542. new programs, also test your compiler on all the tests for \LangLoop{}
  11543. and tests for \LangDyn{}. Sometimes you may get a type checking error
  11544. on the \LangDyn{} programs but you can adapt them by inserting
  11545. a cast to the \code{Any} type around each subexpression
  11546. causing a type error. While \LangDyn{} doesn't have explicit casts,
  11547. you can induce one by wrapping the subexpression \code{e}
  11548. with a call to an un-annotated identity function, like this:
  11549. \code{((lambda (x) x) e)}.
  11550. \end{exercise}
  11551. \begin{figure}[p]
  11552. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11553. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  11554. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  11555. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  11556. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  11557. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  11558. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  11559. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  11560. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  11561. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  11562. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  11563. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  11564. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  11565. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  11566. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  11567. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11568. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11569. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11570. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11571. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11572. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11573. \path[->,bend right=15] (Rgradual) edge [above] node
  11574. {\ttfamily\footnotesize type-check} (Rgradualp);
  11575. \path[->,bend right=15] (Rgradualp) edge [above] node
  11576. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  11577. \path[->,bend right=15] (Rwhilepp) edge [right] node
  11578. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  11579. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  11580. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  11581. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  11582. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  11583. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  11584. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  11585. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  11586. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  11587. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  11588. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11589. \path[->,bend left=15] (F1-1) edge [below] node
  11590. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11591. \path[->,bend right=15] (F1-2) edge [above] node
  11592. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11593. \path[->,bend right=15] (F1-3) edge [above] node
  11594. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11595. \path[->,bend right=15] (F1-4) edge [above] node
  11596. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11597. \path[->,bend right=15] (F1-5) edge [right] node
  11598. {\ttfamily\footnotesize explicate-control} (C3-2);
  11599. \path[->,bend left=15] (C3-2) edge [left] node
  11600. {\ttfamily\footnotesize select-instr.} (x86-2);
  11601. \path[->,bend right=15] (x86-2) edge [left] node
  11602. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11603. \path[->,bend right=15] (x86-2-1) edge [below] node
  11604. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11605. \path[->,bend right=15] (x86-2-2) edge [left] node
  11606. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11607. \path[->,bend left=15] (x86-3) edge [above] node
  11608. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11609. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11610. \end{tikzpicture}
  11611. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  11612. \label{fig:Rgradual-passes}
  11613. \end{figure}
  11614. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  11615. for the compilation of \LangGrad{}.
  11616. \section{Further Reading}
  11617. This chapter just scratches the surface of gradual typing. The basic
  11618. approach described here is missing two key ingredients that one would
  11619. want in a implementation of gradual typing: blame
  11620. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  11621. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  11622. problem addressed by blame tracking is that when a cast on a
  11623. higher-order value fails, it often does so at a point in the program
  11624. that is far removed from the original cast. Blame tracking is a
  11625. technique for propagating extra information through casts and proxies
  11626. so that when a cast fails, the error message can point back to the
  11627. original location of the cast in the source program.
  11628. The problem addressed by space-efficient casts also relates to
  11629. higher-order casts. It turns out that in partially typed programs, a
  11630. function or vector can flow through very-many casts at runtime. With
  11631. the approach described in this chapter, each cast adds another
  11632. \code{lambda} wrapper or a vector proxy. Not only does this take up
  11633. considerable space, but it also makes the function calls and vector
  11634. operations slow. For example, a partially-typed version of quicksort
  11635. could, in the worst case, build a chain of proxies of length $O(n)$
  11636. around the vector, changing the overall time complexity of the
  11637. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  11638. solution to this problem by representing casts using the coercion
  11639. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  11640. long chains of proxies by compressing them into a concise normal
  11641. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  11642. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  11643. the Grift compiler.
  11644. \begin{center}
  11645. \url{https://github.com/Gradual-Typing/Grift}
  11646. \end{center}
  11647. There are also interesting interactions between gradual typing and
  11648. other language features, such as parametetric polymorphism,
  11649. information-flow types, and type inference, to name a few. We
  11650. recommend the reader to the online gradual typing bibliography:
  11651. \begin{center}
  11652. \url{http://samth.github.io/gradual-typing-bib/}
  11653. \end{center}
  11654. % TODO: challenge problem:
  11655. % type analysis and type specialization?
  11656. % coercions?
  11657. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11658. \chapter{Parametric Polymorphism}
  11659. \label{ch:Rpoly}
  11660. \index{parametric polymorphism}
  11661. \index{generics}
  11662. This chapter studies the compilation of parametric
  11663. polymorphism\index{parametric polymorphism}
  11664. (aka. generics\index{generics}) in the subset \LangPoly{} of Typed
  11665. Racket. Parametric polymorphism enables improved code reuse by
  11666. parameterizing functions and data structures with respect to the types
  11667. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  11668. revisits the \code{map-vec} example but this time gives it a more
  11669. fitting type. This \code{map-vec} function is parameterized with
  11670. respect to the element type of the vector. The type of \code{map-vec}
  11671. is the following polymorphic type as specified by the \code{All} and
  11672. the type parameter \code{a}.
  11673. \begin{lstlisting}
  11674. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11675. \end{lstlisting}
  11676. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  11677. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  11678. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  11679. \code{a}, but we could have just as well applied \code{map-vec} to a
  11680. vector of Booleans (and a function on Booleans).
  11681. \begin{figure}[tbp]
  11682. % poly_test_2.rkt
  11683. \begin{lstlisting}
  11684. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  11685. (define (map-vec f v)
  11686. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11687. (define (add1 [x : Integer]) : Integer (+ x 1))
  11688. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11689. \end{lstlisting}
  11690. \caption{The \code{map-vec} example using parametric polymorphism.}
  11691. \label{fig:map-vec-poly}
  11692. \end{figure}
  11693. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  11694. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  11695. syntax. We add a second form for function definitions in which a type
  11696. declaration comes before the \code{define}. In the abstract syntax,
  11697. the return type in the \code{Def} is \code{Any}, but that should be
  11698. ignored in favor of the return type in the type declaration. (The
  11699. \code{Any} comes from using the same parser as in
  11700. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  11701. enables the use of an \code{All} type for a function, thereby making
  11702. it polymorphic. The grammar for types is extended to include
  11703. polymorphic types and type variables.
  11704. \begin{figure}[tp]
  11705. \centering
  11706. \fbox{
  11707. \begin{minipage}{0.96\textwidth}
  11708. \small
  11709. \[
  11710. \begin{array}{lcl}
  11711. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11712. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  11713. &\mid& \LP\key{:}~\Var~\Type\RP \\
  11714. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  11715. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  11716. \end{array}
  11717. \]
  11718. \end{minipage}
  11719. }
  11720. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  11721. (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  11722. \label{fig:Rpoly-concrete-syntax}
  11723. \end{figure}
  11724. \begin{figure}[tp]
  11725. \centering
  11726. \fbox{
  11727. \begin{minipage}{0.96\textwidth}
  11728. \small
  11729. \[
  11730. \begin{array}{lcl}
  11731. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11732. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11733. &\mid& \DECL{\Var}{\Type} \\
  11734. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  11735. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11736. \end{array}
  11737. \]
  11738. \end{minipage}
  11739. }
  11740. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  11741. (Figure~\ref{fig:Rwhile-syntax}).}
  11742. \label{fig:Rpoly-syntax}
  11743. \end{figure}
  11744. By including polymorphic types in the $\Type$ non-terminal we choose
  11745. to make them first-class which has interesting repercussions on the
  11746. compiler. Many languages with polymorphism, such as
  11747. C++~\citep{stroustrup88:_param_types} and Standard
  11748. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  11749. it is useful to see an example of first-class polymorphism. In
  11750. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  11751. whose parameter is a polymorphic function. The occurrence of a
  11752. polymorphic type underneath a function type is enabled by the normal
  11753. recursive structure of the grammar for $\Type$ and the categorization
  11754. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  11755. applies the polymorphic function to a Boolean and to an integer.
  11756. \begin{figure}[tbp]
  11757. \begin{lstlisting}
  11758. (: apply-twice ((All (b) (b -> b)) -> Integer))
  11759. (define (apply-twice f)
  11760. (if (f #t) (f 42) (f 777)))
  11761. (: id (All (a) (a -> a)))
  11762. (define (id x) x)
  11763. (apply-twice id)
  11764. \end{lstlisting}
  11765. \caption{An example illustrating first-class polymorphism.}
  11766. \label{fig:apply-twice}
  11767. \end{figure}
  11768. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  11769. three new responsibilities (compared to \LangLoop{}). The type checking of
  11770. function application is extended to handle the case where the operator
  11771. expression is a polymorphic function. In that case the type arguments
  11772. are deduced by matching the type of the parameters with the types of
  11773. the arguments.
  11774. %
  11775. The \code{match-types} auxiliary function carries out this deduction
  11776. by recursively descending through a parameter type \code{pt} and the
  11777. corresponding argument type \code{at}, making sure that they are equal
  11778. except when there is a type parameter on the left (in the parameter
  11779. type). If it's the first time that the type parameter has been
  11780. encountered, then the algorithm deduces an association of the type
  11781. parameter to the corresponding type on the right (in the argument
  11782. type). If it's not the first time that the type parameter has been
  11783. encountered, the algorithm looks up its deduced type and makes sure
  11784. that it is equal to the type on the right.
  11785. %
  11786. Once the type arguments are deduced, the operator expression is
  11787. wrapped in an \code{Inst} AST node (for instantiate) that records the
  11788. type of the operator, but more importantly, records the deduced type
  11789. arguments. The return type of the application is the return type of
  11790. the polymorphic function, but with the type parameters replaced by the
  11791. deduced type arguments, using the \code{subst-type} function.
  11792. The second responsibility of the type checker is extending the
  11793. function \code{type-equal?} to handle the \code{All} type. This is
  11794. not quite a simple as equal on other types, such as function and
  11795. vector types, because two polymorphic types can be syntactically
  11796. different even though they are equivalent types. For example,
  11797. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  11798. Two polymorphic types should be considered equal if they differ only
  11799. in the choice of the names of the type parameters. The
  11800. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  11801. renames the type parameters of the first type to match the type
  11802. parameters of the second type.
  11803. The third responsibility of the type checker is making sure that only
  11804. defined type variables appear in type annotations. The
  11805. \code{check-well-formed} function defined in
  11806. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  11807. sure that each type variable has been defined.
  11808. The output language of the type checker is \LangInst{}, defined in
  11809. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  11810. declaration and polymorphic function into a single definition, using
  11811. the \code{Poly} form, to make polymorphic functions more convenient to
  11812. process in next pass of the compiler.
  11813. \begin{figure}[tp]
  11814. \centering
  11815. \fbox{
  11816. \begin{minipage}{0.96\textwidth}
  11817. \small
  11818. \[
  11819. \begin{array}{lcl}
  11820. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11821. \Exp &::=& \ldots \mid \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  11822. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11823. &\mid& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  11824. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11825. \end{array}
  11826. \]
  11827. \end{minipage}
  11828. }
  11829. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  11830. (Figure~\ref{fig:Rwhile-syntax}).}
  11831. \label{fig:Rpoly-prime-syntax}
  11832. \end{figure}
  11833. The output of the type checker on the polymorphic \code{map-vec}
  11834. example is listed in Figure~\ref{fig:map-vec-type-check}.
  11835. \begin{figure}[tbp]
  11836. % poly_test_2.rkt
  11837. \begin{lstlisting}
  11838. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  11839. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  11840. (define (add1 [x : Integer]) : Integer (+ x 1))
  11841. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11842. (Integer))
  11843. add1 (vector 0 41)) 1)
  11844. \end{lstlisting}
  11845. \caption{Output of the type checker on the \code{map-vec} example.}
  11846. \label{fig:map-vec-type-check}
  11847. \end{figure}
  11848. \begin{figure}[tbp]
  11849. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11850. (define type-check-poly-class
  11851. (class type-check-Rwhile-class
  11852. (super-new)
  11853. (inherit check-type-equal?)
  11854. (define/override (type-check-apply env e1 es)
  11855. (define-values (e^ ty) ((type-check-exp env) e1))
  11856. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  11857. ((type-check-exp env) e)))
  11858. (match ty
  11859. [`(,ty^* ... -> ,rt)
  11860. (for ([arg-ty ty*] [param-ty ty^*])
  11861. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  11862. (values e^ es^ rt)]
  11863. [`(All ,xs (,tys ... -> ,rt))
  11864. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11865. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  11866. (match-types env^^ param-ty arg-ty)))
  11867. (define targs
  11868. (for/list ([x xs])
  11869. (match (dict-ref env^^ x (lambda () #f))
  11870. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  11871. x (Apply e1 es))]
  11872. [ty ty])))
  11873. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  11874. [else (error 'type-check "expected a function, not ~a" ty)]))
  11875. (define/override ((type-check-exp env) e)
  11876. (match e
  11877. [(Lambda `([,xs : ,Ts] ...) rT body)
  11878. (for ([T Ts]) ((check-well-formed env) T))
  11879. ((check-well-formed env) rT)
  11880. ((super type-check-exp env) e)]
  11881. [(HasType e1 ty)
  11882. ((check-well-formed env) ty)
  11883. ((super type-check-exp env) e)]
  11884. [else ((super type-check-exp env) e)]))
  11885. (define/override ((type-check-def env) d)
  11886. (verbose 'type-check "poly/def" d)
  11887. (match d
  11888. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  11889. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  11890. (for ([p ps]) ((check-well-formed ts-env) p))
  11891. ((check-well-formed ts-env) rt)
  11892. (define new-env (append ts-env (map cons xs ps) env))
  11893. (define-values (body^ ty^) ((type-check-exp new-env) body))
  11894. (check-type-equal? ty^ rt body)
  11895. (Generic ts (Def f p:t* rt info body^))]
  11896. [else ((super type-check-def env) d)]))
  11897. (define/override (type-check-program p)
  11898. (match p
  11899. [(Program info body)
  11900. (type-check-program (ProgramDefsExp info '() body))]
  11901. [(ProgramDefsExp info ds body)
  11902. (define ds^ (combine-decls-defs ds))
  11903. (define new-env (for/list ([d ds^])
  11904. (cons (def-name d) (fun-def-type d))))
  11905. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  11906. (define-values (body^ ty) ((type-check-exp new-env) body))
  11907. (check-type-equal? ty 'Integer body)
  11908. (ProgramDefsExp info ds^^ body^)]))
  11909. ))
  11910. \end{lstlisting}
  11911. \caption{Type checker for the \LangPoly{} language.}
  11912. \label{fig:type-check-Rvar0}
  11913. \end{figure}
  11914. \begin{figure}[tbp]
  11915. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11916. (define/override (type-equal? t1 t2)
  11917. (match* (t1 t2)
  11918. [(`(All ,xs ,T1) `(All ,ys ,T2))
  11919. (define env (map cons xs ys))
  11920. (type-equal? (subst-type env T1) T2)]
  11921. [(other wise)
  11922. (super type-equal? t1 t2)]))
  11923. (define/public (match-types env pt at)
  11924. (match* (pt at)
  11925. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  11926. [('Void 'Void) env] [('Any 'Any) env]
  11927. [(`(Vector ,pts ...) `(Vector ,ats ...))
  11928. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  11929. (match-types env^ pt1 at1))]
  11930. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  11931. (define env^ (match-types env prt art))
  11932. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  11933. (match-types env^^ pt1 at1))]
  11934. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  11935. (define env^ (append (map cons pxs axs) env))
  11936. (match-types env^ pt1 at1)]
  11937. [((? symbol? x) at)
  11938. (match (dict-ref env x (lambda () #f))
  11939. [#f (error 'type-check "undefined type variable ~a" x)]
  11940. ['Type (cons (cons x at) env)]
  11941. [t^ (check-type-equal? at t^ 'matching) env])]
  11942. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  11943. (define/public (subst-type env pt)
  11944. (match pt
  11945. ['Integer 'Integer] ['Boolean 'Boolean]
  11946. ['Void 'Void] ['Any 'Any]
  11947. [`(Vector ,ts ...)
  11948. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  11949. [`(,ts ... -> ,rt)
  11950. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  11951. [`(All ,xs ,t)
  11952. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  11953. [(? symbol? x) (dict-ref env x)]
  11954. [else (error 'type-check "expected a type not ~a" pt)]))
  11955. (define/public (combine-decls-defs ds)
  11956. (match ds
  11957. ['() '()]
  11958. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  11959. (unless (equal? name f)
  11960. (error 'type-check "name mismatch, ~a != ~a" name f))
  11961. (match type
  11962. [`(All ,xs (,ps ... -> ,rt))
  11963. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11964. (cons (Generic xs (Def name params^ rt info body))
  11965. (combine-decls-defs ds^))]
  11966. [`(,ps ... -> ,rt)
  11967. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11968. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  11969. [else (error 'type-check "expected a function type, not ~a" type) ])]
  11970. [`(,(Def f params rt info body) . ,ds^)
  11971. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  11972. \end{lstlisting}
  11973. \caption{Auxiliary functions for type checking \LangPoly{}.}
  11974. \label{fig:type-check-Rvar0-aux}
  11975. \end{figure}
  11976. \begin{figure}[tbp]
  11977. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  11978. (define/public ((check-well-formed env) ty)
  11979. (match ty
  11980. ['Integer (void)]
  11981. ['Boolean (void)]
  11982. ['Void (void)]
  11983. [(? symbol? a)
  11984. (match (dict-ref env a (lambda () #f))
  11985. ['Type (void)]
  11986. [else (error 'type-check "undefined type variable ~a" a)])]
  11987. [`(Vector ,ts ...)
  11988. (for ([t ts]) ((check-well-formed env) t))]
  11989. [`(,ts ... -> ,t)
  11990. (for ([t ts]) ((check-well-formed env) t))
  11991. ((check-well-formed env) t)]
  11992. [`(All ,xs ,t)
  11993. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11994. ((check-well-formed env^) t)]
  11995. [else (error 'type-check "unrecognized type ~a" ty)]))
  11996. \end{lstlisting}
  11997. \caption{Well-formed types.}
  11998. \label{fig:well-formed-types}
  11999. \end{figure}
  12000. % TODO: interpreter for R'_10
  12001. \section{Compiling Polymorphism}
  12002. \label{sec:compiling-poly}
  12003. Broadly speaking, there are four approaches to compiling parametric
  12004. polymorphism, which we describe below.
  12005. \begin{description}
  12006. \item[Monomorphization] generates a different version of a polymorphic
  12007. function for each set of type arguments that it is used with,
  12008. producing type-specialized code. This approach results in the most
  12009. efficient code but requires whole-program compilation (no separate
  12010. compilation) and increases code size. For our current purposes
  12011. monomorphization is a non-starter because, with first-class
  12012. polymorphism, it is sometimes not possible to determine which
  12013. generic functions are used with which type arguments during
  12014. compilation. (It can be done at runtime, with just-in-time
  12015. compilation.) This approach is used to compile C++
  12016. templates~\citep{stroustrup88:_param_types} and polymorphic
  12017. functions in NESL~\citep{Blelloch:1993aa} and
  12018. ML~\citep{Weeks:2006aa}.
  12019. \item[Uniform representation] generates one version of each
  12020. polymorphic function but requires all values have a common ``boxed''
  12021. format, such as the tagged values of type \code{Any} in
  12022. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  12023. similarly to code in a dynamically typed language (like \LangDyn{}), in
  12024. which primitive operators require their arguments to be projected
  12025. from \code{Any} and their results are injected into \code{Any}. (In
  12026. object-oriented languages, the projection is accomplished via
  12027. virtual method dispatch.) The uniform representation approach is
  12028. compatible with separate compilation and with first-class
  12029. polymorphism. However, it produces the least-efficient code because
  12030. it introduces overhead in the entire program, including
  12031. non-polymorphic code. This approach is used in the implementation of
  12032. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  12033. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  12034. Java~\citep{Bracha:1998fk}.
  12035. \item[Mixed representation] generates one version of each polymorphic
  12036. function, using a boxed representation for type
  12037. variables. Monomorphic code is compiled as usual (as in \LangLoop{}) and
  12038. conversions are performed at the boundaries between monomorphic and
  12039. polymorphic (e.g. when a polymorphic function is instantiated and
  12040. called). This approach is compatible with separate compilation and
  12041. first-class polymorphism and maintains the efficiency for
  12042. monomorphic code. The tradeoff is increased overhead at the boundary
  12043. between monomorphic and polymorphic code. This approach is used in
  12044. compilers for variants of ML~\citep{Leroy:1992qb} and starting in
  12045. Java 5 with the addition of autoboxing.
  12046. \item[Type passing] uses the unboxed representation in both
  12047. monomorphic and polymorphic code. Each polymorphic function is
  12048. compiled to a single function with extra parameters that describe
  12049. the type arguments. The type information is used by the generated
  12050. code to direct access of the unboxed values at runtime. This
  12051. approach is used in compilers for the Napier88
  12052. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. This
  12053. approach is compatible with separate compilation and first-class
  12054. polymorphism and maintains the efficiency for monomorphic
  12055. code. There is runtime overhead in polymorphic code from dispatching
  12056. on type information.
  12057. \end{description}
  12058. In this chapter we use the mixed representation approach, partly
  12059. because of its favorable attributes, and partly because it is
  12060. straightforward to implement using the tools that we have already
  12061. built to support gradual typing. To compile polymorphic functions, we
  12062. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  12063. \LangCast{}.
  12064. \section{Erase Types}
  12065. \label{sec:erase-types}
  12066. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  12067. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  12068. shows the output of the \code{erase-types} pass on the polymorphic
  12069. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  12070. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  12071. \code{All} types are removed from the type of \code{map-vec}.
  12072. \begin{figure}[tbp]
  12073. \begin{lstlisting}
  12074. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  12075. : (Vector Any Any)
  12076. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12077. (define (add1 [x : Integer]) : Integer (+ x 1))
  12078. (vector-ref ((cast map-vec
  12079. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12080. ((Integer -> Integer) (Vector Integer Integer)
  12081. -> (Vector Integer Integer)))
  12082. add1 (vector 0 41)) 1)
  12083. \end{lstlisting}
  12084. \caption{The polymorphic \code{map-vec} example after type erasure.}
  12085. \label{fig:map-vec-erase}
  12086. \end{figure}
  12087. This process of type erasure creates a challenge at points of
  12088. instantiation. For example, consider the instantiation of
  12089. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  12090. The type of \code{map-vec} is
  12091. \begin{lstlisting}
  12092. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12093. \end{lstlisting}
  12094. and it is instantiated to
  12095. \begin{lstlisting}
  12096. ((Integer -> Integer) (Vector Integer Integer)
  12097. -> (Vector Integer Integer))
  12098. \end{lstlisting}
  12099. After erasure, the type of \code{map-vec} is
  12100. \begin{lstlisting}
  12101. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12102. \end{lstlisting}
  12103. but we need to convert it to the instantiated type. This is easy to
  12104. do in the target language \LangCast{} with a single \code{cast}. In
  12105. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  12106. has been compiled to a \code{cast} from the type of \code{map-vec} to
  12107. the instantiated type. The source and target type of a cast must be
  12108. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  12109. because both the source and target are obtained from the same
  12110. polymorphic type of \code{map-vec}, replacing the type parameters with
  12111. \code{Any} in the former and with the deduced type arguments in the
  12112. later. (Recall that the \code{Any} type is consistent with any type.)
  12113. To implement the \code{erase-types} pass, we recommend defining a
  12114. recursive auxiliary function named \code{erase-type} that applies the
  12115. following two transformations. It replaces type variables with
  12116. \code{Any}
  12117. \begin{lstlisting}
  12118. |$x$|
  12119. |$\Rightarrow$|
  12120. Any
  12121. \end{lstlisting}
  12122. and it removes the polymorphic \code{All} types.
  12123. \begin{lstlisting}
  12124. (All |$xs$| |$T_1$|)
  12125. |$\Rightarrow$|
  12126. |$T'_1$|
  12127. \end{lstlisting}
  12128. Apply the \code{erase-type} function to all of the type annotations in
  12129. the program.
  12130. Regarding the translation of expressions, the case for \code{Inst} is
  12131. the interesting one. We translate it into a \code{Cast}, as shown
  12132. below. The type of the subexpression $e$ is the polymorphic type
  12133. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  12134. $T$, the type $T'$. The target type $T''$ is the result of
  12135. substituting the arguments types $ts$ for the type parameters $xs$ in
  12136. $T$ followed by doing type erasure.
  12137. \begin{lstlisting}
  12138. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  12139. |$\Rightarrow$|
  12140. (Cast |$e'$| |$T'$| |$T''$|)
  12141. \end{lstlisting}
  12142. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  12143. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  12144. Finally, each polymorphic function is translated to a regular
  12145. functions in which type erasure has been applied to all the type
  12146. annotations and the body.
  12147. \begin{lstlisting}
  12148. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  12149. |$\Rightarrow$|
  12150. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  12151. \end{lstlisting}
  12152. \begin{exercise}\normalfont
  12153. Implement a compiler for the polymorphic language \LangPoly{} by
  12154. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  12155. programs that use polymorphic functions. Some of them should make
  12156. use of first-class polymorphism.
  12157. \end{exercise}
  12158. \begin{figure}[p]
  12159. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12160. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  12161. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  12162. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  12163. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  12164. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  12165. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  12166. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  12167. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  12168. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  12169. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  12170. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  12171. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  12172. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  12173. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  12174. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  12175. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12176. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12177. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12178. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12179. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12180. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12181. \path[->,bend right=15] (Rpoly) edge [above] node
  12182. {\ttfamily\footnotesize type-check} (Rpolyp);
  12183. \path[->,bend right=15] (Rpolyp) edge [above] node
  12184. {\ttfamily\footnotesize erase-types} (Rgradualp);
  12185. \path[->,bend right=15] (Rgradualp) edge [above] node
  12186. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  12187. \path[->,bend right=15] (Rwhilepp) edge [right] node
  12188. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  12189. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  12190. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  12191. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  12192. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  12193. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  12194. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  12195. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  12196. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  12197. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  12198. {\ttfamily\footnotesize convert-assignments} (F1-1);
  12199. \path[->,bend left=15] (F1-1) edge [below] node
  12200. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12201. \path[->,bend right=15] (F1-2) edge [above] node
  12202. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12203. \path[->,bend right=15] (F1-3) edge [above] node
  12204. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12205. \path[->,bend right=15] (F1-4) edge [above] node
  12206. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12207. \path[->,bend right=15] (F1-5) edge [right] node
  12208. {\ttfamily\footnotesize explicate-control} (C3-2);
  12209. \path[->,bend left=15] (C3-2) edge [left] node
  12210. {\ttfamily\footnotesize select-instr.} (x86-2);
  12211. \path[->,bend right=15] (x86-2) edge [left] node
  12212. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12213. \path[->,bend right=15] (x86-2-1) edge [below] node
  12214. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12215. \path[->,bend right=15] (x86-2-2) edge [left] node
  12216. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12217. \path[->,bend left=15] (x86-3) edge [above] node
  12218. {\ttfamily\footnotesize patch-instr.} (x86-4);
  12219. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  12220. \end{tikzpicture}
  12221. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  12222. \label{fig:Rpoly-passes}
  12223. \end{figure}
  12224. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  12225. for the compilation of \LangPoly{}.
  12226. % TODO: challenge problem: specialization of instantiations
  12227. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12228. \chapter{Appendix}
  12229. \section{Interpreters}
  12230. \label{appendix:interp}
  12231. \index{interpreter}
  12232. We provide interpreters for each of the source languages \LangInt{},
  12233. \LangVar{}, $\ldots$ in the files \code{interp-Rint.rkt},
  12234. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  12235. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  12236. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  12237. and x86 are in the \key{interp.rkt} file.
  12238. \section{Utility Functions}
  12239. \label{appendix:utilities}
  12240. The utility functions described in this section are in the
  12241. \key{utilities.rkt} file of the support code.
  12242. \paragraph{\code{interp-tests}}
  12243. The \key{interp-tests} function runs the compiler passes and the
  12244. interpreters on each of the specified tests to check whether each pass
  12245. is correct. The \key{interp-tests} function has the following
  12246. parameters:
  12247. \begin{description}
  12248. \item[name (a string)] a name to identify the compiler,
  12249. \item[typechecker] a function of exactly one argument that either
  12250. raises an error using the \code{error} function when it encounters a
  12251. type error, or returns \code{\#f} when it encounters a type
  12252. error. If there is no type error, the type checker returns the
  12253. program.
  12254. \item[passes] a list with one entry per pass. An entry is a list with
  12255. four things:
  12256. \begin{enumerate}
  12257. \item a string giving the name of the pass,
  12258. \item the function that implements the pass (a translator from AST
  12259. to AST),
  12260. \item a function that implements the interpreter (a function from
  12261. AST to result value) for the output language,
  12262. \item and a type checker for the output language. Type checkers for
  12263. the $R$ and $C$ languages are provided in the support code. For
  12264. example, the type checkers for \LangVar{} and \LangCVar{} are in
  12265. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  12266. type checker entry is optional. The support code does not provide
  12267. type checkers for the x86 languages.
  12268. \end{enumerate}
  12269. \item[source-interp] an interpreter for the source language. The
  12270. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  12271. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  12272. \item[tests] a list of test numbers that specifies which tests to
  12273. run. (see below)
  12274. \end{description}
  12275. %
  12276. The \key{interp-tests} function assumes that the subdirectory
  12277. \key{tests} has a collection of Racket programs whose names all start
  12278. with the family name, followed by an underscore and then the test
  12279. number, ending with the file extension \key{.rkt}. Also, for each test
  12280. program that calls \code{read} one or more times, there is a file with
  12281. the same name except that the file extension is \key{.in} that
  12282. provides the input for the Racket program. If the test program is
  12283. expected to fail type checking, then there should be an empty file of
  12284. the same name but with extension \key{.tyerr}.
  12285. \paragraph{\code{compiler-tests}}
  12286. runs the compiler passes to generate x86 (a \key{.s} file) and then
  12287. runs the GNU C compiler (gcc) to generate machine code. It runs the
  12288. machine code and checks that the output is $42$. The parameters to the
  12289. \code{compiler-tests} function are similar to those of the
  12290. \code{interp-tests} function, and consist of
  12291. \begin{itemize}
  12292. \item a compiler name (a string),
  12293. \item a type checker,
  12294. \item description of the passes,
  12295. \item name of a test-family, and
  12296. \item a list of test numbers.
  12297. \end{itemize}
  12298. \paragraph{\code{compile-file}}
  12299. takes a description of the compiler passes (see the comment for
  12300. \key{interp-tests}) and returns a function that, given a program file
  12301. name (a string ending in \key{.rkt}), applies all of the passes and
  12302. writes the output to a file whose name is the same as the program file
  12303. name but with \key{.rkt} replaced with \key{.s}.
  12304. \paragraph{\code{read-program}}
  12305. takes a file path and parses that file (it must be a Racket program)
  12306. into an abstract syntax tree.
  12307. \paragraph{\code{parse-program}}
  12308. takes an S-expression representation of an abstract syntax tree and converts it into
  12309. the struct-based representation.
  12310. \paragraph{\code{assert}}
  12311. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  12312. and displays the message \key{msg} if the Boolean \key{bool} is false.
  12313. \paragraph{\code{lookup}}
  12314. % remove discussion of lookup? -Jeremy
  12315. takes a key and an alist, and returns the first value that is
  12316. associated with the given key, if there is one. If not, an error is
  12317. triggered. The alist may contain both immutable pairs (built with
  12318. \key{cons}) and mutable pairs (built with \key{mcons}).
  12319. %The \key{map2} function ...
  12320. \section{x86 Instruction Set Quick-Reference}
  12321. \label{sec:x86-quick-reference}
  12322. \index{x86}
  12323. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  12324. do. We write $A \to B$ to mean that the value of $A$ is written into
  12325. location $B$. Address offsets are given in bytes. The instruction
  12326. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  12327. registers (such as \code{\%rax}), or memory references (such as
  12328. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  12329. reference per instruction. Other operands must be immediates or
  12330. registers.
  12331. \begin{table}[tbp]
  12332. \centering
  12333. \begin{tabular}{l|l}
  12334. \textbf{Instruction} & \textbf{Operation} \\ \hline
  12335. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  12336. \texttt{negq} $A$ & $- A \to A$ \\
  12337. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  12338. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  12339. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  12340. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  12341. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  12342. \texttt{retq} & Pops the return address and jumps to it \\
  12343. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  12344. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  12345. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  12346. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  12347. be an immediate) \\
  12348. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  12349. matches the condition code of the instruction, otherwise go to the
  12350. next instructions. The condition codes are \key{e} for ``equal'',
  12351. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  12352. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  12353. \texttt{jl} $L$ & \\
  12354. \texttt{jle} $L$ & \\
  12355. \texttt{jg} $L$ & \\
  12356. \texttt{jge} $L$ & \\
  12357. \texttt{jmp} $L$ & Jump to label $L$ \\
  12358. \texttt{movq} $A$, $B$ & $A \to B$ \\
  12359. \texttt{movzbq} $A$, $B$ &
  12360. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  12361. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  12362. and the extra bytes of $B$ are set to zero.} \\
  12363. & \\
  12364. & \\
  12365. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  12366. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  12367. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  12368. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  12369. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  12370. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  12371. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  12372. description of the condition codes. $A$ must be a single byte register
  12373. (e.g., \texttt{al} or \texttt{cl}).} \\
  12374. \texttt{setl} $A$ & \\
  12375. \texttt{setle} $A$ & \\
  12376. \texttt{setg} $A$ & \\
  12377. \texttt{setge} $A$ &
  12378. \end{tabular}
  12379. \vspace{5pt}
  12380. \caption{Quick-reference for the x86 instructions used in this book.}
  12381. \label{tab:x86-instr}
  12382. \end{table}
  12383. \cleardoublepage
  12384. \section{Concrete Syntax for Intermediate Languages}
  12385. The concrete syntax of \LangAny{} is defined in
  12386. Figure~\ref{fig:Rany-concrete-syntax}.
  12387. \begin{figure}[tp]
  12388. \centering
  12389. \fbox{
  12390. \begin{minipage}{0.97\textwidth}\small
  12391. \[
  12392. \begin{array}{lcl}
  12393. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  12394. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}} \\
  12395. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  12396. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void}
  12397. \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  12398. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  12399. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType}\\
  12400. &\mid& \LP\key{any-vector-length}\;\Exp\RP
  12401. \mid \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  12402. &\mid& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  12403. &\mid& \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP
  12404. \mid \LP\key{void?}\;\Exp\RP \\
  12405. &\mid& \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \\
  12406. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  12407. \LangAny{} &::=& \gray{\Def\ldots \; \Exp}
  12408. \end{array}
  12409. \]
  12410. \end{minipage}
  12411. }
  12412. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  12413. (Figure~\ref{fig:Rlam-syntax}) with \key{Any}.}
  12414. \label{fig:Rany-concrete-syntax}
  12415. \end{figure}
  12416. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  12417. defined in Figures~\ref{fig:c0-concrete-syntax},
  12418. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  12419. and \ref{fig:c3-concrete-syntax}, respectively.
  12420. \begin{figure}[tbp]
  12421. \fbox{
  12422. \begin{minipage}{0.96\textwidth}
  12423. \[
  12424. \begin{array}{lcl}
  12425. \Atm &::=& \Int \mid \Var \\
  12426. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  12427. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  12428. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  12429. \LangCVar{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  12430. \end{array}
  12431. \]
  12432. \end{minipage}
  12433. }
  12434. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  12435. \label{fig:c0-concrete-syntax}
  12436. \end{figure}
  12437. \begin{figure}[tbp]
  12438. \fbox{
  12439. \begin{minipage}{0.96\textwidth}
  12440. \small
  12441. \[
  12442. \begin{array}{lcl}
  12443. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  12444. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  12445. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12446. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  12447. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  12448. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12449. \mid \key{goto}~\itm{label}\key{;}\\
  12450. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  12451. \LangCIf{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12452. \end{array}
  12453. \]
  12454. \end{minipage}
  12455. }
  12456. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  12457. \label{fig:c1-concrete-syntax}
  12458. \end{figure}
  12459. \begin{figure}[tbp]
  12460. \fbox{
  12461. \begin{minipage}{0.96\textwidth}
  12462. \small
  12463. \[
  12464. \begin{array}{lcl}
  12465. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  12466. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12467. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12468. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  12469. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  12470. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  12471. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  12472. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  12473. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12474. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  12475. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  12476. \LangCVec{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12477. \end{array}
  12478. \]
  12479. \end{minipage}
  12480. }
  12481. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  12482. \label{fig:c2-concrete-syntax}
  12483. \end{figure}
  12484. \begin{figure}[tp]
  12485. \fbox{
  12486. \begin{minipage}{0.96\textwidth}
  12487. \small
  12488. \[
  12489. \begin{array}{lcl}
  12490. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  12491. \\
  12492. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12493. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  12494. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  12495. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  12496. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  12497. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  12498. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  12499. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  12500. \mid \LP\key{collect} \,\itm{int}\RP }\\
  12501. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  12502. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  12503. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  12504. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  12505. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  12506. \LangCFun{} & ::= & \Def\ldots
  12507. \end{array}
  12508. \]
  12509. \end{minipage}
  12510. }
  12511. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  12512. \label{fig:c3-concrete-syntax}
  12513. \end{figure}
  12514. \cleardoublepage
  12515. \addcontentsline{toc}{chapter}{Index}
  12516. \printindex
  12517. \cleardoublepage
  12518. \bibliographystyle{plainnat}
  12519. \bibliography{all}
  12520. \addcontentsline{toc}{chapter}{Bibliography}
  12521. \end{document}
  12522. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  12523. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  12524. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  12525. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  12526. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator jane
  12527. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  12528. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  12529. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  12530. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs Tt
  12531. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  12532. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  12533. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  12534. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  12535. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  12536. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  12537. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  12538. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  12539. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  12540. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  12541. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  12542. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  12543. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  12544. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  12545. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  12546. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  12547. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  12548. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  12549. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  12550. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  12551. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  12552. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  12553. % LocalWords: struct Friedman's MacOS Nystrom alist sam kate
  12554. % LocalWords: alists arity github unordered pqueue exprs ret param
  12555. % LocalWords: tyerr bytereg dh dl JmpIf HasType Osterlund Jacek TODO
  12556. % LocalWords: Gamari GlobalValue ProgramDefsExp prm ProgramDefs vn
  12557. % LocalWords: FunRef TailCall tailjmp IndirectCallq TailJmp Gilray
  12558. % LocalWords: dereference unbox Dataflow versa dataflow Kildall rhs
  12559. % LocalWords: Kleene enqueue dequeue AssignedFree FV cnvt SetBang tg
  12560. % LocalWords: ValueOf typechecker