book.bak 539 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942
  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. Here we reveal 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. We take you on a journey by constructing your own compiler for a small
  155. but powerful language. Along the way we explain the essential
  156. concepts, algorithms, and data structures that underlie compilers. We
  157. develop your understanding of how programs are mapped onto computer
  158. hardware, which is helpful when reasoning about properties at the
  159. junction between hardware and software such as execution time,
  160. software errors, and security vulnerabilities. For those interested
  161. in pursuing compiler construction, our goal is to provide a
  162. stepping-stone to advanced topics such as just-in-time compilation,
  163. program analysis, and program optimization. For those interested in
  164. designing and implementing programming languages, we connect
  165. language design choices to their impact on the compiler and the generated
  166. code.
  167. A compiler is typically organized as a sequence of stages that
  168. progressively translates a program to code that runs on hardware. We
  169. take this approach to the extreme by partitioning our compiler into a
  170. large number of \emph{nanopasses}, each of which performs a single
  171. task. This allows us to test the output of each pass in isolation, and
  172. furthermore, allows us to focus our attention making the compiler far
  173. easier to understand.
  174. %% [TODO: easier to understand/debug for those maintaining the compiler,
  175. %% proving correctness]
  176. The most familiar approach to describing compilers is with one pass
  177. per chapter. The problem with that is it obfuscates how language
  178. features motivate design choices in a compiler. We take an
  179. \emph{incremental} approach in which we build a complete compiler in
  180. each chapter, starting with arithmetic and variables and add new
  181. features in subsequent chapters.
  182. Our choice of language features is designed to elicit the fundamental
  183. concepts and algorithms used in compilers.
  184. \begin{itemize}
  185. \item We begin with integer arithmetic and local variables in
  186. Chapters~\ref{ch:trees-recur} and \ref{ch:Rvar}, where we introduce
  187. the fundamental tools of compiler construction: \emph{abstract
  188. syntax trees} and \emph{recursive functions}.
  189. \item In Chapter~\ref{ch:register-allocation-Rvar} we apply
  190. \emph{graph coloring} to assign variables to machine registers.
  191. \item Chapter~\ref{ch:Rif} adds \code{if} expressions, which motivates
  192. an elegant recursive algorithm for mapping expressions to
  193. \emph{control-flow graphs}.
  194. \item Chapter~\ref{ch:Rvec} adds heap-allocated tuples, motivating
  195. \emph{garbage collection}.
  196. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  197. but lack lexical scoping, similar to the C programming
  198. language~\citep{Kernighan:1988nx} except that we generate efficient
  199. tail calls. The reader learns about the procedure call stack,
  200. \emph{calling conventions}, and their interaction with register
  201. allocation and garbage collection.
  202. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  203. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  204. \emph{closure conversion}, in which lambdas are translated into a
  205. combination of functions and tuples.
  206. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  207. point the input languages are statically typed. The reader extends
  208. the statically typed language with an \code{Any} type which serves
  209. as a target for compiling the dynamically typed language.
  210. \item Chapter~\ref{ch:Rwhile} fleshes out support for imperative
  211. programming languages with the addition of loops and mutable
  212. variables. These additions elicit the need for \emph{dataflow
  213. analysis} in the register allocator.
  214. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  215. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  216. in which different regions of a program may be static or dynamically
  217. typed. The reader implements runtime support for \emph{proxies} that
  218. allow values to safely move between regions.
  219. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  220. leveraging the \code{Any} type and type casts developed in Chapters
  221. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  222. \end{itemize}
  223. There are many language features that we do not include. Our choices
  224. weigh the incidental complexity of a feature against the fundamental
  225. concepts that it exposes. For example, we include tuples and not
  226. records because they both elicit the study of heap allocation and
  227. garbage collection but records come with more incidental complexity.
  228. Since 2016 this book has served as the textbook for the compiler
  229. course at Indiana University, a 16-week course for upper-level
  230. undergraduates and first-year graduate students.
  231. %
  232. Prior to this course, students learn to program in both imperative and
  233. functional languages, study data structures and algorithms, and take
  234. discrete mathematics.
  235. %
  236. At the beginning of the course, students form groups of 2-4 people.
  237. The groups complete one chapter every two weeks, starting with
  238. Chapter~\ref{ch:Rvar} and finishing with Chapter~\ref{ch:Rdyn}. Many
  239. chapters include a challenge problem that we assign to the graduate
  240. students. The last two weeks of the course involve a final project in
  241. which students design and implement a compiler extension of their
  242. choosing. Chapters~\ref{ch:Rwhile}, \ref{ch:Rgrad}, and
  243. \ref{ch:Rpoly} can be used in support of these projects or they can
  244. replace some of the earlier chapters. For example, a course with an
  245. emphasis on statically-typed imperative languages would skip
  246. Chapter~\ref{ch:Rdyn} in favor of
  247. Chapter~\ref{ch:Rwhile}. Figure~\ref{fig:chapter-dependences} depicts
  248. the dependencies between chapters.
  249. This book has also been used in compiler courses at California
  250. Polytechnic State University, Rose–Hulman Institute of Technology, and
  251. University of Massachusetts Lowell.
  252. \begin{figure}[tp]
  253. \begin{tikzpicture}[baseline=(current bounding box.center)]
  254. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  255. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Rvar} Variables};
  256. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Rvar} Registers};
  257. \node (C4) at (0,0) {\small Ch.~\ref{ch:Rif} Control Flow};
  258. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  259. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  260. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  261. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  262. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  263. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual};
  264. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  265. \path[->] (C1) edge [above] node {} (C2);
  266. \path[->] (C2) edge [above] node {} (C3);
  267. \path[->] (C3) edge [above] node {} (C4);
  268. \path[->] (C4) edge [above] node {} (C5);
  269. \path[->] (C5) edge [above] node {} (C6);
  270. \path[->] (C6) edge [above] node {} (C7);
  271. \path[->] (C4) edge [above] node {} (C8);
  272. \path[->] (C4) edge [above] node {} (C9);
  273. \path[->] (C8) edge [above] node {} (C10);
  274. \path[->] (C10) edge [above] node {} (C11);
  275. \end{tikzpicture}
  276. \caption{Diagram of chapter dependencies.}
  277. \label{fig:chapter-dependences}
  278. \end{figure}
  279. We use the \href{https://racket-lang.org/}{Racket} language both for
  280. the implementation of the compiler and for the input language, so the
  281. reader should be proficient with Racket or Scheme. There are many
  282. excellent resources for learning Scheme and
  283. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. The
  284. support code for this book is in the \code{github} repository at the
  285. following URL:
  286. \begin{center}\small
  287. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  288. \end{center}
  289. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  290. is helpful but not necessary for the reader to have taken a computer
  291. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  292. of x86-64 assembly language that are needed.
  293. %
  294. We follow the System V calling
  295. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  296. that we generate works with the runtime system (written in C) when it
  297. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  298. operating systems.
  299. %
  300. On the Windows operating system, \code{gcc} uses the Microsoft x64
  301. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  302. assembly code that we generate does \emph{not} work with the runtime
  303. system on Windows. One workaround is to use a virtual machine with
  304. Linux as the guest operating system.
  305. \section*{Acknowledgments}
  306. The tradition of compiler construction at Indiana University goes back
  307. to research and courses on programming languages by Daniel Friedman in
  308. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  309. Chez Scheme~\citep{Dybvig:2006aa}, a production-quality, efficient
  310. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  311. the compiler course and continued the development of Chez Scheme.
  312. %
  313. The compiler course evolved to incorporate novel pedagogical ideas
  314. while also including elements of efficient real-world compilers. One
  315. of Friedman's ideas was to split the compiler into many small
  316. passes. Another idea, called ``the game'', was to test the code
  317. generated by each pass on interpreters.
  318. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  319. developed infrastructure to support this approach and evolved the
  320. course to use even smaller
  321. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  322. design decisions in this book are inspired by the assignment
  323. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  324. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  325. organization of the course made it difficult for students to
  326. understand the rationale for the compiler design. Ghuloum proposed the
  327. incremental approach~\citep{Ghuloum:2006bh}.
  328. We thank the many graduate students who served as teaching assistants
  329. for the compiler course at IU. In particular, we thank Andre
  330. Kuhlenschmidt for his work on the garbage collector, Michael Vollmer
  331. for his work on efficient tail calls, and Michael Vitousek for his
  332. help running the first offering of the incremental compiler course at
  333. IU.
  334. We thank Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph Near, Nate
  335. Nystrom, and Michael Wollowski for teaching courses based on early
  336. drafts of this book.
  337. We thank Ronald Garcia for being Jeremy's partner when they took the
  338. compiler course in the early 2000's and especially for finding the bug
  339. that sent the garbage collector on a wild goose chase!
  340. \mbox{}\\
  341. \noindent Jeremy G. Siek \\
  342. Bloomington, Indiana
  343. %Oscar Waddell ??
  344. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  345. \chapter{Preliminaries}
  346. \label{ch:trees-recur}
  347. In this chapter we review the basic tools that are needed to implement
  348. a compiler. Programs are typically input by a programmer as text,
  349. i.e., a sequence of characters. The program-as-text representation is
  350. called \emph{concrete syntax}. We use concrete syntax to concisely
  351. write down and talk about programs. Inside the compiler, we use
  352. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  353. that efficiently supports the operations that the compiler needs to
  354. perform.\index{concrete syntax}\index{abstract syntax}\index{abstract
  355. syntax tree}\index{AST}\index{program}\index{parse} The translation
  356. from concrete syntax to abstract syntax is a process called
  357. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  358. implementation of parsing in this book. A parser is provided in the
  359. support code for translating from concrete to abstract syntax.
  360. ASTs can be represented in many different ways inside the compiler,
  361. depending on the programming language used to write the compiler.
  362. %
  363. We use Racket's
  364. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  365. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  366. define the abstract syntax of programming languages
  367. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  368. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  369. recursive functions to construct and deconstruct ASTs
  370. (Section~\ref{sec:recursion}). This chapter provides an brief
  371. introduction to these ideas. \index{struct}
  372. \section{Abstract Syntax Trees and Racket Structures}
  373. \label{sec:ast}
  374. Compilers use abstract syntax trees to represent programs because they
  375. often need to ask questions like: for a given part of a program, what
  376. kind of language feature is it? What are its sub-parts? Consider the
  377. program on the left and its AST on the right. This program is an
  378. addition operation and it has two sub-parts, a read operation and a
  379. negation. The negation has another sub-part, the integer constant
  380. \code{8}. By using a tree to represent the program, we can easily
  381. follow the links to go from one part of a program to its sub-parts.
  382. \begin{center}
  383. \begin{minipage}{0.4\textwidth}
  384. \begin{lstlisting}
  385. (+ (read) (- 8))
  386. \end{lstlisting}
  387. \end{minipage}
  388. \begin{minipage}{0.4\textwidth}
  389. \begin{equation}
  390. \begin{tikzpicture}
  391. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  392. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  393. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  394. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  395. \draw[->] (plus) to (read);
  396. \draw[->] (plus) to (minus);
  397. \draw[->] (minus) to (8);
  398. \end{tikzpicture}
  399. \label{eq:arith-prog}
  400. \end{equation}
  401. \end{minipage}
  402. \end{center}
  403. We use the standard terminology for trees to describe ASTs: each
  404. circle above is called a \emph{node}. The arrows connect a node to its
  405. \emph{children} (which are also nodes). The top-most node is the
  406. \emph{root}. Every node except for the root has a \emph{parent} (the
  407. node it is the child of). If a node has no children, it is a
  408. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  409. \index{node}
  410. \index{children}
  411. \index{root}
  412. \index{parent}
  413. \index{leaf}
  414. \index{internal node}
  415. %% Recall that an \emph{symbolic expression} (S-expression) is either
  416. %% \begin{enumerate}
  417. %% \item an atom, or
  418. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  419. %% where $e_1$ and $e_2$ are each an S-expression.
  420. %% \end{enumerate}
  421. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  422. %% null value \code{'()}, etc. We can create an S-expression in Racket
  423. %% simply by writing a backquote (called a quasi-quote in Racket)
  424. %% followed by the textual representation of the S-expression. It is
  425. %% quite common to use S-expressions to represent a list, such as $a, b
  426. %% ,c$ in the following way:
  427. %% \begin{lstlisting}
  428. %% `(a . (b . (c . ())))
  429. %% \end{lstlisting}
  430. %% Each element of the list is in the first slot of a pair, and the
  431. %% second slot is either the rest of the list or the null value, to mark
  432. %% the end of the list. Such lists are so common that Racket provides
  433. %% special notation for them that removes the need for the periods
  434. %% and so many parenthesis:
  435. %% \begin{lstlisting}
  436. %% `(a b c)
  437. %% \end{lstlisting}
  438. %% The following expression creates an S-expression that represents AST
  439. %% \eqref{eq:arith-prog}.
  440. %% \begin{lstlisting}
  441. %% `(+ (read) (- 8))
  442. %% \end{lstlisting}
  443. %% When using S-expressions to represent ASTs, the convention is to
  444. %% represent each AST node as a list and to put the operation symbol at
  445. %% the front of the list. The rest of the list contains the children. So
  446. %% in the above case, the root AST node has operation \code{`+} and its
  447. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  448. %% diagram \eqref{eq:arith-prog}.
  449. %% To build larger S-expressions one often needs to splice together
  450. %% several smaller S-expressions. Racket provides the comma operator to
  451. %% splice an S-expression into a larger one. For example, instead of
  452. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  453. %% we could have first created an S-expression for AST
  454. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  455. %% S-expression.
  456. %% \begin{lstlisting}
  457. %% (define ast1.4 `(- 8))
  458. %% (define ast1.1 `(+ (read) ,ast1.4))
  459. %% \end{lstlisting}
  460. %% In general, the Racket expression that follows the comma (splice)
  461. %% can be any expression that produces an S-expression.
  462. We define a Racket \code{struct} for each kind of node. For this
  463. chapter we require just two kinds of nodes: one for integer constants
  464. and one for primitive operations. The following is the \code{struct}
  465. definition for integer constants.
  466. \begin{lstlisting}
  467. (struct Int (value))
  468. \end{lstlisting}
  469. An integer node includes just one thing: the integer value.
  470. To create an AST node for the integer $8$, we write \code{(Int 8)}.
  471. \begin{lstlisting}
  472. (define eight (Int 8))
  473. \end{lstlisting}
  474. We say that the value created by \code{(Int 8)} is an
  475. \emph{instance} of the \code{Int} structure.
  476. The following is the \code{struct} definition for primitive operations.
  477. \begin{lstlisting}
  478. (struct Prim (op args))
  479. \end{lstlisting}
  480. A primitive operation node includes an operator symbol \code{op}
  481. and a list of child \code{args}. For example, to create
  482. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  483. \begin{lstlisting}
  484. (define neg-eight (Prim '- (list eight)))
  485. \end{lstlisting}
  486. Primitive operations may have zero or more children. The \code{read}
  487. operator has zero children:
  488. \begin{lstlisting}
  489. (define rd (Prim 'read '()))
  490. \end{lstlisting}
  491. whereas the addition operator has two children:
  492. \begin{lstlisting}
  493. (define ast1.1 (Prim '+ (list rd neg-eight)))
  494. \end{lstlisting}
  495. We have made a design choice regarding the \code{Prim} structure.
  496. Instead of using one structure for many different operations
  497. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  498. structure for each operation, as follows.
  499. \begin{lstlisting}
  500. (struct Read ())
  501. (struct Add (left right))
  502. (struct Neg (value))
  503. \end{lstlisting}
  504. The reason we choose to use just one structure is that in many parts
  505. of the compiler the code for the different primitive operators is the
  506. same, so we might as well just write that code once, which is enabled
  507. by using a single structure.
  508. When compiling a program such as \eqref{eq:arith-prog}, we need to
  509. know that the operation associated with the root node is addition and
  510. we need to be able to access its two children. Racket provides pattern
  511. matching to support these kinds of queries, as we see in
  512. Section~\ref{sec:pattern-matching}.
  513. In this book, we often write down the concrete syntax of a program
  514. even when we really have in mind the AST because the concrete syntax
  515. is more concise. We recommend that, in your mind, you always think of
  516. programs as abstract syntax trees.
  517. \section{Grammars}
  518. \label{sec:grammar}
  519. \index{integer}
  520. \index{literal}
  521. \index{constant}
  522. A programming language can be thought of as a \emph{set} of programs.
  523. The set is typically infinite (one can always create larger and larger
  524. programs), so one cannot simply describe a language by listing all of
  525. the programs in the language. Instead we write down a set of rules, a
  526. \emph{grammar}, for building programs. Grammars are often used to
  527. define the concrete syntax of a language, but they can also be used to
  528. describe the abstract syntax. We write our rules in a variant of
  529. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  530. \index{Backus-Naur Form}\index{BNF}
  531. As an example, we describe a small language, named \LangInt{}, that consists of
  532. integers and arithmetic operations.
  533. \index{grammar}
  534. The first grammar rule for the abstract syntax of \LangInt{} says that an
  535. instance of the \code{Int} structure is an expression:
  536. \begin{equation}
  537. \Exp ::= \INT{\Int} \label{eq:arith-int}
  538. \end{equation}
  539. %
  540. Each rule has a left-hand-side and a right-hand-side. The way to read
  541. a rule is that if you have an AST node that matches the
  542. right-hand-side, then you can categorize it according to the
  543. left-hand-side.
  544. %
  545. A name such as $\Exp$ that is defined by the grammar rules is a
  546. \emph{non-terminal}. \index{non-terminal}
  547. %
  548. The name $\Int$ is also a non-terminal, but instead of defining it
  549. with a grammar rule, we define it with the following explanation. We
  550. make the simplifying design decision that all of the languages in this
  551. book only handle machine-representable integers. On most modern
  552. machines this corresponds to integers represented with 64-bits, i.e.,
  553. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  554. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  555. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  556. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  557. that the sequence of decimals represent an integer in range $-2^{62}$
  558. to $2^{62}-1$.
  559. The second grammar rule is the \texttt{read} operation that receives
  560. an input integer from the user of the program.
  561. \begin{equation}
  562. \Exp ::= \READ{} \label{eq:arith-read}
  563. \end{equation}
  564. The third rule says that, given an $\Exp$ node, the negation of that
  565. node is also an $\Exp$.
  566. \begin{equation}
  567. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  568. \end{equation}
  569. Symbols in typewriter font such as \key{-} and \key{read} are
  570. \emph{terminal} symbols and must literally appear in the program for
  571. the rule to be applicable.
  572. \index{terminal}
  573. We can apply these rules to categorize the ASTs that are in the
  574. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  575. \texttt{(Int 8)} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  576. following AST is an $\Exp$.
  577. \begin{center}
  578. \begin{minipage}{0.4\textwidth}
  579. \begin{lstlisting}
  580. (Prim '- (list (Int 8)))
  581. \end{lstlisting}
  582. \end{minipage}
  583. \begin{minipage}{0.25\textwidth}
  584. \begin{equation}
  585. \begin{tikzpicture}
  586. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  587. \node[draw, circle] (8) at (0, -1.2) {$8$};
  588. \draw[->] (minus) to (8);
  589. \end{tikzpicture}
  590. \label{eq:arith-neg8}
  591. \end{equation}
  592. \end{minipage}
  593. \end{center}
  594. The next grammar rule is for addition expressions:
  595. \begin{equation}
  596. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  597. \end{equation}
  598. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  599. \LangInt{}. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  600. \eqref{eq:arith-read} and we have already categorized \code{(Prim '-
  601. (list (Int 8)))} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  602. to show that
  603. \begin{lstlisting}
  604. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  605. \end{lstlisting}
  606. is an $\Exp$ in the \LangInt{} language.
  607. If you have an AST for which the above rules do not apply, then the
  608. AST is not in \LangInt{}. For example, the program \code{(- (read) (+ 8))}
  609. is not in \LangInt{} because there are no rules for \code{+} with only one
  610. argument, nor for \key{-} with two arguments. Whenever we define a
  611. language with a grammar, the language only includes those programs
  612. that are justified by the rules.
  613. The last grammar rule for \LangInt{} states that there is a \code{Program}
  614. node to mark the top of the whole program:
  615. \[
  616. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  617. \]
  618. The \code{Program} structure is defined as follows
  619. \begin{lstlisting}
  620. (struct Program (info body))
  621. \end{lstlisting}
  622. where \code{body} is an expression. In later chapters, the \code{info}
  623. part will be used to store auxiliary information but for now it is
  624. just the empty list.
  625. It is common to have many grammar rules with the same left-hand side
  626. but different right-hand sides, such as the rules for $\Exp$ in the
  627. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  628. combine several right-hand-sides into a single rule.
  629. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  630. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  631. defined in Figure~\ref{fig:r0-concrete-syntax}.
  632. The \code{read-program} function provided in \code{utilities.rkt} of
  633. the support code reads a program in from a file (the sequence of
  634. characters in the concrete syntax of Racket) and parses it into an
  635. abstract syntax tree. See the description of \code{read-program} in
  636. Appendix~\ref{appendix:utilities} for more details.
  637. \begin{figure}[tp]
  638. \fbox{
  639. \begin{minipage}{0.96\textwidth}
  640. \[
  641. \begin{array}{rcl}
  642. \begin{array}{rcl}
  643. \Exp &::=& \Int \mid \LP\key{read}\RP \mid \LP\key{-}\;\Exp\RP \mid \LP\key{+} \; \Exp\;\Exp\RP\\
  644. \LangInt{} &::=& \Exp
  645. \end{array}
  646. \end{array}
  647. \]
  648. \end{minipage}
  649. }
  650. \caption{The concrete syntax of \LangInt{}.}
  651. \label{fig:r0-concrete-syntax}
  652. \end{figure}
  653. \begin{figure}[tp]
  654. \fbox{
  655. \begin{minipage}{0.96\textwidth}
  656. \[
  657. \begin{array}{rcl}
  658. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  659. &\mid& \ADD{\Exp}{\Exp} \\
  660. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  661. \end{array}
  662. \]
  663. \end{minipage}
  664. }
  665. \caption{The abstract syntax of \LangInt{}.}
  666. \label{fig:r0-syntax}
  667. \end{figure}
  668. \section{Pattern Matching}
  669. \label{sec:pattern-matching}
  670. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  671. the parts of an AST node. Racket provides the \texttt{match} form to
  672. access the parts of a structure. Consider the following example and
  673. the output on the right. \index{match} \index{pattern matching}
  674. \begin{center}
  675. \begin{minipage}{0.5\textwidth}
  676. \begin{lstlisting}
  677. (match ast1.1
  678. [(Prim op (list child1 child2))
  679. (print op)])
  680. \end{lstlisting}
  681. \end{minipage}
  682. \vrule
  683. \begin{minipage}{0.25\textwidth}
  684. \begin{lstlisting}
  685. '+
  686. \end{lstlisting}
  687. \end{minipage}
  688. \end{center}
  689. In the above example, the \texttt{match} form takes an AST
  690. \eqref{eq:arith-prog} and binds its parts to the three pattern
  691. variables \texttt{op}, \texttt{child1}, and \texttt{child2}, and then
  692. prints out the operator. In general, a match clause consists of a
  693. \emph{pattern} and a \emph{body}.\index{pattern} Patterns are
  694. recursively defined to be either a pattern variable, a structure name
  695. followed by a pattern for each of the structure's arguments, or an
  696. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  697. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  698. and Chapter 9 of The Racket
  699. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  700. for a complete description of \code{match}.)
  701. %
  702. The body of a match clause may contain arbitrary Racket code. The
  703. pattern variables can be used in the scope of the body, such as
  704. \code{op} in \code{(print op)}.
  705. A \code{match} form may contain several clauses, as in the following
  706. function \code{leaf?} that recognizes when an \LangInt{} node is a leaf in
  707. the AST. The \code{match} proceeds through the clauses in order,
  708. checking whether the pattern can match the input AST. The body of the
  709. first clause that matches is executed. The output of \code{leaf?} for
  710. several ASTs is shown on the right.
  711. \begin{center}
  712. \begin{minipage}{0.6\textwidth}
  713. \begin{lstlisting}
  714. (define (leaf? arith)
  715. (match arith
  716. [(Int n) #t]
  717. [(Prim 'read '()) #t]
  718. [(Prim '- (list e1)) #f]
  719. [(Prim '+ (list e1 e2)) #f]))
  720. (leaf? (Prim 'read '()))
  721. (leaf? (Prim '- (list (Int 8))))
  722. (leaf? (Int 8))
  723. \end{lstlisting}
  724. \end{minipage}
  725. \vrule
  726. \begin{minipage}{0.25\textwidth}
  727. \begin{lstlisting}
  728. #t
  729. #f
  730. #t
  731. \end{lstlisting}
  732. \end{minipage}
  733. \end{center}
  734. When writing a \code{match}, we refer to the grammar definition to
  735. identify which non-terminal we are expecting to match against, then we
  736. make sure that 1) we have one clause for each alternative of that
  737. non-terminal and 2) that the pattern in each clause corresponds to the
  738. corresponding right-hand side of a grammar rule. For the \code{match}
  739. in the \code{leaf?} function, we refer to the grammar for \LangInt{} in
  740. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  741. alternatives, so the \code{match} has 4 clauses. The pattern in each
  742. clause corresponds to the right-hand side of a grammar rule. For
  743. example, the pattern \code{(Prim '+ (list e1 e2))} corresponds to the
  744. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  745. patterns, replace non-terminals such as $\Exp$ with pattern variables
  746. of your choice (e.g. \code{e1} and \code{e2}).
  747. \section{Recursive Functions}
  748. \label{sec:recursion}
  749. \index{recursive function}
  750. Programs are inherently recursive. For example, an \LangInt{} expression is
  751. often made of smaller expressions. Thus, the natural way to process an
  752. entire program is with a recursive function. As a first example of
  753. such a recursive function, we define \texttt{exp?} below, which takes
  754. an arbitrary value and determines whether or not it is an \LangInt{}
  755. expression.
  756. %
  757. We say that a function is defined by \emph{structural recursion} when
  758. it is defined using a sequence of match clauses that correspond to a
  759. grammar, and the body of each clause makes a recursive call on each
  760. child node.\footnote{This principle of structuring code according to
  761. the data definition is advocated in the book \emph{How to Design
  762. Programs} \url{https://htdp.org/2020-8-1/Book/index.html}.}.
  763. Below we also define a second function, named \code{Rint?}, that
  764. determines whether an AST is an \LangInt{} program. In general we can
  765. expect to write one recursive function to handle each non-terminal in
  766. a grammar.\index{structural recursion}
  767. %
  768. \begin{center}
  769. \begin{minipage}{0.7\textwidth}
  770. \begin{lstlisting}
  771. (define (exp? ast)
  772. (match ast
  773. [(Int n) #t]
  774. [(Prim 'read '()) #t]
  775. [(Prim '- (list e)) (exp? e)]
  776. [(Prim '+ (list e1 e2))
  777. (and (exp? e1) (exp? e2))]
  778. [else #f]))
  779. (define (Rint? ast)
  780. (match ast
  781. [(Program '() e) (exp? e)]
  782. [else #f]))
  783. (Rint? (Program '() ast1.1)
  784. (Rint? (Program '()
  785. (Prim '- (list (Prim 'read '())
  786. (Prim '+ (list (Num 8)))))))
  787. \end{lstlisting}
  788. \end{minipage}
  789. \vrule
  790. \begin{minipage}{0.25\textwidth}
  791. \begin{lstlisting}
  792. #t
  793. #f
  794. \end{lstlisting}
  795. \end{minipage}
  796. \end{center}
  797. You may be tempted to merge the two functions into one, like this:
  798. \begin{center}
  799. \begin{minipage}{0.5\textwidth}
  800. \begin{lstlisting}
  801. (define (Rint? ast)
  802. (match ast
  803. [(Int n) #t]
  804. [(Prim 'read '()) #t]
  805. [(Prim '- (list e)) (Rint? e)]
  806. [(Prim '+ (list e1 e2)) (and (Rint? e1) (Rint? e2))]
  807. [(Program '() e) (Rint? e)]
  808. [else #f]))
  809. \end{lstlisting}
  810. \end{minipage}
  811. \end{center}
  812. %
  813. Sometimes such a trick will save a few lines of code, especially when
  814. it comes to the \code{Program} wrapper. Yet this style is generally
  815. \emph{not} recommended because it can get you into trouble.
  816. %
  817. For example, the above function is subtly wrong:
  818. \lstinline{(Rint? (Program '() (Program '() (Int 3))))}
  819. returns true when it should return false.
  820. \section{Interpreters}
  821. \label{sec:interp-Rint}
  822. \index{interpreter}
  823. In general, the intended behavior of a program is defined by the
  824. specification of the language. For example, the Scheme language is
  825. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  826. defined in its reference manual~\citep{plt-tr}. In this book we use
  827. interpreters to specify each language that we consider. An interpreter
  828. that is designated as the definition of a language is called a
  829. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  830. \index{definitional interpreter} We warm up by creating a definitional
  831. interpreter for the \LangInt{} language, which serves as a second example
  832. of structural recursion. The \texttt{interp-Rint} function is defined in
  833. Figure~\ref{fig:interp-Rint}. The body of the function is a match on the
  834. input program followed by a call to the \lstinline{interp-exp} helper
  835. function, which in turn has one match clause per grammar rule for
  836. \LangInt{} expressions.
  837. \begin{figure}[tp]
  838. \begin{lstlisting}
  839. (define (interp-exp e)
  840. (match e
  841. [(Int n) n]
  842. [(Prim 'read '())
  843. (define r (read))
  844. (cond [(fixnum? r) r]
  845. [else (error 'interp-exp "read expected an integer" r)])]
  846. [(Prim '- (list e))
  847. (define v (interp-exp e))
  848. (fx- 0 v)]
  849. [(Prim '+ (list e1 e2))
  850. (define v1 (interp-exp e1))
  851. (define v2 (interp-exp e2))
  852. (fx+ v1 v2)]))
  853. (define (interp-Rint p)
  854. (match p
  855. [(Program '() e) (interp-exp e)]))
  856. \end{lstlisting}
  857. \caption{Interpreter for the \LangInt{} language.}
  858. \label{fig:interp-Rint}
  859. \end{figure}
  860. Let us consider the result of interpreting a few \LangInt{} programs. The
  861. following program adds two integers.
  862. \begin{lstlisting}
  863. (+ 10 32)
  864. \end{lstlisting}
  865. The result is \key{42}, the answer to life, the universe, and
  866. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  867. Galaxy} by Douglas Adams.}.
  868. %
  869. We wrote the above program in concrete syntax whereas the parsed
  870. abstract syntax is:
  871. \begin{lstlisting}
  872. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  873. \end{lstlisting}
  874. The next example demonstrates that expressions may be nested within
  875. each other, in this case nesting several additions and negations.
  876. \begin{lstlisting}
  877. (+ 10 (- (+ 12 20)))
  878. \end{lstlisting}
  879. What is the result of the above program?
  880. As mentioned previously, the \LangInt{} language does not support
  881. arbitrarily-large integers, but only $63$-bit integers, so we
  882. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  883. in Racket.
  884. Suppose
  885. \[
  886. n = 999999999999999999
  887. \]
  888. which indeed fits in $63$-bits. What happens when we run the
  889. following program in our interpreter?
  890. \begin{lstlisting}
  891. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  892. \end{lstlisting}
  893. It produces an error:
  894. \begin{lstlisting}
  895. fx+: result is not a fixnum
  896. \end{lstlisting}
  897. We establish the convention that if running the definitional
  898. interpreter on a program produces an error then the meaning of that
  899. program is \emph{unspecified}\index{unspecified behavior}, unless the
  900. error is a \code{trapped-error}. A compiler for the language is under
  901. no obligations regarding programs with unspecified behavior; it does
  902. not have to produce an executable, and if it does, that executable can
  903. do anything. On the other hand, if the error is a
  904. \code{trapped-error}, then the compiler must produce an executable and
  905. it is required to report that an error occurred. To signal an error,
  906. exit with a return code of \code{255}. The interpreters in chapters
  907. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  908. \code{trapped-error}.
  909. %% This convention applies to the languages defined in this
  910. %% book, as a way to simplify the student's task of implementing them,
  911. %% but this convention is not applicable to all programming languages.
  912. %%
  913. Moving on to the last feature of the \LangInt{} language, the \key{read}
  914. operation prompts the user of the program for an integer. Recall that
  915. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  916. \code{8}. So if we run
  917. \begin{lstlisting}
  918. (interp-Rint (Program '() ast1.1))
  919. \end{lstlisting}
  920. and if the input is \code{50}, the result is \code{42}.
  921. We include the \key{read} operation in \LangInt{} so a clever student
  922. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  923. during compilation to obtain the output and then generates the trivial
  924. code to produce the output. (Yes, a clever student did this in the
  925. first instance of this course.)
  926. The job of a compiler is to translate a program in one language into a
  927. program in another language so that the output program behaves the
  928. same way as the input program does. This idea is depicted in the
  929. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  930. $\mathcal{L}_2$, and a definitional interpreter for each language.
  931. Given a compiler that translates from language $\mathcal{L}_1$ to
  932. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  933. compiler must translate it into some program $P_2$ such that
  934. interpreting $P_1$ and $P_2$ on their respective interpreters with
  935. same input $i$ yields the same output $o$.
  936. \begin{equation} \label{eq:compile-correct}
  937. \begin{tikzpicture}[baseline=(current bounding box.center)]
  938. \node (p1) at (0, 0) {$P_1$};
  939. \node (p2) at (3, 0) {$P_2$};
  940. \node (o) at (3, -2.5) {$o$};
  941. \path[->] (p1) edge [above] node {compile} (p2);
  942. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  943. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  944. \end{tikzpicture}
  945. \end{equation}
  946. In the next section we see our first example of a compiler.
  947. \section{Example Compiler: a Partial Evaluator}
  948. \label{sec:partial-evaluation}
  949. In this section we consider a compiler that translates \LangInt{} programs
  950. into \LangInt{} programs that may be more efficient, that is, this compiler
  951. is an optimizer. This optimizer eagerly computes the parts of the
  952. program that do not depend on any inputs, a process known as
  953. \emph{partial evaluation}~\citep{Jones:1993uq}.
  954. \index{partial evaluation}
  955. For example, given the following program
  956. \begin{lstlisting}
  957. (+ (read) (- (+ 5 3)))
  958. \end{lstlisting}
  959. our compiler will translate it into the program
  960. \begin{lstlisting}
  961. (+ (read) -8)
  962. \end{lstlisting}
  963. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  964. evaluator for the \LangInt{} language. The output of the partial evaluator
  965. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  966. recursion over $\Exp$ is captured in the \code{pe-exp} function
  967. whereas the code for partially evaluating the negation and addition
  968. operations is factored into two separate helper functions:
  969. \code{pe-neg} and \code{pe-add}. The input to these helper
  970. functions is the output of partially evaluating the children.
  971. \begin{figure}[tp]
  972. \begin{lstlisting}
  973. (define (pe-neg r)
  974. (match r
  975. [(Int n) (Int (fx- 0 n))]
  976. [else (Prim '- (list r))]))
  977. (define (pe-add r1 r2)
  978. (match* (r1 r2)
  979. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  980. [(_ _) (Prim '+ (list r1 r2))]))
  981. (define (pe-exp e)
  982. (match e
  983. [(Int n) (Int n)]
  984. [(Prim 'read '()) (Prim 'read '())]
  985. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  986. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]))
  987. (define (pe-Rint p)
  988. (match p
  989. [(Program '() e) (Program '() (pe-exp e))]))
  990. \end{lstlisting}
  991. \caption{A partial evaluator for \LangInt{}.}
  992. \label{fig:pe-arith}
  993. \end{figure}
  994. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  995. arguments are integers and if they are, perform the appropriate
  996. arithmetic. Otherwise, they create an AST node for the arithmetic
  997. operation.
  998. To gain some confidence that the partial evaluator is correct, we can
  999. test whether it produces programs that get the same result as the
  1000. input programs. That is, we can test whether it satisfies Diagram
  1001. \ref{eq:compile-correct}. The following code runs the partial
  1002. evaluator on several examples and tests the output program. The
  1003. \texttt{parse-program} and \texttt{assert} functions are defined in
  1004. Appendix~\ref{appendix:utilities}.\\
  1005. \begin{minipage}{1.0\textwidth}
  1006. \begin{lstlisting}
  1007. (define (test-pe p)
  1008. (assert "testing pe-Rint"
  1009. (equal? (interp-Rint p) (interp-Rint (pe-Rint p)))))
  1010. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1011. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1012. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  1013. \end{lstlisting}
  1014. \end{minipage}
  1015. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1016. \chapter{Integers and Variables}
  1017. \label{ch:Rvar}
  1018. This chapter is about compiling a subset of Racket to x86-64 assembly
  1019. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1020. integer arithmetic and local variable binding. We often refer to
  1021. x86-64 simply as x86. The chapter begins with a description of the
  1022. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1023. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  1024. is large so we discuss only the instructions needed for compiling
  1025. \LangVar{}. We introduce more x86 instructions in later chapters.
  1026. After introducing \LangVar{} and x86, we reflect on their differences
  1027. and come up with a plan to break down the translation from \LangVar{}
  1028. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1029. rest of the sections in this chapter give detailed hints regarding
  1030. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  1031. We hope to give enough hints that the well-prepared reader, together
  1032. with a few friends, can implement a compiler from \LangVar{} to x86 in
  1033. a couple weeks. To give the reader a feeling for the scale of this
  1034. first compiler, the instructor solution for the \LangVar{} compiler is
  1035. approximately 500 lines of code.
  1036. \section{The \LangVar{} Language}
  1037. \label{sec:s0}
  1038. \index{variable}
  1039. The \LangVar{} language extends the \LangInt{} language with variable
  1040. definitions. The concrete syntax of the \LangVar{} language is defined by
  1041. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  1042. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  1043. \Var{} may be any Racket identifier. As in \LangInt{}, \key{read} is a
  1044. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  1045. operator. Similar to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1046. \key{Program} struct to mark the top of the program.
  1047. %% The $\itm{info}$
  1048. %% field of the \key{Program} structure contains an \emph{association
  1049. %% list} (a list of key-value pairs) that is used to communicate
  1050. %% auxiliary data from one compiler pass the next.
  1051. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1052. exhibit several compilation techniques.
  1053. \begin{figure}[tp]
  1054. \centering
  1055. \fbox{
  1056. \begin{minipage}{0.96\textwidth}
  1057. \[
  1058. \begin{array}{rcl}
  1059. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  1060. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  1061. \LangVar{} &::=& \Exp
  1062. \end{array}
  1063. \]
  1064. \end{minipage}
  1065. }
  1066. \caption{The concrete syntax of \LangVar{}.}
  1067. \label{fig:r1-concrete-syntax}
  1068. \end{figure}
  1069. \begin{figure}[tp]
  1070. \centering
  1071. \fbox{
  1072. \begin{minipage}{0.96\textwidth}
  1073. \[
  1074. \begin{array}{rcl}
  1075. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1076. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1077. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1078. \LangVar{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1079. \end{array}
  1080. \]
  1081. \end{minipage}
  1082. }
  1083. \caption{The abstract syntax of \LangVar{}.}
  1084. \label{fig:r1-syntax}
  1085. \end{figure}
  1086. Let us dive further into the syntax and semantics of the \LangVar{}
  1087. language. The \key{let} feature defines a variable for use within its
  1088. body and initializes the variable with the value of an expression.
  1089. The abstract syntax for \key{let} is defined in
  1090. Figure~\ref{fig:r1-syntax}. The concrete syntax for \key{let} is
  1091. \begin{lstlisting}
  1092. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1093. \end{lstlisting}
  1094. For example, the following program initializes \code{x} to $32$ and then
  1095. evaluates the body \code{(+ 10 x)}, producing $42$.
  1096. \begin{lstlisting}
  1097. (let ([x (+ 12 20)]) (+ 10 x))
  1098. \end{lstlisting}
  1099. When there are multiple \key{let}'s for the same variable, the closest
  1100. enclosing \key{let} is used. That is, variable definitions overshadow
  1101. prior definitions. Consider the following program with two \key{let}'s
  1102. that define variables named \code{x}. Can you figure out the result?
  1103. \begin{lstlisting}
  1104. (let ([x 32]) (+ (let ([x 10]) x) x))
  1105. \end{lstlisting}
  1106. For the purposes of depicting which variable uses correspond to which
  1107. definitions, the following shows the \code{x}'s annotated with
  1108. subscripts to distinguish them. Double check that your answer for the
  1109. above is the same as your answer for this annotated version of the
  1110. program.
  1111. \begin{lstlisting}
  1112. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1113. \end{lstlisting}
  1114. The initializing expression is always evaluated before the body of the
  1115. \key{let}, so in the following, the \key{read} for \code{x} is
  1116. performed before the \key{read} for \code{y}. Given the input
  1117. $52$ then $10$, the following produces $42$ (not $-42$).
  1118. \begin{lstlisting}
  1119. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1120. \end{lstlisting}
  1121. \subsection{Extensible Interpreters via Method Overriding}
  1122. \label{sec:extensible-interp}
  1123. To prepare for discussing the interpreter for \LangVar{}, we need to
  1124. explain why we choose to implement the interpreter using
  1125. object-oriented programming, that is, as a collection of methods
  1126. inside of a class. Throughout this book we define many interpreters,
  1127. one for each of the languages that we study. Because each language
  1128. builds on the prior one, there is a lot of commonality between their
  1129. interpreters. We want to write down those common parts just once
  1130. instead of many times. A naive approach would be to have, for example,
  1131. the interpreter for \LangIf{} handle all of the new features in that
  1132. language and then have a default case that dispatches to the
  1133. interpreter for \LangVar{}. The following code sketches this idea.
  1134. \begin{center}
  1135. \begin{minipage}{0.45\textwidth}
  1136. \begin{lstlisting}
  1137. (define (interp-Rvar e)
  1138. (match e
  1139. [(Prim '- (list e))
  1140. (fx- 0 (interp-Rvar e))]
  1141. ...))
  1142. \end{lstlisting}
  1143. \end{minipage}
  1144. \begin{minipage}{0.45\textwidth}
  1145. \begin{lstlisting}
  1146. (define (interp-Rif e)
  1147. (match e
  1148. [(If cnd thn els)
  1149. (match (interp-Rif cnd)
  1150. [#t (interp-Rif thn)]
  1151. [#f (interp-Rif els)])]
  1152. ...
  1153. [else (interp-Rvar e)]))
  1154. \end{lstlisting}
  1155. \end{minipage}
  1156. \end{center}
  1157. The problem with this approach is that it does not handle situations
  1158. in which an \LangIf{} feature, like \code{If}, is nested inside an \LangVar{}
  1159. feature, like the \code{-} operator, as in the following program.
  1160. \begin{lstlisting}
  1161. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1162. \end{lstlisting}
  1163. If we invoke \code{interp-Rif} on this program, it dispatches to
  1164. \code{interp-Rvar} to handle the \code{-} operator, but then it
  1165. recurisvely calls \code{interp-Rvar} again on the argument of \code{-},
  1166. which is an \code{If}. But there is no case for \code{If} in
  1167. \code{interp-Rvar}, so we get an error!
  1168. To make our interpreters extensible we need something called
  1169. \emph{open recursion}\index{open recursion}, where the tying of the
  1170. recursive knot is delayed to when the functions are
  1171. composed. Object-oriented languages provide open recursion with the
  1172. late-binding of overridden methods\index{method overriding}. The
  1173. following code sketches this idea for interpreting \LangVar{} and
  1174. \LangIf{} using the
  1175. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1176. \index{class} feature of Racket. We define one class for each
  1177. language and define a method for interpreting expressions inside each
  1178. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1179. and the method \code{interp-exp} in \LangIf{} overrides the
  1180. \code{interp-exp} in \LangVar{}. Note that the default case of
  1181. \code{interp-exp} in \LangIf{} uses \code{super} to invoke
  1182. \code{interp-exp}, and because \LangIf{} inherits from \LangVar{},
  1183. that dispatches to the \code{interp-exp} in \LangVar{}.
  1184. \begin{center}
  1185. \begin{minipage}{0.45\textwidth}
  1186. \begin{lstlisting}
  1187. (define interp-Rvar-class
  1188. (class object%
  1189. (define/public (interp-exp e)
  1190. (match e
  1191. [(Prim '- (list e))
  1192. (fx- 0 (interp-exp e))]
  1193. ...))
  1194. ...))
  1195. \end{lstlisting}
  1196. \end{minipage}
  1197. \begin{minipage}{0.45\textwidth}
  1198. \begin{lstlisting}
  1199. (define interp-Rif-class
  1200. (class interp-Rvar-class
  1201. (define/override (interp-exp e)
  1202. (match e
  1203. [(If cnd thn els)
  1204. (match (interp-exp cnd)
  1205. [#t (interp-exp thn)]
  1206. [#f (interp-exp els)])]
  1207. ...
  1208. [else (super interp-exp e)]))
  1209. ...
  1210. ))
  1211. \end{lstlisting}
  1212. \end{minipage}
  1213. \end{center}
  1214. Getting back to the troublesome example, repeated here:
  1215. \begin{lstlisting}
  1216. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1217. \end{lstlisting}
  1218. We can invoke the \code{interp-exp} method for \LangIf{} on this
  1219. expression by creating an object of the \LangIf{} class and sending it the
  1220. \code{interp-exp} method with the argument \code{e0}.
  1221. \begin{lstlisting}
  1222. (send (new interp-Rif-class) interp-exp e0)
  1223. \end{lstlisting}
  1224. The default case of \code{interp-exp} in \LangIf{} handles it by
  1225. dispatching to the \code{interp-exp} method in \LangVar{}, which
  1226. handles the \code{-} operator. But then for the recursive method call,
  1227. it dispatches back to \code{interp-exp} in \LangIf{}, where the
  1228. \code{If} is handled correctly. Thus, method overriding gives us the
  1229. open recursion that we need to implement our interpreters in an
  1230. extensible way.
  1231. \newpage
  1232. \subsection{Definitional Interpreter for \LangVar{}}
  1233. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  1234. \small
  1235. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1236. An \emph{association list} (alist) is a list of key-value pairs.
  1237. For example, we can map people to their ages with an alist.
  1238. \index{alist}\index{association list}
  1239. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1240. (define ages
  1241. '((jane . 25) (sam . 24) (kate . 45)))
  1242. \end{lstlisting}
  1243. The \emph{dictionary} interface is for mapping keys to values.
  1244. Every alist implements this interface. \index{dictionary} The package
  1245. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1246. provides many functions for working with dictionaries. Here
  1247. are a few of them:
  1248. \begin{description}
  1249. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1250. returns the value associated with the given $\itm{key}$.
  1251. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1252. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1253. but otherwise is the same as $\itm{dict}$.
  1254. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1255. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1256. of keys and values in $\itm{dict}$. For example, the following
  1257. creates a new alist in which the ages are incremented.
  1258. \end{description}
  1259. \vspace{-10pt}
  1260. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1261. (for/list ([(k v) (in-dict ages)])
  1262. (cons k (add1 v)))
  1263. \end{lstlisting}
  1264. \end{tcolorbox}
  1265. \end{wrapfigure}
  1266. Having justified the use of classes and methods to implement
  1267. interpreters, we turn to the definitional interpreter for \LangVar{}
  1268. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1269. \LangInt{} but adds two new \key{match} cases for variables and
  1270. \key{let}. For \key{let} we need a way to communicate the value bound
  1271. to a variable to all the uses of the variable. To accomplish this, we
  1272. maintain a mapping from variables to values. Throughout the compiler
  1273. we often need to map variables to information about them. We refer to
  1274. these mappings as
  1275. \emph{environments}\index{environment}.\footnote{Another common term
  1276. for environment in the compiler literature is \emph{symbol
  1277. table}\index{symbol table}.}
  1278. %
  1279. For simplicity, we use an association list (alist) to represent the
  1280. environment. The sidebar to the right gives a brief introduction to
  1281. alists and the \code{racket/dict} package. The \code{interp-exp}
  1282. function takes the current environment, \code{env}, as an extra
  1283. parameter. When the interpreter encounters a variable, it finds the
  1284. corresponding value using the \code{dict-ref} function. When the
  1285. interpreter encounters a \key{Let}, it evaluates the initializing
  1286. expression, extends the environment with the result value bound to the
  1287. variable, using \code{dict-set}, then evaluates the body of the
  1288. \key{Let}.
  1289. \begin{figure}[tp]
  1290. \begin{lstlisting}
  1291. (define interp-Rvar-class
  1292. (class object%
  1293. (super-new)
  1294. (define/public ((interp-exp env) e)
  1295. (match e
  1296. [(Int n) n]
  1297. [(Prim 'read '())
  1298. (define r (read))
  1299. (cond [(fixnum? r) r]
  1300. [else (error 'interp-exp "expected an integer" r)])]
  1301. [(Prim '- (list e)) (fx- 0 ((interp-exp env) e))]
  1302. [(Prim '+ (list e1 e2))
  1303. (fx+ ((interp-exp env) e1) ((interp-exp env) e2))]
  1304. [(Var x) (dict-ref env x)]
  1305. [(Let x e body)
  1306. (define new-env (dict-set env x ((interp-exp env) e)))
  1307. ((interp-exp new-env) body)]))
  1308. (define/public (interp-program p)
  1309. (match p
  1310. [(Program '() e) ((interp-exp '()) e)]))
  1311. ))
  1312. (define (interp-Rvar p)
  1313. (send (new interp-Rvar-class) interp-program p))
  1314. \end{lstlisting}
  1315. \caption{Interpreter for the \LangVar{} language.}
  1316. \label{fig:interp-Rvar}
  1317. \end{figure}
  1318. The goal for this chapter is to implement a compiler that translates
  1319. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1320. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1321. computer as the $P_1$ program interpreted by \code{interp-Rvar}. That
  1322. is, they output the same integer $n$. We depict this correctness
  1323. criteria in the following diagram.
  1324. \[
  1325. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1326. \node (p1) at (0, 0) {$P_1$};
  1327. \node (p2) at (4, 0) {$P_2$};
  1328. \node (o) at (4, -2) {$n$};
  1329. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1330. \path[->] (p1) edge [left] node {\footnotesize\code{interp-Rvar}} (o);
  1331. \path[->] (p2) edge [right] node {\footnotesize\code{interp-x86int}} (o);
  1332. \end{tikzpicture}
  1333. \]
  1334. In the next section we introduce the \LangXInt{} subset of x86 that
  1335. suffices for compiling \LangVar{}.
  1336. \section{The \LangXInt{} Assembly Language}
  1337. \label{sec:x86}
  1338. \index{x86}
  1339. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1340. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1341. assembler.
  1342. %
  1343. A program begins with a \code{main} label followed by a sequence of
  1344. instructions. The \key{globl} directive says that the \key{main}
  1345. procedure is externally visible, which is necessary so that the
  1346. operating system can call it. In the grammar, ellipses such as
  1347. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1348. \ldots$ is a sequence of instructions.\index{instruction}
  1349. %
  1350. An x86 program is stored in the computer's memory. For our purposes,
  1351. the computer's memory is a mapping of 64-bit addresses to 64-bit
  1352. values. The computer has a \emph{program counter} (PC)\index{program
  1353. counter}\index{PC} stored in the \code{rip} register that points to
  1354. the address of the next instruction to be executed. For most
  1355. instructions, the program counter is incremented after the instruction
  1356. is executed, so it points to the next instruction in memory. Most x86
  1357. instructions take two operands, where each operand is either an
  1358. integer constant (called an \emph{immediate value}\index{immediate
  1359. value}), a \emph{register}\index{register}, or a memory location.
  1360. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1361. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1362. && \key{r8} \mid \key{r9} \mid \key{r10}
  1363. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1364. \mid \key{r14} \mid \key{r15}}
  1365. \begin{figure}[tp]
  1366. \fbox{
  1367. \begin{minipage}{0.96\textwidth}
  1368. \[
  1369. \begin{array}{lcl}
  1370. \Reg &::=& \allregisters{} \\
  1371. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1372. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1373. \key{subq} \; \Arg\key{,} \Arg \mid
  1374. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1375. && \key{callq} \; \mathit{label} \mid
  1376. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1377. && \itm{label}\key{:}\; \Instr \\
  1378. \LangXInt{} &::= & \key{.globl main}\\
  1379. & & \key{main:} \; \Instr\ldots
  1380. \end{array}
  1381. \]
  1382. \end{minipage}
  1383. }
  1384. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  1385. \label{fig:x86-int-concrete}
  1386. \end{figure}
  1387. A register is a special kind of variable. Each one holds a 64-bit
  1388. value; there are 16 general-purpose registers in the computer and
  1389. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1390. is written with a \key{\%} followed by the register name, such as
  1391. \key{\%rax}.
  1392. An immediate value is written using the notation \key{\$}$n$ where $n$
  1393. is an integer.
  1394. %
  1395. %
  1396. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1397. which obtains the address stored in register $r$ and then adds $n$
  1398. bytes to the address. The resulting address is used to load or store
  1399. to memory depending on whether it occurs as a source or destination
  1400. argument of an instruction.
  1401. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1402. source $s$ and destination $d$, applies the arithmetic operation, then
  1403. writes the result back to the destination $d$.
  1404. %
  1405. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1406. stores the result in $d$.
  1407. %
  1408. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1409. specified by the label and $\key{retq}$ returns from a procedure to
  1410. its caller.
  1411. %
  1412. We discuss procedure calls in more detail later in this chapter and in
  1413. Chapter~\ref{ch:Rfun}. The instruction $\key{jmp}\,\itm{label}$
  1414. updates the program counter to the address of the instruction after
  1415. the specified label.
  1416. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1417. all of the x86 instructions used in this book.
  1418. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent to
  1419. \code{(+ 10 32)}. The instruction \lstinline{movq $10, %rax}
  1420. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1421. adds $32$ to the $10$ in \key{rax} and
  1422. puts the result, $42$, back into \key{rax}.
  1423. %
  1424. The last instruction, \key{retq}, finishes the \key{main} function by
  1425. returning the integer in \key{rax} to the operating system. The
  1426. operating system interprets this integer as the program's exit
  1427. code. By convention, an exit code of 0 indicates that a program
  1428. completed successfully, and all other exit codes indicate various
  1429. errors. Nevertheless, in this book we return the result of the program
  1430. as the exit code.
  1431. \begin{figure}[tbp]
  1432. \begin{lstlisting}
  1433. .globl main
  1434. main:
  1435. movq $10, %rax
  1436. addq $32, %rax
  1437. retq
  1438. \end{lstlisting}
  1439. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1440. \label{fig:p0-x86}
  1441. \end{figure}
  1442. The x86 assembly language varies in a couple of ways depending on what
  1443. operating system it is assembled in. The code examples shown here are
  1444. correct on Linux and most Unix-like platforms, but when assembled on
  1445. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1446. as in \key{\_main}.
  1447. We exhibit the use of memory for storing intermediate results in the
  1448. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1449. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1450. memory called the \emph{procedure call stack} (or \emph{stack} for
  1451. short). \index{stack}\index{procedure call stack} The stack consists
  1452. of a separate \emph{frame}\index{frame} for each procedure call. The
  1453. memory layout for an individual frame is shown in
  1454. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1455. \emph{stack pointer}\index{stack pointer} and points to the item at
  1456. the top of the stack. The stack grows downward in memory, so we
  1457. increase the size of the stack by subtracting from the stack pointer.
  1458. In the context of a procedure call, the \emph{return
  1459. address}\index{return address} is the instruction after the call
  1460. instruction on the caller side. The function call instruction,
  1461. \code{callq}, pushes the return address onto the stack prior to
  1462. jumping to the procedure. The register \key{rbp} is the \emph{base
  1463. pointer}\index{base pointer} and is used to access variables that
  1464. are stored in the frame of the current procedure call. The base
  1465. pointer of the caller is pushed onto the stack after the return
  1466. address and then the base pointer is set to the location of the old
  1467. base pointer. In Figure~\ref{fig:frame} we number the variables from
  1468. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  1469. variable $2$ at $-16\key{(\%rbp)}$, etc.
  1470. \begin{figure}[tbp]
  1471. \begin{lstlisting}
  1472. start:
  1473. movq $10, -8(%rbp)
  1474. negq -8(%rbp)
  1475. movq -8(%rbp), %rax
  1476. addq $52, %rax
  1477. jmp conclusion
  1478. .globl main
  1479. main:
  1480. pushq %rbp
  1481. movq %rsp, %rbp
  1482. subq $16, %rsp
  1483. jmp start
  1484. conclusion:
  1485. addq $16, %rsp
  1486. popq %rbp
  1487. retq
  1488. \end{lstlisting}
  1489. \caption{An x86 program equivalent to \code{(+ 52 (- 10))}.}
  1490. \label{fig:p1-x86}
  1491. \end{figure}
  1492. \begin{figure}[tbp]
  1493. \centering
  1494. \begin{tabular}{|r|l|} \hline
  1495. Position & Contents \\ \hline
  1496. 8(\key{\%rbp}) & return address \\
  1497. 0(\key{\%rbp}) & old \key{rbp} \\
  1498. -8(\key{\%rbp}) & variable $1$ \\
  1499. -16(\key{\%rbp}) & variable $2$ \\
  1500. \ldots & \ldots \\
  1501. 0(\key{\%rsp}) & variable $n$\\ \hline
  1502. \end{tabular}
  1503. \caption{Memory layout of a frame.}
  1504. \label{fig:frame}
  1505. \end{figure}
  1506. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1507. control is transferred from the operating system to the \code{main}
  1508. function. The operating system issues a \code{callq main} instruction
  1509. which pushes its return address on the stack and then jumps to
  1510. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1511. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1512. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1513. alignment (because the \code{callq} pushed the return address). The
  1514. first three instructions are the typical \emph{prelude}\index{prelude}
  1515. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1516. pointer for the caller onto the stack and subtracts $8$ from the stack
  1517. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  1518. base pointer so that it points the location of the old base
  1519. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1520. pointer down to make enough room for storing variables. This program
  1521. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  1522. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  1523. functions. The last instruction of the prelude is \code{jmp start},
  1524. which transfers control to the instructions that were generated from
  1525. the Racket expression \code{(+ 52 (- 10))}.
  1526. The first instruction under the \code{start} label is
  1527. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  1528. %
  1529. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1530. %
  1531. The next instruction moves the $-10$ from variable $1$ into the
  1532. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1533. the value in \code{rax}, updating its contents to $42$.
  1534. The three instructions under the label \code{conclusion} are the
  1535. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1536. two instructions restore the \code{rsp} and \code{rbp} registers to
  1537. the state they were in at the beginning of the procedure. The
  1538. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  1539. point at the old base pointer. Then \key{popq \%rbp} returns the old
  1540. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1541. instruction, \key{retq}, jumps back to the procedure that called this
  1542. one and adds $8$ to the stack pointer.
  1543. The compiler needs a convenient representation for manipulating x86
  1544. programs, so we define an abstract syntax for x86 in
  1545. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  1546. \LangXInt{}. The main difference compared to the concrete syntax of
  1547. \LangXInt{} (Figure~\ref{fig:x86-int-concrete}) is that labels are not
  1548. allowed in front of every instruction. Instead instructions are
  1549. grouped into \emph{blocks}\index{block}\index{basic block} with a
  1550. label associated with every block, which is why the \key{X86Program}
  1551. struct includes an alist mapping labels to blocks. The reason for this
  1552. organization becomes apparent in Chapter~\ref{ch:Rif} when we
  1553. introduce conditional branching. The \code{Block} structure includes
  1554. an $\itm{info}$ field that is not needed for this chapter, but becomes
  1555. useful in Chapter~\ref{ch:register-allocation-Rvar}. For now, the
  1556. $\itm{info}$ field should contain an empty list. Also, regarding the
  1557. abstract syntax for \code{callq}, the \code{Callq} struct includes an
  1558. integer for representing the arity of the function, i.e., the number
  1559. of arguments, which is helpful to know during register allocation
  1560. (Chapter~\ref{ch:register-allocation-Rvar}).
  1561. \begin{figure}[tp]
  1562. \fbox{
  1563. \begin{minipage}{0.98\textwidth}
  1564. \small
  1565. \[
  1566. \begin{array}{lcl}
  1567. \Reg &::=& \allregisters{} \\
  1568. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1569. \mid \DEREF{\Reg}{\Int} \\
  1570. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  1571. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  1572. &\mid& \BININSTR{\code{movq}}{\Arg}{\Arg}
  1573. \mid \UNIINSTR{\code{negq}}{\Arg}\\
  1574. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1575. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1576. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  1577. \LangXInt{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  1578. \end{array}
  1579. \]
  1580. \end{minipage}
  1581. }
  1582. \caption{The abstract syntax of \LangXInt{} assembly.}
  1583. \label{fig:x86-int-ast}
  1584. \end{figure}
  1585. \section{Planning the trip to x86 via the \LangCVar{} language}
  1586. \label{sec:plan-s0-x86}
  1587. To compile one language to another it helps to focus on the
  1588. differences between the two languages because the compiler will need
  1589. to bridge those differences. What are the differences between \LangVar{}
  1590. and x86 assembly? Here are some of the most important ones:
  1591. \begin{enumerate}
  1592. \item[(a)] x86 arithmetic instructions typically have two arguments
  1593. and update the second argument in place. In contrast, \LangVar{}
  1594. arithmetic operations take two arguments and produce a new value.
  1595. An x86 instruction may have at most one memory-accessing argument.
  1596. Furthermore, some instructions place special restrictions on their
  1597. arguments.
  1598. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  1599. expression, whereas x86 instructions restrict their arguments to be
  1600. integer constants, registers, and memory locations.
  1601. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1602. sequence of instructions and jumps to labeled positions, whereas in
  1603. \LangVar{} the order of evaluation is a left-to-right depth-first
  1604. traversal of the abstract syntax tree.
  1605. \item[(d)] A program in \LangVar{} can have any number of variables
  1606. whereas x86 has 16 registers and the procedure calls stack.
  1607. \item[(e)] Variables in \LangVar{} can shadow other variables with the
  1608. same name. In x86, registers have unique names and memory locations
  1609. have unique addresses.
  1610. \end{enumerate}
  1611. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  1612. the problem into several steps, dealing with the above differences one
  1613. at a time. Each of these steps is called a \emph{pass} of the
  1614. compiler.\index{pass}\index{compiler pass}
  1615. %
  1616. This terminology comes from the way each step passes over the AST of
  1617. the program.
  1618. %
  1619. We begin by sketching how we might implement each pass, and give them
  1620. names. We then figure out an ordering of the passes and the
  1621. input/output language for each pass. The very first pass has
  1622. \LangVar{} as its input language and the last pass has \LangXInt{} as
  1623. its output language. In between we can choose whichever language is
  1624. most convenient for expressing the output of each pass, whether that
  1625. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  1626. our own design. Finally, to implement each pass we write one
  1627. recursive function per non-terminal in the grammar of the input
  1628. language of the pass. \index{intermediate language}
  1629. \begin{description}
  1630. \item[\key{select-instructions}] handles the difference between
  1631. \LangVar{} operations and x86 instructions. This pass converts each
  1632. \LangVar{} operation to a short sequence of instructions that
  1633. accomplishes the same task.
  1634. \item[\key{remove-complex-opera*}] ensures that each subexpression of
  1635. a primitive operation is a variable or integer, that is, an
  1636. \emph{atomic} expression. We refer to non-atomic expressions as
  1637. \emph{complex}. This pass introduces temporary variables to hold
  1638. the results of complex subexpressions.\index{atomic
  1639. expression}\index{complex expression}%
  1640. \footnote{The subexpressions of an operation are often called
  1641. operators and operands which explains the presence of
  1642. \code{opera*} in the name of this pass.}
  1643. \item[\key{explicate-control}] makes the execution order of the
  1644. program explicit. It convert the abstract syntax tree representation
  1645. into a control-flow graph in which each node contains a sequence of
  1646. statements and the edges between nodes say which nodes contain jumps
  1647. to other nodes.
  1648. \item[\key{assign-homes}] replaces the variables in \LangVar{} with
  1649. registers or stack locations in x86.
  1650. \item[\key{uniquify}] deals with the shadowing of variables by
  1651. renaming every variable to a unique name.
  1652. \end{description}
  1653. The next question is: in what order should we apply these passes? This
  1654. question can be challenging because it is difficult to know ahead of
  1655. time which orderings will be better (easier to implement, produce more
  1656. efficient code, etc.) so oftentimes trial-and-error is
  1657. involved. Nevertheless, we can try to plan ahead and make educated
  1658. choices regarding the ordering.
  1659. What should be the ordering of \key{explicate-control} with respect to
  1660. \key{uniquify}? The \key{uniquify} pass should come first because
  1661. \key{explicate-control} changes all the \key{let}-bound variables to
  1662. become local variables whose scope is the entire program, which would
  1663. confuse variables with the same name.
  1664. %
  1665. We place \key{remove-complex-opera*} before \key{explicate-control}
  1666. because the later removes the \key{let} form, but it is convenient to
  1667. use \key{let} in the output of \key{remove-complex-opera*}.
  1668. %
  1669. The ordering of \key{uniquify} with respect to
  1670. \key{remove-complex-opera*} does not matter so we arbitrarily choose
  1671. \key{uniquify} to come first.
  1672. Last, we consider \key{select-instructions} and \key{assign-homes}.
  1673. These two passes are intertwined. In Chapter~\ref{ch:Rfun} we
  1674. learn that, in x86, registers are used for passing arguments to
  1675. functions and it is preferable to assign parameters to their
  1676. corresponding registers. On the other hand, by selecting instructions
  1677. first we may run into a dead end in \key{assign-homes}. Recall that
  1678. only one argument of an x86 instruction may be a memory access but
  1679. \key{assign-homes} might fail to assign even one of them to a
  1680. register.
  1681. %
  1682. A sophisticated approach is to iteratively repeat the two passes until
  1683. a solution is found. However, to reduce implementation complexity we
  1684. recommend a simpler approach in which \key{select-instructions} comes
  1685. first, followed by the \key{assign-homes}, then a third pass named
  1686. \key{patch-instructions} that uses a reserved register to fix
  1687. outstanding problems.
  1688. \begin{figure}[tbp]
  1689. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1690. \node (Rvar) at (0,2) {\large \LangVar{}};
  1691. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  1692. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  1693. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  1694. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  1695. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  1696. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  1697. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  1698. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  1699. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  1700. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  1701. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-2);
  1702. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1703. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1704. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1705. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1706. \end{tikzpicture}
  1707. \caption{Diagram of the passes for compiling \LangVar{}. }
  1708. \label{fig:Rvar-passes}
  1709. \end{figure}
  1710. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  1711. passes and identifies the input and output language of each pass. The
  1712. last pass, \key{print-x86}, converts from the abstract syntax of
  1713. \LangXInt{} to the concrete syntax. In the following two sections
  1714. we discuss the \LangCVar{} intermediate language and the \LangXVar{}
  1715. dialect of x86. The remainder of this chapter gives hints regarding
  1716. the implementation of each of the compiler passes in
  1717. Figure~\ref{fig:Rvar-passes}.
  1718. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  1719. %% are programs that are still in the \LangVar{} language, though the
  1720. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  1721. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  1722. %% %
  1723. %% The output of \key{explicate-control} is in an intermediate language
  1724. %% \LangCVar{} designed to make the order of evaluation explicit in its
  1725. %% syntax, which we introduce in the next section. The
  1726. %% \key{select-instruction} pass translates from \LangCVar{} to
  1727. %% \LangXVar{}. The \key{assign-homes} and
  1728. %% \key{patch-instructions}
  1729. %% passes input and output variants of x86 assembly.
  1730. \subsection{The \LangCVar{} Intermediate Language}
  1731. The output of \key{explicate-control} is similar to the $C$
  1732. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1733. categories for expressions and statements, so we name it \LangCVar{}. The
  1734. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  1735. (The concrete syntax for \LangCVar{} is in the Appendix,
  1736. Figure~\ref{fig:c0-concrete-syntax}.)
  1737. %
  1738. The \LangCVar{} language supports the same operators as \LangVar{} but
  1739. the arguments of operators are restricted to atomic
  1740. expressions. Instead of \key{let} expressions, \LangCVar{} has
  1741. assignment statements which can be executed in sequence using the
  1742. \key{Seq} form. A sequence of statements always ends with
  1743. \key{Return}, a guarantee that is baked into the grammar rules for
  1744. \itm{tail}. The naming of this non-terminal comes from the term
  1745. \emph{tail position}\index{tail position}, which refers to an
  1746. expression that is the last one to execute within a function.
  1747. A \LangCVar{} program consists of a control-flow graph represented as
  1748. an alist mapping labels to tails. This is more general than necessary
  1749. for the present chapter, as we do not yet introduce \key{goto} for
  1750. jumping to labels, but it saves us from having to change the syntax in
  1751. Chapter~\ref{ch:Rif}. For now there will be just one label,
  1752. \key{start}, and the whole program is its tail.
  1753. %
  1754. The $\itm{info}$ field of the \key{CProgram} form, after the
  1755. \key{explicate-control} pass, contains a mapping from the symbol
  1756. \key{locals} to a list of variables, that is, a list of all the
  1757. variables used in the program. At the start of the program, these
  1758. variables are uninitialized; they become initialized on their first
  1759. assignment.
  1760. \begin{figure}[tbp]
  1761. \fbox{
  1762. \begin{minipage}{0.96\textwidth}
  1763. \[
  1764. \begin{array}{lcl}
  1765. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1766. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1767. &\mid& \ADD{\Atm}{\Atm}\\
  1768. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1769. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1770. \LangCVar{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  1771. \end{array}
  1772. \]
  1773. \end{minipage}
  1774. }
  1775. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  1776. \label{fig:c0-syntax}
  1777. \end{figure}
  1778. The definitional interpreter for \LangCVar{} is in the support code,
  1779. in the file \code{interp-Cvar.rkt}.
  1780. \subsection{The \LangXVar{} dialect}
  1781. The \LangXVar{} language is the output of the pass
  1782. \key{select-instructions}. It extends \LangXInt{} with an unbounded
  1783. number of program-scope variables and removes the restrictions
  1784. regarding instruction arguments.
  1785. \section{Uniquify Variables}
  1786. \label{sec:uniquify-Rvar}
  1787. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  1788. programs in which every \key{let} binds a unique variable name. For
  1789. example, the \code{uniquify} pass should translate the program on the
  1790. left into the program on the right. \\
  1791. \begin{tabular}{lll}
  1792. \begin{minipage}{0.4\textwidth}
  1793. \begin{lstlisting}
  1794. (let ([x 32])
  1795. (+ (let ([x 10]) x) x))
  1796. \end{lstlisting}
  1797. \end{minipage}
  1798. &
  1799. $\Rightarrow$
  1800. &
  1801. \begin{minipage}{0.4\textwidth}
  1802. \begin{lstlisting}
  1803. (let ([x.1 32])
  1804. (+ (let ([x.2 10]) x.2) x.1))
  1805. \end{lstlisting}
  1806. \end{minipage}
  1807. \end{tabular} \\
  1808. %
  1809. The following is another example translation, this time of a program
  1810. with a \key{let} nested inside the initializing expression of another
  1811. \key{let}.\\
  1812. \begin{tabular}{lll}
  1813. \begin{minipage}{0.4\textwidth}
  1814. \begin{lstlisting}
  1815. (let ([x (let ([x 4])
  1816. (+ x 1))])
  1817. (+ x 2))
  1818. \end{lstlisting}
  1819. \end{minipage}
  1820. &
  1821. $\Rightarrow$
  1822. &
  1823. \begin{minipage}{0.4\textwidth}
  1824. \begin{lstlisting}
  1825. (let ([x.2 (let ([x.1 4])
  1826. (+ x.1 1))])
  1827. (+ x.2 2))
  1828. \end{lstlisting}
  1829. \end{minipage}
  1830. \end{tabular}
  1831. We recommend implementing \code{uniquify} by creating a structurally
  1832. recursive function named \code{uniquify-exp} that mostly just copies
  1833. an expression. However, when encountering a \key{let}, it should
  1834. generate a unique name for the variable and associate the old name
  1835. with the new name in an alist.\footnote{The Racket function
  1836. \code{gensym} is handy for generating unique variable names.} The
  1837. \code{uniquify-exp} function needs to access this alist when it gets
  1838. to a variable reference, so we add a parameter to \code{uniquify-exp}
  1839. for the alist.
  1840. The skeleton of the \code{uniquify-exp} function is shown in
  1841. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  1842. convenient to partially apply it to an alist and then apply it to
  1843. different expressions, as in the last case for primitive operations in
  1844. Figure~\ref{fig:uniquify-Rvar}. The
  1845. %
  1846. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1847. %
  1848. form of Racket is useful for transforming each element of a list to
  1849. produce a new list.\index{for/list}
  1850. \begin{exercise}
  1851. \normalfont % I don't like the italics for exercises. -Jeremy
  1852. Complete the \code{uniquify} pass by filling in the blanks in
  1853. Figure~\ref{fig:uniquify-Rvar}, that is, implement the cases for
  1854. variables and for the \key{let} form in the file \code{compiler.rkt}
  1855. in the support code.
  1856. \end{exercise}
  1857. \begin{figure}[tbp]
  1858. \begin{lstlisting}
  1859. (define (uniquify-exp env)
  1860. (lambda (e)
  1861. (match e
  1862. [(Var x) ___]
  1863. [(Int n) (Int n)]
  1864. [(Let x e body) ___]
  1865. [(Prim op es)
  1866. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  1867. (define (uniquify p)
  1868. (match p
  1869. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  1870. \end{lstlisting}
  1871. \caption{Skeleton for the \key{uniquify} pass.}
  1872. \label{fig:uniquify-Rvar}
  1873. \end{figure}
  1874. \begin{exercise}
  1875. \normalfont % I don't like the italics for exercises. -Jeremy
  1876. \label{ex:Rvar}
  1877. Create five \LangVar{} programs that exercise the most interesting
  1878. parts of the \key{uniquify} pass, that is, the programs should include
  1879. \key{let} forms, variables, and variables that shadow each other.
  1880. The five programs should be placed in the subdirectory named
  1881. \key{tests} and the file names should start with \code{var\_test\_}
  1882. followed by a unique integer and end with the file extension
  1883. \key{.rkt}.
  1884. %
  1885. The \key{run-tests.rkt} script in the support code checks whether the
  1886. output programs produce the same result as the input programs. The
  1887. script uses the \key{interp-tests} function
  1888. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1889. your \key{uniquify} pass on the example programs. The \code{passes}
  1890. parameter of \key{interp-tests} is a list that should have one entry
  1891. for each pass in your compiler. For now, define \code{passes} to
  1892. contain just one entry for \code{uniquify} as follows.
  1893. \begin{lstlisting}
  1894. (define passes
  1895. (list (list "uniquify" uniquify interp-Rvar type-check-Rvar)))
  1896. \end{lstlisting}
  1897. Run the \key{run-tests.rkt} script in the support code to check
  1898. whether the output programs produce the same result as the input
  1899. programs.
  1900. \end{exercise}
  1901. \section{Remove Complex Operands}
  1902. \label{sec:remove-complex-opera-Rvar}
  1903. The \code{remove-complex-opera*} pass compiles \LangVar{} programs
  1904. into a restricted form in which the arguments of operations are atomic
  1905. expressions. Put another way, this pass removes complex
  1906. operands\index{complex operand}, such as the expression \code{(- 10)}
  1907. in the program below. This is accomplished by introducing a new
  1908. \key{let}-bound variable, binding the complex operand to the new
  1909. variable, and then using the new variable in place of the complex
  1910. operand, as shown in the output of \code{remove-complex-opera*} on the
  1911. right.\\
  1912. \begin{tabular}{lll}
  1913. \begin{minipage}{0.4\textwidth}
  1914. % var_test_19.rkt
  1915. \begin{lstlisting}
  1916. (+ 52 (- 10))
  1917. \end{lstlisting}
  1918. \end{minipage}
  1919. &
  1920. $\Rightarrow$
  1921. &
  1922. \begin{minipage}{0.4\textwidth}
  1923. \begin{lstlisting}
  1924. (let ([tmp.1 (- 10)])
  1925. (+ 52 tmp.1))
  1926. \end{lstlisting}
  1927. \end{minipage}
  1928. \end{tabular}
  1929. \begin{figure}[tp]
  1930. \centering
  1931. \fbox{
  1932. \begin{minipage}{0.96\textwidth}
  1933. \[
  1934. \begin{array}{rcl}
  1935. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1936. \Exp &::=& \Atm \mid \READ{} \\
  1937. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1938. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1939. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1940. \end{array}
  1941. \]
  1942. \end{minipage}
  1943. }
  1944. \caption{\LangVarANF{} is \LangVar{} in administrative normal form (ANF).}
  1945. \label{fig:r1-anf-syntax}
  1946. \end{figure}
  1947. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1948. this pass, the language \LangVarANF{}. The only difference is that
  1949. operator arguments are restricted to be atomic expressions that are
  1950. defined by the \Atm{} non-terminal. In particular, integer constants
  1951. and variables are atomic. In the literature, restricting arguments to
  1952. be atomic expressions is called \emph{administrative normal form}, or
  1953. ANF for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1954. \index{administrative normal form} \index{ANF}
  1955. We recommend implementing this pass with two mutually recursive
  1956. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1957. \code{rco-atom} to subexpressions that need to become atomic and to
  1958. apply \code{rco-exp} to subexpressions that do not. Both functions
  1959. take an \LangVar{} expression as input. The \code{rco-exp} function
  1960. returns an expression. The \code{rco-atom} function returns two
  1961. things: an atomic expression and an alist mapping temporary variables to
  1962. complex subexpressions. You can return multiple things from a function
  1963. using Racket's \key{values} form and you can receive multiple things
  1964. from a function call using the \key{define-values} form. If you are
  1965. not familiar with these features, review the Racket documentation.
  1966. Also, the
  1967. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1968. form is useful for applying a function to each element of a list, in
  1969. the case where the function returns multiple values.
  1970. \index{for/lists}
  1971. Returning to the example program \code{(+ 52 (- 10))}, the
  1972. subexpression \code{(- 10)} should be processed using the
  1973. \code{rco-atom} function because it is an argument of the \code{+} and
  1974. therefore needs to become atomic. The output of \code{rco-atom}
  1975. applied to \code{(- 10)} is as follows.
  1976. \begin{tabular}{lll}
  1977. \begin{minipage}{0.4\textwidth}
  1978. \begin{lstlisting}
  1979. (- 10)
  1980. \end{lstlisting}
  1981. \end{minipage}
  1982. &
  1983. $\Rightarrow$
  1984. &
  1985. \begin{minipage}{0.4\textwidth}
  1986. \begin{lstlisting}
  1987. tmp.1
  1988. ((tmp.1 . (- 10)))
  1989. \end{lstlisting}
  1990. \end{minipage}
  1991. \end{tabular}
  1992. Take special care of programs such as the following one that binds a
  1993. variable to an atomic expression. You should leave such variable
  1994. bindings unchanged, as shown in to the program on the right \\
  1995. \begin{tabular}{lll}
  1996. \begin{minipage}{0.4\textwidth}
  1997. % var_test_20.rkt
  1998. \begin{lstlisting}
  1999. (let ([a 42])
  2000. (let ([b a])
  2001. b))
  2002. \end{lstlisting}
  2003. \end{minipage}
  2004. &
  2005. $\Rightarrow$
  2006. &
  2007. \begin{minipage}{0.4\textwidth}
  2008. \begin{lstlisting}
  2009. (let ([a 42])
  2010. (let ([b a])
  2011. b))
  2012. \end{lstlisting}
  2013. \end{minipage}
  2014. \end{tabular} \\
  2015. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  2016. produce the following output with unnecessary temporary variables.\\
  2017. \begin{minipage}{0.4\textwidth}
  2018. \begin{lstlisting}
  2019. (let ([tmp.1 42])
  2020. (let ([a tmp.1])
  2021. (let ([tmp.2 a])
  2022. (let ([b tmp.2])
  2023. b))))
  2024. \end{lstlisting}
  2025. \end{minipage}
  2026. \begin{exercise}\normalfont
  2027. %
  2028. Implement the \code{remove-complex-opera*} function in
  2029. \code{compiler.rkt}.
  2030. %
  2031. Create three new \LangInt{} programs that exercise the interesting
  2032. code in the \code{remove-complex-opera*} pass. Follow the guidelines
  2033. regarding file names described in Exercise~\ref{ex:Rvar}.
  2034. %
  2035. In the \code{run-tests.rkt} script, add the following entry to the
  2036. list of \code{passes} and then run the script to test your compiler.
  2037. \begin{lstlisting}
  2038. (list "remove-complex" remove-complex-opera* interp-Rvar type-check-Rvar)
  2039. \end{lstlisting}
  2040. While debugging your compiler, it is often useful to see the
  2041. intermediate programs that are output from each pass. To print the
  2042. intermediate programs, place the following before the call to
  2043. \code{interp-tests} in \code{run-tests.rkt}.
  2044. \begin{lstlisting}
  2045. (debug-level 1)
  2046. \end{lstlisting}
  2047. \end{exercise}
  2048. \section{Explicate Control}
  2049. \label{sec:explicate-control-Rvar}
  2050. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  2051. programs that make the order of execution explicit in their
  2052. syntax. For now this amounts to flattening \key{let} constructs into a
  2053. sequence of assignment statements. For example, consider the following
  2054. \LangVar{} program.\\
  2055. % var_test_11.rkt
  2056. \begin{minipage}{0.96\textwidth}
  2057. \begin{lstlisting}
  2058. (let ([y (let ([x 20])
  2059. (+ x (let ([x 22]) x)))])
  2060. y)
  2061. \end{lstlisting}
  2062. \end{minipage}\\
  2063. %
  2064. The output of the previous pass and of \code{explicate-control} is
  2065. shown below. Recall that the right-hand-side of a \key{let} executes
  2066. before its body, so the order of evaluation for this program is to
  2067. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2068. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2069. output of \code{explicate-control} makes this ordering explicit.\\
  2070. \begin{tabular}{lll}
  2071. \begin{minipage}{0.4\textwidth}
  2072. \begin{lstlisting}
  2073. (let ([y (let ([x.1 20])
  2074. (let ([x.2 22])
  2075. (+ x.1 x.2)))])
  2076. y)
  2077. \end{lstlisting}
  2078. \end{minipage}
  2079. &
  2080. $\Rightarrow$
  2081. &
  2082. \begin{minipage}{0.4\textwidth}
  2083. \begin{lstlisting}[language=C]
  2084. start:
  2085. x.1 = 20;
  2086. x.2 = 22;
  2087. y = (+ x.1 x.2);
  2088. return y;
  2089. \end{lstlisting}
  2090. \end{minipage}
  2091. \end{tabular}
  2092. \begin{figure}[tbp]
  2093. \begin{lstlisting}
  2094. (define (explicate-tail e)
  2095. (match e
  2096. [(Var x) ___]
  2097. [(Int n) (Return (Int n))]
  2098. [(Let x rhs body) ___]
  2099. [(Prim op es) ___]
  2100. [else (error "explicate-tail unhandled case" e)]))
  2101. (define (explicate-assign e x cont)
  2102. (match e
  2103. [(Var x) ___]
  2104. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2105. [(Let y rhs body) ___]
  2106. [(Prim op es) ___]
  2107. [else (error "explicate-assign unhandled case" e)]))
  2108. (define (explicate-control p)
  2109. (match p
  2110. [(Program info body) ___]))
  2111. \end{lstlisting}
  2112. \caption{Skeleton for the \key{explicate-control} pass.}
  2113. \label{fig:explicate-control-Rvar}
  2114. \end{figure}
  2115. The organization of this pass depends on the notion of tail position
  2116. that we have alluded to earlier. Formally, \emph{tail
  2117. position}\index{tail position} in the context of \LangVar{} is
  2118. defined recursively by the following two rules.
  2119. \begin{enumerate}
  2120. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2121. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2122. \end{enumerate}
  2123. We recommend implementing \code{explicate-control} using two mutually
  2124. recursive functions, \code{explicate-tail} and
  2125. \code{explicate-assign}, as suggested in the skeleton code in
  2126. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2127. function should be applied to expressions in tail position whereas the
  2128. \code{explicate-assign} should be applied to expressions that occur on
  2129. the right-hand-side of a \key{let}.
  2130. %
  2131. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2132. input and produces a \Tail{} in \LangCVar{} (see
  2133. Figure~\ref{fig:c0-syntax}).
  2134. %
  2135. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2136. the variable that it is to be assigned to, and a \Tail{} in
  2137. \LangCVar{} for the code that will come after the assignment. The
  2138. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2139. The \code{explicate-assign} function is in accumulator-passing style
  2140. in that the \code{cont} parameter is used for accumulating the
  2141. output. The reader might be tempted to instead organize
  2142. \code{explicate-assign} in a more direct fashion, without the
  2143. \code{cont} parameter and perhaps using \code{append} to combine
  2144. statements. We warn against that alternative because the
  2145. accumulator-passing style is key to how we generate high-quality code
  2146. for conditional expressions in Chapter~\ref{ch:Rif}.
  2147. \begin{exercise}\normalfont
  2148. %
  2149. Implement the \code{explicate-control} function in
  2150. \code{compiler.rkt}. Create three new \LangInt{} programs that
  2151. exercise the code in \code{explicate-control}.
  2152. %
  2153. In the \code{run-tests.rkt} script, add the following entry to the
  2154. list of \code{passes} and then run the script to test your compiler.
  2155. \begin{lstlisting}
  2156. (list "explicate control" explicate-control interp-Cvar type-check-Cvar)
  2157. \end{lstlisting}
  2158. \end{exercise}
  2159. \section{Select Instructions}
  2160. \label{sec:select-Rvar}
  2161. \index{instruction selection}
  2162. In the \code{select-instructions} pass we begin the work of
  2163. translating from \LangCVar{} to \LangXVar{}. The target language of
  2164. this pass is a variant of x86 that still uses variables, so we add an
  2165. AST node of the form $\VAR{\itm{var}}$ to the \Arg{} non-terminal of
  2166. the \LangXInt{} abstract syntax (Figure~\ref{fig:x86-int-ast}). We
  2167. recommend implementing the \code{select-instructions} with
  2168. three auxiliary functions, one for each of the non-terminals of
  2169. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.
  2170. The cases for $\Atm$ are straightforward; variables stay
  2171. the same and integer constants are changed to immediates:
  2172. $\INT{n}$ changes to $\IMM{n}$.
  2173. Next we consider the cases for $\Stmt$, starting with arithmetic
  2174. operations. For example, consider the addition operation. We can use
  2175. the \key{addq} instruction, but it performs an in-place update. So we
  2176. could move $\itm{arg}_1$ into the left-hand side \itm{var} and then
  2177. add $\itm{arg}_2$ to \itm{var}. \\
  2178. \begin{tabular}{lll}
  2179. \begin{minipage}{0.4\textwidth}
  2180. \begin{lstlisting}
  2181. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2182. \end{lstlisting}
  2183. \end{minipage}
  2184. &
  2185. $\Rightarrow$
  2186. &
  2187. \begin{minipage}{0.4\textwidth}
  2188. \begin{lstlisting}
  2189. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2190. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2191. \end{lstlisting}
  2192. \end{minipage}
  2193. \end{tabular} \\
  2194. %
  2195. There are also cases that require special care to avoid generating
  2196. needlessly complicated code. For example, if one of the arguments of
  2197. the addition is the same variable as the left-hand side of the
  2198. assignment, then there is no need for the extra move instruction. The
  2199. assignment statement can be translated into a single \key{addq}
  2200. instruction as follows.\\
  2201. \begin{tabular}{lll}
  2202. \begin{minipage}{0.4\textwidth}
  2203. \begin{lstlisting}
  2204. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2205. \end{lstlisting}
  2206. \end{minipage}
  2207. &
  2208. $\Rightarrow$
  2209. &
  2210. \begin{minipage}{0.4\textwidth}
  2211. \begin{lstlisting}
  2212. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2213. \end{lstlisting}
  2214. \end{minipage}
  2215. \end{tabular}
  2216. The \key{read} operation does not have a direct counterpart in x86
  2217. assembly, so we provide this functionality with the function
  2218. \code{read\_int} in the file \code{runtime.c}, written in
  2219. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2220. functionality in this file as the \emph{runtime system}\index{runtime
  2221. system}, or simply the \emph{runtime} for short. When compiling your
  2222. generated x86 assembly code, you need to compile \code{runtime.c} to
  2223. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2224. \code{-c}) and link it into the executable. For our purposes of code
  2225. generation, all you need to do is translate an assignment of
  2226. \key{read} into a call to the \code{read\_int} function followed by a
  2227. move from \code{rax} to the left-hand-side variable. (Recall that the
  2228. return value of a function goes into \code{rax}.) \\
  2229. \begin{tabular}{lll}
  2230. \begin{minipage}{0.3\textwidth}
  2231. \begin{lstlisting}
  2232. |$\itm{var}$| = (read);
  2233. \end{lstlisting}
  2234. \end{minipage}
  2235. &
  2236. $\Rightarrow$
  2237. &
  2238. \begin{minipage}{0.3\textwidth}
  2239. \begin{lstlisting}
  2240. callq read_int
  2241. movq %rax, |$\itm{var}$|
  2242. \end{lstlisting}
  2243. \end{minipage}
  2244. \end{tabular}
  2245. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2246. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2247. assignment to the \key{rax} register followed by a jump to the
  2248. conclusion of the program (so the conclusion needs to be labeled).
  2249. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2250. recursively and then append the resulting instructions.
  2251. \begin{exercise}
  2252. \normalfont Implement the \key{select-instructions} pass in
  2253. \code{compiler.rkt}. Create three new example programs that are
  2254. designed to exercise all of the interesting cases in this pass.
  2255. %
  2256. In the \code{run-tests.rkt} script, add the following entry to the
  2257. list of \code{passes} and then run the script to test your compiler.
  2258. \begin{lstlisting}
  2259. (list "instruction selection" select-instructions interp-pseudo-x86-0)
  2260. \end{lstlisting}
  2261. \end{exercise}
  2262. \section{Assign Homes}
  2263. \label{sec:assign-Rvar}
  2264. The \key{assign-homes} pass compiles \LangXVar{} programs to
  2265. \LangXVar{} programs that no longer use program variables.
  2266. Thus, the \key{assign-homes} pass is responsible for placing all of
  2267. the program variables in registers or on the stack. For runtime
  2268. efficiency, it is better to place variables in registers, but as there
  2269. are only 16 registers, some programs must necessarily resort to
  2270. placing some variables on the stack. In this chapter we focus on the
  2271. mechanics of placing variables on the stack. We study an algorithm for
  2272. placing variables in registers in
  2273. Chapter~\ref{ch:register-allocation-Rvar}.
  2274. Consider again the following \LangVar{} program from
  2275. Section~\ref{sec:remove-complex-opera-Rvar}.
  2276. % var_test_20.rkt
  2277. \begin{lstlisting}
  2278. (let ([a 42])
  2279. (let ([b a])
  2280. b))
  2281. \end{lstlisting}
  2282. The output of \code{select-instructions} is shown on the left and the
  2283. output of \code{assign-homes} on the right. In this example, we
  2284. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  2285. variable \code{b} to location \code{-16(\%rbp)}.\\
  2286. \begin{tabular}{l}
  2287. \begin{minipage}{0.4\textwidth}
  2288. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2289. locals-types:
  2290. a : Integer, b : Integer
  2291. start:
  2292. movq $42, a
  2293. movq a, b
  2294. movq b, %rax
  2295. jmp conclusion
  2296. \end{lstlisting}
  2297. \end{minipage}
  2298. {$\Rightarrow$}
  2299. \begin{minipage}{0.4\textwidth}
  2300. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2301. stack-space: 16
  2302. start:
  2303. movq $42, -8(%rbp)
  2304. movq -8(%rbp), -16(%rbp)
  2305. movq -16(%rbp), %rax
  2306. jmp conclusion
  2307. \end{lstlisting}
  2308. \end{minipage}
  2309. \end{tabular}
  2310. The \code{locals-types} entry in the $\itm{info}$ of the
  2311. \code{X86Program} node is an alist mapping all the variables in the
  2312. program to their types (for now just \code{Integer}). The
  2313. \code{assign-homes} pass should replace all uses of those variables
  2314. with stack locations. As an aside, the \code{locals-types} entry is
  2315. computed by \code{type-check-Cvar} in the support code, which installs
  2316. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  2317. be propagated to the \code{X86Program} node.
  2318. In the process of assigning variables to stack locations, it is
  2319. convenient for you to compute and store the size of the frame (in
  2320. bytes) in the $\itm{info}$ field of the \key{X86Program} node, with
  2321. the key \code{stack-space}, which is needed later to generate the
  2322. conclusion of the \code{main} procedure. The x86-64 standard requires
  2323. the frame size to be a multiple of 16 bytes.\index{frame}
  2324. \begin{exercise}\normalfont
  2325. Implement the \key{assign-homes} pass in \code{compiler.rkt}, defining
  2326. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  2327. \Block{}. We recommend that the auxiliary functions take an extra
  2328. parameter that is an alist mapping variable names to homes (stack
  2329. locations for now).
  2330. %
  2331. In the \code{run-tests.rkt} script, add the following entry to the
  2332. list of \code{passes} and then run the script to test your compiler.
  2333. \begin{lstlisting}
  2334. (list "assign homes" assign-homes interp-x86-0)
  2335. \end{lstlisting}
  2336. \end{exercise}
  2337. \section{Patch Instructions}
  2338. \label{sec:patch-s0}
  2339. The \code{patch-instructions} pass compiles from \LangXVar{} to
  2340. \LangXInt{} by making sure that each instruction adheres to the
  2341. restriction that at most one argument of an instruction may be a
  2342. memory reference.
  2343. We return to the following example.
  2344. % var_test_20.rkt
  2345. \begin{lstlisting}
  2346. (let ([a 42])
  2347. (let ([b a])
  2348. b))
  2349. \end{lstlisting}
  2350. The \key{assign-homes} pass produces the following output
  2351. for this program. \\
  2352. \begin{minipage}{0.5\textwidth}
  2353. \begin{lstlisting}
  2354. stack-space: 16
  2355. start:
  2356. movq $42, -8(%rbp)
  2357. movq -8(%rbp), -16(%rbp)
  2358. movq -16(%rbp), %rax
  2359. jmp conclusion
  2360. \end{lstlisting}
  2361. \end{minipage}\\
  2362. The second \key{movq} instruction is problematic because both
  2363. arguments are stack locations. We suggest fixing this problem by
  2364. moving from the source location to the register \key{rax} and then
  2365. from \key{rax} to the destination location, as follows.
  2366. \begin{lstlisting}
  2367. movq -8(%rbp), %rax
  2368. movq %rax, -16(%rbp)
  2369. \end{lstlisting}
  2370. \begin{exercise}
  2371. \normalfont Implement the \key{patch-instructions} pass in
  2372. \code{compiler.rkt}. Create three new example programs that are
  2373. designed to exercise all of the interesting cases in this pass.
  2374. %
  2375. In the \code{run-tests.rkt} script, add the following entry to the
  2376. list of \code{passes} and then run the script to test your compiler.
  2377. \begin{lstlisting}
  2378. (list "patch instructions" patch-instructions interp-x86-0)
  2379. \end{lstlisting}
  2380. \end{exercise}
  2381. \section{Print x86}
  2382. \label{sec:print-x86}
  2383. The last step of the compiler from \LangVar{} to x86 is to convert the
  2384. \LangXInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  2385. string representation (defined in
  2386. Figure~\ref{fig:x86-int-concrete}). The Racket \key{format} and
  2387. \key{string-append} functions are useful in this regard. The main work
  2388. that this step needs to perform is to create the \key{main} function
  2389. and the standard instructions for its prelude and conclusion, as shown
  2390. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  2391. know the amount of space needed for the stack frame, which you can
  2392. obtain from the \code{stack-space} entry in the $\itm{info}$ field of
  2393. the \key{X86Program} node.
  2394. When running on Mac OS X, you compiler should prefix an underscore to
  2395. labels like \key{main}. The Racket call \code{(system-type 'os)} is
  2396. useful for determining which operating system the compiler is running
  2397. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.
  2398. \begin{exercise}\normalfont
  2399. %
  2400. Implement the \key{print-x86} pass in \code{compiler.rkt}.
  2401. %
  2402. In the \code{run-tests.rkt} script, add the following entry to the
  2403. list of \code{passes} and then run the script to test your compiler.
  2404. \begin{lstlisting}
  2405. (list "print x86" print-x86 #f)
  2406. \end{lstlisting}
  2407. %
  2408. Uncomment the call to the \key{compiler-tests} function
  2409. (Appendix~\ref{appendix:utilities}), which tests your complete
  2410. compiler by executing the generated x86 code. Compile the provided
  2411. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  2412. script to test your compiler.
  2413. \end{exercise}
  2414. \section{Challenge: Partial Evaluator for \LangVar{}}
  2415. \label{sec:pe-Rvar}
  2416. \index{partial evaluation}
  2417. This section describes optional challenge exercises that involve
  2418. adapting and improving the partial evaluator for \LangInt{} that was
  2419. introduced in Section~\ref{sec:partial-evaluation}.
  2420. \begin{exercise}\label{ex:pe-Rvar}
  2421. \normalfont
  2422. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2423. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  2424. instead of \LangInt{} programs. Recall that \LangVar{} adds \key{let} binding
  2425. and variables to the \LangInt{} language, so you will need to add cases for
  2426. them in the \code{pe-exp} function. Once complete, add the partial
  2427. evaluation pass to the front of your compiler and make sure that your
  2428. compiler still passes all of the tests.
  2429. \end{exercise}
  2430. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  2431. \begin{exercise}
  2432. \normalfont
  2433. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2434. \code{pe-add} auxiliary functions with functions that know more about
  2435. arithmetic. For example, your partial evaluator should translate
  2436. \[
  2437. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  2438. \code{(+ 2 (read))}
  2439. \]
  2440. To accomplish this, the \code{pe-exp} function should produce output
  2441. in the form of the $\itm{residual}$ non-terminal of the following
  2442. grammar. The idea is that when processing an addition expression, we
  2443. can always produce either 1) an integer constant, 2) an addition
  2444. expression with an integer constant on the left-hand side but not the
  2445. right-hand side, or 3) or an addition expression in which neither
  2446. subexpression is a constant.
  2447. \[
  2448. \begin{array}{lcl}
  2449. \itm{inert} &::=& \Var
  2450. \mid \LP\key{read}\RP
  2451. \mid \LP\key{-} \;\Var\RP
  2452. \mid \LP\key{-} \;\LP\key{read}\RP\RP
  2453. \mid \LP\key{+} \; \itm{inert} \; \itm{inert}\RP\\
  2454. &\mid& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  2455. \itm{residual} &::=& \Int
  2456. \mid \LP\key{+}\; \Int\; \itm{inert}\RP
  2457. \mid \itm{inert}
  2458. \end{array}
  2459. \]
  2460. The \code{pe-add} and \code{pe-neg} functions may assume that their
  2461. inputs are $\itm{residual}$ expressions and they should return
  2462. $\itm{residual}$ expressions. Once the improvements are complete,
  2463. make sure that your compiler still passes all of the tests. After
  2464. all, fast code is useless if it produces incorrect results!
  2465. \end{exercise}
  2466. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2467. \chapter{Register Allocation}
  2468. \label{ch:register-allocation-Rvar}
  2469. \index{register allocation}
  2470. In Chapter~\ref{ch:Rvar} we learned how to store variables on the
  2471. stack. In this Chapter we learn how to improve the performance of the
  2472. generated code by placing some variables into registers. The CPU can
  2473. access a register in a single cycle, whereas accessing the stack can
  2474. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  2475. serves as a running example. The source program is on the left and the
  2476. output of instruction selection is on the right. The program is almost
  2477. in the x86 assembly language but it still uses variables.
  2478. \begin{figure}
  2479. \begin{minipage}{0.45\textwidth}
  2480. Example \LangVar{} program:
  2481. % var_test_28.rkt
  2482. \begin{lstlisting}
  2483. (let ([v 1])
  2484. (let ([w 42])
  2485. (let ([x (+ v 7)])
  2486. (let ([y x])
  2487. (let ([z (+ x w)])
  2488. (+ z (- y)))))))
  2489. \end{lstlisting}
  2490. \end{minipage}
  2491. \begin{minipage}{0.45\textwidth}
  2492. After instruction selection:
  2493. \begin{lstlisting}
  2494. locals-types:
  2495. x : Integer, y : Integer,
  2496. z : Integer, t : Integer,
  2497. v : Integer, w : Integer
  2498. start:
  2499. movq $1, v
  2500. movq $42, w
  2501. movq v, x
  2502. addq $7, x
  2503. movq x, y
  2504. movq x, z
  2505. addq w, z
  2506. movq y, t
  2507. negq t
  2508. movq z, %rax
  2509. addq t, %rax
  2510. jmp conclusion
  2511. \end{lstlisting}
  2512. \end{minipage}
  2513. \caption{A running example for register allocation.}
  2514. \label{fig:reg-eg}
  2515. \end{figure}
  2516. The goal of register allocation is to fit as many variables into
  2517. registers as possible. Some programs have more variables than
  2518. registers so we cannot always map each variable to a different
  2519. register. Fortunately, it is common for different variables to be
  2520. needed during different periods of time during program execution, and
  2521. in such cases several variables can be mapped to the same register.
  2522. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  2523. After the variable \code{x} is moved to \code{z} it is no longer
  2524. needed. Variable \code{z}, on the other hand, is used only after this
  2525. point, so \code{x} and \code{z} could share the same register. The
  2526. topic of Section~\ref{sec:liveness-analysis-Rvar} is how to compute
  2527. where a variable is needed. Once we have that information, we compute
  2528. which variables are needed at the same time, i.e., which ones
  2529. \emph{interfere} with each other, and represent this relation as an
  2530. undirected graph whose vertices are variables and edges indicate when
  2531. two variables interfere (Section~\ref{sec:build-interference}). We
  2532. then model register allocation as a graph coloring problem
  2533. (Section~\ref{sec:graph-coloring}).
  2534. If we run out of registers despite these efforts, we place the
  2535. remaining variables on the stack, similar to what we did in
  2536. Chapter~\ref{ch:Rvar}. It is common to use the verb \emph{spill}
  2537. for assigning a variable to a stack location. The decision to spill a
  2538. variable is handled as part of the graph coloring process
  2539. (Section~\ref{sec:graph-coloring}).
  2540. We make the simplifying assumption that each variable is assigned to
  2541. one location (a register or stack address). A more sophisticated
  2542. approach is to assign a variable to one or more locations in different
  2543. regions of the program. For example, if a variable is used many times
  2544. in short sequence and then only used again after many other
  2545. instructions, it could be more efficient to assign the variable to a
  2546. register during the initial sequence and then move it to the stack for
  2547. the rest of its lifetime. We refer the interested reader to
  2548. \citet{Cooper:2011aa} for more information about that approach.
  2549. % discuss prioritizing variables based on how much they are used.
  2550. \section{Registers and Calling Conventions}
  2551. \label{sec:calling-conventions}
  2552. \index{calling conventions}
  2553. As we perform register allocation, we need to be aware of the
  2554. \emph{calling conventions} \index{calling conventions} that govern how
  2555. functions calls are performed in x86.
  2556. %
  2557. Even though \LangVar{} does not include programmer-defined functions,
  2558. our generated code includes a \code{main} function that is called by
  2559. the operating system and our generated code contains calls to the
  2560. \code{read\_int} function.
  2561. Function calls require coordination between two pieces of code that
  2562. may be written by different programmers or generated by different
  2563. compilers. Here we follow the System V calling conventions that are
  2564. used by the GNU C compiler on Linux and
  2565. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2566. %
  2567. The calling conventions include rules about how functions share the
  2568. use of registers. In particular, the caller is responsible for freeing
  2569. up some registers prior to the function call for use by the callee.
  2570. These are called the \emph{caller-saved registers}
  2571. \index{caller-saved registers}
  2572. and they are
  2573. \begin{lstlisting}
  2574. rax rcx rdx rsi rdi r8 r9 r10 r11
  2575. \end{lstlisting}
  2576. On the other hand, the callee is responsible for preserving the values
  2577. of the \emph{callee-saved registers}, \index{callee-saved registers}
  2578. which are
  2579. \begin{lstlisting}
  2580. rsp rbp rbx r12 r13 r14 r15
  2581. \end{lstlisting}
  2582. We can think about this caller/callee convention from two points of
  2583. view, the caller view and the callee view:
  2584. \begin{itemize}
  2585. \item The caller should assume that all the caller-saved registers get
  2586. overwritten with arbitrary values by the callee. On the other hand,
  2587. the caller can safely assume that all the callee-saved registers
  2588. contain the same values after the call that they did before the
  2589. call.
  2590. \item The callee can freely use any of the caller-saved registers.
  2591. However, if the callee wants to use a callee-saved register, the
  2592. callee must arrange to put the original value back in the register
  2593. prior to returning to the caller. This can be accomplished by saving
  2594. the value to the stack in the prelude of the function and restoring
  2595. the value in the conclusion of the function.
  2596. \end{itemize}
  2597. In x86, registers are also used for passing arguments to a function
  2598. and for the return value. In particular, the first six arguments to a
  2599. function are passed in the following six registers, in this order.
  2600. \begin{lstlisting}
  2601. rdi rsi rdx rcx r8 r9
  2602. \end{lstlisting}
  2603. If there are more than six arguments, then the convention is to use
  2604. space on the frame of the caller for the rest of the
  2605. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  2606. need more than six arguments. For now, the only function we care about
  2607. is \code{read\_int} and it takes zero arguments.
  2608. %
  2609. The register \code{rax} is used for the return value of a function.
  2610. The next question is how these calling conventions impact register
  2611. allocation. Consider the \LangVar{} program in
  2612. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2613. example from the caller point of view and then from the callee point
  2614. of view.
  2615. The program makes two calls to the \code{read} function. Also, the
  2616. variable \code{x} is in use during the second call to \code{read}, so
  2617. we need to make sure that the value in \code{x} does not get
  2618. accidentally wiped out by the call to \code{read}. One obvious
  2619. approach is to save all the values in caller-saved registers to the
  2620. stack prior to each function call, and restore them after each
  2621. call. That way, if the register allocator chooses to assign \code{x}
  2622. to a caller-saved register, its value will be preserved across the
  2623. call to \code{read}. However, saving and restoring to the stack is
  2624. relatively slow. If \code{x} is not used many times, it may be better
  2625. to assign \code{x} to a stack location in the first place. Or better
  2626. yet, if we can arrange for \code{x} to be placed in a callee-saved
  2627. register, then it won't need to be saved and restored during function
  2628. calls.
  2629. The approach that we recommend for variables that are in use during a
  2630. function call is to either assign them to callee-saved registers or to
  2631. spill them to the stack. On the other hand, for variables that are not
  2632. in use during a function call, we try the following alternatives in
  2633. order 1) look for an available caller-saved register (to leave room
  2634. for other variables in the callee-saved register), 2) look for a
  2635. callee-saved register, and 3) spill the variable to the stack.
  2636. It is straightforward to implement this approach in a graph coloring
  2637. register allocator. First, we know which variables are in use during
  2638. every function call because we compute that information for every
  2639. instruction (Section~\ref{sec:liveness-analysis-Rvar}). Second, when we
  2640. build the interference graph (Section~\ref{sec:build-interference}),
  2641. we can place an edge between each of these variables and the
  2642. caller-saved registers in the interference graph. This will prevent
  2643. the graph coloring algorithm from assigning those variables to
  2644. caller-saved registers.
  2645. Returning to the example in
  2646. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2647. generated x86 code on the right-hand side, focusing on the
  2648. \code{start} block. Notice that variable \code{x} is assigned to
  2649. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2650. place during the second call to \code{read\_int}. Next, notice that
  2651. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2652. because there are no function calls in the remainder of the block.
  2653. Next we analyze the example from the callee point of view, focusing on
  2654. the prelude and conclusion of the \code{main} function. As usual the
  2655. prelude begins with saving the \code{rbp} register to the stack and
  2656. setting the \code{rbp} to the current stack pointer. We now know why
  2657. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2658. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2659. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  2660. (\code{x}). The other callee-saved registers are not saved in the
  2661. prelude because they are not used. The prelude subtracts 8 bytes from
  2662. the \code{rsp} to make it 16-byte aligned and then jumps to the
  2663. \code{start} block. Shifting attention to the \code{conclusion}, we
  2664. see that \code{rbx} is restored from the stack with a \code{popq}
  2665. instruction. \index{prelude}\index{conclusion}
  2666. \begin{figure}[tp]
  2667. \begin{minipage}{0.45\textwidth}
  2668. Example \LangVar{} program:
  2669. %var_test_14.rkt
  2670. \begin{lstlisting}
  2671. (let ([x (read)])
  2672. (let ([y (read)])
  2673. (+ (+ x y) 42)))
  2674. \end{lstlisting}
  2675. \end{minipage}
  2676. \begin{minipage}{0.45\textwidth}
  2677. Generated x86 assembly:
  2678. \begin{lstlisting}
  2679. start:
  2680. callq read_int
  2681. movq %rax, %rbx
  2682. callq read_int
  2683. movq %rax, %rcx
  2684. addq %rcx, %rbx
  2685. movq %rbx, %rax
  2686. addq $42, %rax
  2687. jmp _conclusion
  2688. .globl main
  2689. main:
  2690. pushq %rbp
  2691. movq %rsp, %rbp
  2692. pushq %rbx
  2693. subq $8, %rsp
  2694. jmp start
  2695. conclusion:
  2696. addq $8, %rsp
  2697. popq %rbx
  2698. popq %rbp
  2699. retq
  2700. \end{lstlisting}
  2701. \end{minipage}
  2702. \caption{An example with function calls.}
  2703. \label{fig:example-calling-conventions}
  2704. \end{figure}
  2705. \clearpage
  2706. \section{Liveness Analysis}
  2707. \label{sec:liveness-analysis-Rvar}
  2708. \index{liveness analysis}
  2709. The \code{uncover-live} pass performs \emph{liveness analysis}, that
  2710. is, it discovers which variables are in-use in different regions of a
  2711. program.
  2712. %
  2713. A variable or register is \emph{live} at a program point if its
  2714. current value is used at some later point in the program. We
  2715. refer to variables and registers collectively as \emph{locations}.
  2716. %
  2717. Consider the following code fragment in which there are two writes to
  2718. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2719. \begin{center}
  2720. \begin{minipage}{0.96\textwidth}
  2721. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2722. movq $5, a
  2723. movq $30, b
  2724. movq a, c
  2725. movq $10, b
  2726. addq b, c
  2727. \end{lstlisting}
  2728. \end{minipage}
  2729. \end{center}
  2730. The answer is no because \code{a} is live from line 1 to 3 and
  2731. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  2732. line 2 is never used because it is overwritten (line 4) before the
  2733. next read (line 5).
  2734. \begin{wrapfigure}[19]{l}[1.0in]{0.6\textwidth}
  2735. \small
  2736. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2737. A \emph{set} is an unordered collection of elements without duplicates.
  2738. \index{set}
  2739. \begin{description}
  2740. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2741. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2742. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2743. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2744. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2745. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2746. \end{description}
  2747. \end{tcolorbox}
  2748. \end{wrapfigure}
  2749. The live locations can be computed by traversing the instruction
  2750. sequence back to front (i.e., backwards in execution order). Let
  2751. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2752. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2753. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2754. locations before instruction $I_k$. The live locations after an
  2755. instruction are always the same as the live locations before the next
  2756. instruction. \index{live-after} \index{live-before}
  2757. \begin{equation} \label{eq:live-after-before-next}
  2758. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2759. \end{equation}
  2760. To start things off, there are no live locations after the last
  2761. instruction, so
  2762. \begin{equation}\label{eq:live-last-empty}
  2763. L_{\mathsf{after}}(n) = \emptyset
  2764. \end{equation}
  2765. We then apply the following rule repeatedly, traversing the
  2766. instruction sequence back to front.
  2767. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2768. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2769. \end{equation}
  2770. where $W(k)$ are the locations written to by instruction $I_k$ and
  2771. $R(k)$ are the locations read by instruction $I_k$.
  2772. There is a special case for \code{jmp} instructions. The locations
  2773. that are live before a \code{jmp} should be the locations in
  2774. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  2775. maintaining an alist named \code{label->live} that maps each label to
  2776. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  2777. now the only \code{jmp} in a \LangXVar{} program is the one at the
  2778. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  2779. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  2780. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  2781. Let us walk through the above example, applying these formulas
  2782. starting with the instruction on line 5. We collect the answers in
  2783. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  2784. \code{addq b, c} instruction is $\emptyset$ because it is the last
  2785. instruction (formula~\ref{eq:live-last-empty}). The
  2786. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  2787. because it reads from variables \code{b} and \code{c}
  2788. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2789. \[
  2790. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2791. \]
  2792. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2793. the live-before set from line 5 to be the live-after set for this
  2794. instruction (formula~\ref{eq:live-after-before-next}).
  2795. \[
  2796. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2797. \]
  2798. This move instruction writes to \code{b} and does not read from any
  2799. variables, so we have the following live-before set
  2800. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2801. \[
  2802. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2803. \]
  2804. The live-before for instruction \code{movq a, c}
  2805. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2806. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2807. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2808. variable that is not live and does not read from a variable.
  2809. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2810. because it writes to variable \code{a}.
  2811. \begin{figure}[tbp]
  2812. \begin{minipage}{0.45\textwidth}
  2813. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2814. movq $5, a
  2815. movq $30, b
  2816. movq a, c
  2817. movq $10, b
  2818. addq b, c
  2819. \end{lstlisting}
  2820. \end{minipage}
  2821. \vrule\hspace{10pt}
  2822. \begin{minipage}{0.45\textwidth}
  2823. \begin{align*}
  2824. L_{\mathsf{before}}(1)= \emptyset,
  2825. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2826. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2827. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2828. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2829. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2830. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2831. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2832. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2833. L_{\mathsf{after}}(5)= \emptyset
  2834. \end{align*}
  2835. \end{minipage}
  2836. \caption{Example output of liveness analysis on a short example.}
  2837. \label{fig:liveness-example-0}
  2838. \end{figure}
  2839. \begin{exercise}\normalfont
  2840. Perform liveness analysis on the running example in
  2841. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  2842. sets for each instruction. Compare your answers to the solution
  2843. shown in Figure~\ref{fig:live-eg}.
  2844. \end{exercise}
  2845. \begin{figure}[tp]
  2846. \hspace{20pt}
  2847. \begin{minipage}{0.45\textwidth}
  2848. \begin{lstlisting}
  2849. |$\{\ttm{rsp}\}$|
  2850. movq $1, v
  2851. |$\{\ttm{v},\ttm{rsp}\}$|
  2852. movq $42, w
  2853. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  2854. movq v, x
  2855. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2856. addq $7, x
  2857. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2858. movq x, y
  2859. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  2860. movq x, z
  2861. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2862. addq w, z
  2863. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2864. movq y, t
  2865. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2866. negq t
  2867. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2868. movq z, %rax
  2869. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  2870. addq t, %rax
  2871. |$\{\ttm{rax},\ttm{rsp}\}$|
  2872. jmp conclusion
  2873. \end{lstlisting}
  2874. \end{minipage}
  2875. \caption{The running example annotated with live-after sets.}
  2876. \label{fig:live-eg}
  2877. \end{figure}
  2878. \begin{exercise}\normalfont
  2879. Implement the \code{uncover-live} pass. Store the sequence of
  2880. live-after sets in the $\itm{info}$ field of the \code{Block}
  2881. structure.
  2882. %
  2883. We recommend creating an auxiliary function that takes a list of
  2884. instructions and an initial live-after set (typically empty) and
  2885. returns the list of live-after sets.
  2886. %
  2887. We also recommend creating auxiliary functions to 1) compute the set
  2888. of locations that appear in an \Arg{}, 2) compute the locations read
  2889. by an instruction (the $R$ function), and 3) the locations written by
  2890. an instruction (the $W$ function). The \code{callq} instruction should
  2891. include all of the caller-saved registers in its write-set $W$ because
  2892. the calling convention says that those registers may be written to
  2893. during the function call. Likewise, the \code{callq} instruction
  2894. should include the appropriate argument-passing registers in its
  2895. read-set $R$, depending on the arity of the function being
  2896. called. (This is why the abstract syntax for \code{callq} includes the
  2897. arity.)
  2898. \end{exercise}
  2899. \clearpage
  2900. \section{Build the Interference Graph}
  2901. \label{sec:build-interference}
  2902. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  2903. \small
  2904. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2905. A \emph{graph} is a collection of vertices and edges where each
  2906. edge connects two vertices. A graph is \emph{directed} if each
  2907. edge points from a source to a target. Otherwise the graph is
  2908. \emph{undirected}.
  2909. \index{graph}\index{directed graph}\index{undirected graph}
  2910. \begin{description}
  2911. %% We currently don't use directed graphs. We instead use
  2912. %% directed multi-graphs. -Jeremy
  2913. %% \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2914. %% directed graph from a list of edges. Each edge is a list
  2915. %% containing the source and target vertex.
  2916. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2917. undirected graph from a list of edges. Each edge is represented by
  2918. a list containing two vertices.
  2919. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2920. inserts a vertex into the graph.
  2921. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2922. inserts an edge between the two vertices into the graph.
  2923. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2924. returns a sequence of all the neighbors of the given vertex.
  2925. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2926. returns a sequence of all the vertices in the graph.
  2927. \end{description}
  2928. \end{tcolorbox}
  2929. \end{wrapfigure}
  2930. Based on the liveness analysis, we know where each location is live.
  2931. However, during register allocation, we need to answer questions of
  2932. the specific form: are locations $u$ and $v$ live at the same time?
  2933. (And therefore cannot be assigned to the same register.) To make this
  2934. question more efficient to answer, we create an explicit data
  2935. structure, an \emph{interference graph}\index{interference graph}. An
  2936. interference graph is an undirected graph that has an edge between two
  2937. locations if they are live at the same time, that is, if they
  2938. interfere with each other.
  2939. An obvious way to compute the interference graph is to look at the set
  2940. of live locations between each instruction and the next and add an edge to the graph
  2941. for every pair of variables in the same set. This approach is less
  2942. than ideal for two reasons. First, it can be expensive because it
  2943. takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  2944. locations. Second, in the special case where two locations hold the
  2945. same value (because one was assigned to the other), they can be live
  2946. at the same time without interfering with each other.
  2947. A better way to compute the interference graph is to focus on
  2948. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  2949. must not overwrite something in a live location. So for each
  2950. instruction, we create an edge between the locations being written to
  2951. and the live locations. (Except that one should not create self
  2952. edges.) Note that for the \key{callq} instruction, we consider all of
  2953. the caller-saved registers as being written to, so an edge is added
  2954. between every live variable and every caller-saved register. For
  2955. \key{movq}, we deal with the above-mentioned special case by not
  2956. adding an edge between a live variable $v$ and the destination if $v$
  2957. matches the source. So we have the following two rules.
  2958. \begin{enumerate}
  2959. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2960. $d$, then add the edge $(d,v)$ for every $v \in
  2961. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2962. \item For any other instruction $I_k$, for every $d \in W(k)$
  2963. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2964. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2965. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2966. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2967. %% \item If instruction $I_k$ is of the form \key{callq}
  2968. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2969. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2970. \end{enumerate}
  2971. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2972. the above rules to each instruction. We highlight a few of the
  2973. instructions. The first instruction is \lstinline{movq $1, v} and the
  2974. live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies, so \code{v}
  2975. interferes with \code{rsp}.
  2976. %
  2977. The fourth instruction is \lstinline{addq $7, x} and the live-after
  2978. set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so $\ttm{x}$
  2979. interferes with \ttm{w} and \ttm{rsp}.
  2980. %
  2981. The next instruction is \lstinline{movq x, y} and the live-after set
  2982. is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1 applies, so \ttm{y}
  2983. interferes with \ttm{w} and \ttm{rsp} but not \ttm{x} because \ttm{x}
  2984. is the source of the move and therefore \ttm{x} and \ttm{y} hold the
  2985. same value. Figure~\ref{fig:interference-results} lists the
  2986. interference results for all of the instructions and the resulting
  2987. interference graph is shown in Figure~\ref{fig:interfere}.
  2988. \begin{figure}[tbp]
  2989. \begin{quote}
  2990. \begin{tabular}{ll}
  2991. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  2992. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  2993. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2994. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2995. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  2996. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  2997. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  2998. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2999. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3000. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  3001. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  3002. \lstinline!jmp conclusion!& no interference.
  3003. \end{tabular}
  3004. \end{quote}
  3005. \caption{Interference results for the running example.}
  3006. \label{fig:interference-results}
  3007. \end{figure}
  3008. \begin{figure}[tbp]
  3009. \large
  3010. \[
  3011. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3012. \node (rax) at (0,0) {$\ttm{rax}$};
  3013. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3014. \node (t1) at (0,2) {$\ttm{t}$};
  3015. \node (z) at (3,2) {$\ttm{z}$};
  3016. \node (x) at (6,2) {$\ttm{x}$};
  3017. \node (y) at (3,0) {$\ttm{y}$};
  3018. \node (w) at (6,0) {$\ttm{w}$};
  3019. \node (v) at (9,0) {$\ttm{v}$};
  3020. \draw (t1) to (rax);
  3021. \draw (t1) to (z);
  3022. \draw (z) to (y);
  3023. \draw (z) to (w);
  3024. \draw (x) to (w);
  3025. \draw (y) to (w);
  3026. \draw (v) to (w);
  3027. \draw (v) to (rsp);
  3028. \draw (w) to (rsp);
  3029. \draw (x) to (rsp);
  3030. \draw (y) to (rsp);
  3031. \path[-.,bend left=15] (z) edge node {} (rsp);
  3032. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3033. \draw (rax) to (rsp);
  3034. \end{tikzpicture}
  3035. \]
  3036. \caption{The interference graph of the example program.}
  3037. \label{fig:interfere}
  3038. \end{figure}
  3039. %% Our next concern is to choose a data structure for representing the
  3040. %% interference graph. There are many choices for how to represent a
  3041. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  3042. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  3043. %% data structure is to study the algorithm that uses the data structure,
  3044. %% determine what operations need to be performed, and then choose the
  3045. %% data structure that provide the most efficient implementations of
  3046. %% those operations. Often times the choice of data structure can have an
  3047. %% effect on the time complexity of the algorithm, as it does here. If
  3048. %% you skim the next section, you will see that the register allocation
  3049. %% algorithm needs to ask the graph for all of its vertices and, given a
  3050. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  3051. %% correct choice of graph representation is that of an adjacency
  3052. %% list. There are helper functions in \code{utilities.rkt} for
  3053. %% representing graphs using the adjacency list representation:
  3054. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  3055. %% (Appendix~\ref{appendix:utilities}).
  3056. %% %
  3057. %% \margincomment{\footnotesize To do: change to use the
  3058. %% Racket graph library. \\ --Jeremy}
  3059. %% %
  3060. %% In particular, those functions use a hash table to map each vertex to
  3061. %% the set of adjacent vertices, and the sets are represented using
  3062. %% Racket's \key{set}, which is also a hash table.
  3063. \begin{exercise}\normalfont
  3064. Implement the compiler pass named \code{build-interference} according
  3065. to the algorithm suggested above. We recommend using the \code{graph}
  3066. package to create and inspect the interference graph. The output
  3067. graph of this pass should be stored in the $\itm{info}$ field of the
  3068. program, under the key \code{conflicts}.
  3069. \end{exercise}
  3070. \section{Graph Coloring via Sudoku}
  3071. \label{sec:graph-coloring}
  3072. \index{graph coloring}
  3073. \index{Sudoku}
  3074. \index{color}
  3075. We come to the main event, mapping variables to registers and stack
  3076. locations. Variables that interfere with each other must be mapped to
  3077. different locations. In terms of the interference graph, this means
  3078. that adjacent vertices must be mapped to different locations. If we
  3079. think of locations as colors, the register allocation problem becomes
  3080. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  3081. The reader may be more familiar with the graph coloring problem than he
  3082. or she realizes; the popular game of Sudoku is an instance of the
  3083. graph coloring problem. The following describes how to build a graph
  3084. out of an initial Sudoku board.
  3085. \begin{itemize}
  3086. \item There is one vertex in the graph for each Sudoku square.
  3087. \item There is an edge between two vertices if the corresponding squares
  3088. are in the same row, in the same column, or if the squares are in
  3089. the same $3\times 3$ region.
  3090. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  3091. \item Based on the initial assignment of numbers to squares in the
  3092. Sudoku board, assign the corresponding colors to the corresponding
  3093. vertices in the graph.
  3094. \end{itemize}
  3095. If you can color the remaining vertices in the graph with the nine
  3096. colors, then you have also solved the corresponding game of Sudoku.
  3097. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  3098. the corresponding graph with colored vertices. We map the Sudoku
  3099. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  3100. sampling of the vertices (the colored ones) because showing edges for
  3101. all of the vertices would make the graph unreadable.
  3102. \begin{figure}[tbp]
  3103. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  3104. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  3105. \caption{A Sudoku game board and the corresponding colored graph.}
  3106. \label{fig:sudoku-graph}
  3107. \end{figure}
  3108. It turns out that some techniques for playing Sudoku correspond to
  3109. heuristics used in graph coloring algorithms. For example, one of the
  3110. basic techniques for Sudoku is called Pencil Marks. The idea is to use
  3111. a process of elimination to determine what numbers are no longer
  3112. available for a square and write down those numbers in the square
  3113. (writing very small). For example, if the number $1$ is assigned to a
  3114. square, then write the pencil mark $1$ in all the squares in the same
  3115. row, column, and region.
  3116. %
  3117. The Pencil Marks technique corresponds to the notion of
  3118. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}. The
  3119. saturation of a vertex, in Sudoku terms, is the set of numbers that
  3120. are no longer available. In graph terminology, we have the following
  3121. definition:
  3122. \begin{equation*}
  3123. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  3124. \text{ and } \mathrm{color}(v) = c \}
  3125. \end{equation*}
  3126. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  3127. edge with $u$.
  3128. Using the Pencil Marks technique leads to a simple strategy for
  3129. filling in numbers: if there is a square with only one possible number
  3130. left, then choose that number! But what if there are no squares with
  3131. only one possibility left? One brute-force approach is to try them
  3132. all: choose the first one and if it ultimately leads to a solution,
  3133. great. If not, backtrack and choose the next possibility. One good
  3134. thing about Pencil Marks is that it reduces the degree of branching in
  3135. the search tree. Nevertheless, backtracking can be horribly time
  3136. consuming. One way to reduce the amount of backtracking is to use the
  3137. most-constrained-first heuristic. That is, when choosing a square,
  3138. always choose one with the fewest possibilities left (the vertex with
  3139. the highest saturation). The idea is that choosing highly constrained
  3140. squares earlier rather than later is better because later on there may
  3141. not be any possibilities left in the highly saturated squares.
  3142. However, register allocation is easier than Sudoku because the
  3143. register allocator can map variables to stack locations when the
  3144. registers run out. Thus, it makes sense to replace backtracking with
  3145. greedy search: make the best choice at the time and keep going. We
  3146. still wish to minimize the number of colors needed, so we use the
  3147. most-constrained-first heuristic in the greedy search.
  3148. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3149. algorithm for register allocation based on saturation and the
  3150. most-constrained-first heuristic. It is roughly equivalent to the
  3151. DSATUR
  3152. algorithm~\citep{Brelaz:1979eu,Gebremedhin:1999fk,Omari:2006uq}. Just
  3153. as in Sudoku, the algorithm represents colors with integers. The
  3154. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  3155. for register allocation. The integers $k$ and larger correspond to
  3156. stack locations. The registers that are not used for register
  3157. allocation, such as \code{rax}, are assigned to negative integers. In
  3158. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3159. %% One might wonder why we include registers at all in the liveness
  3160. %% analysis and interference graph. For example, we never allocate a
  3161. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  3162. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  3163. %% to use register for passing arguments to functions, it will be
  3164. %% necessary for those registers to appear in the interference graph
  3165. %% because those registers will also be assigned to variables, and we
  3166. %% don't want those two uses to encroach on each other. Regarding
  3167. %% registers such as \code{rax} and \code{rsp} that are not used for
  3168. %% variables, we could omit them from the interference graph but that
  3169. %% would require adding special cases to our algorithm, which would
  3170. %% complicate the logic for little gain.
  3171. \begin{figure}[btp]
  3172. \centering
  3173. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3174. Algorithm: DSATUR
  3175. Input: a graph |$G$|
  3176. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3177. |$W \gets \mathrm{vertices}(G)$|
  3178. while |$W \neq \emptyset$| do
  3179. pick a vertex |$u$| from |$W$| with the highest saturation,
  3180. breaking ties randomly
  3181. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3182. |$\mathrm{color}[u] \gets c$|
  3183. |$W \gets W - \{u\}$|
  3184. \end{lstlisting}
  3185. \caption{The saturation-based greedy graph coloring algorithm.}
  3186. \label{fig:satur-algo}
  3187. \end{figure}
  3188. With the DSATUR algorithm in hand, let us return to the running
  3189. example and consider how to color the interference graph in
  3190. Figure~\ref{fig:interfere}.
  3191. %
  3192. We start by assigning the register nodes to their own color. For
  3193. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  3194. assigned $-2$. The variables are not yet colored, so they are
  3195. annotated with a dash. We then update the saturation for vertices that
  3196. are adjacent to a register, obtaining the following annotated
  3197. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  3198. it interferes with both \code{rax} and \code{rsp}.
  3199. \[
  3200. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3201. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3202. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3203. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3204. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3205. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3206. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3207. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3208. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3209. \draw (t1) to (rax);
  3210. \draw (t1) to (z);
  3211. \draw (z) to (y);
  3212. \draw (z) to (w);
  3213. \draw (x) to (w);
  3214. \draw (y) to (w);
  3215. \draw (v) to (w);
  3216. \draw (v) to (rsp);
  3217. \draw (w) to (rsp);
  3218. \draw (x) to (rsp);
  3219. \draw (y) to (rsp);
  3220. \path[-.,bend left=15] (z) edge node {} (rsp);
  3221. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3222. \draw (rax) to (rsp);
  3223. \end{tikzpicture}
  3224. \]
  3225. The algorithm says to select a maximally saturated vertex. So we pick
  3226. $\ttm{t}$ and color it with the first available integer, which is
  3227. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3228. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3229. \[
  3230. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3231. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3232. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3233. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3234. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3235. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3236. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3237. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3238. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3239. \draw (t1) to (rax);
  3240. \draw (t1) to (z);
  3241. \draw (z) to (y);
  3242. \draw (z) to (w);
  3243. \draw (x) to (w);
  3244. \draw (y) to (w);
  3245. \draw (v) to (w);
  3246. \draw (v) to (rsp);
  3247. \draw (w) to (rsp);
  3248. \draw (x) to (rsp);
  3249. \draw (y) to (rsp);
  3250. \path[-.,bend left=15] (z) edge node {} (rsp);
  3251. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3252. \draw (rax) to (rsp);
  3253. \end{tikzpicture}
  3254. \]
  3255. We repeat the process, selecting the next maximally saturated vertex,
  3256. which is \code{z}, and color it with the first available number, which
  3257. is $1$. We add $1$ to the saturation for the neighboring vertices
  3258. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3259. \[
  3260. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3261. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3262. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3263. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3264. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3265. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3266. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3267. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3268. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3269. \draw (t1) to (rax);
  3270. \draw (t1) to (z);
  3271. \draw (z) to (y);
  3272. \draw (z) to (w);
  3273. \draw (x) to (w);
  3274. \draw (y) to (w);
  3275. \draw (v) to (w);
  3276. \draw (v) to (rsp);
  3277. \draw (w) to (rsp);
  3278. \draw (x) to (rsp);
  3279. \draw (y) to (rsp);
  3280. \path[-.,bend left=15] (z) edge node {} (rsp);
  3281. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3282. \draw (rax) to (rsp);
  3283. \end{tikzpicture}
  3284. \]
  3285. The most saturated vertices are now \code{w} and \code{y}. We color
  3286. \code{w} with the first available color, which is $0$.
  3287. \[
  3288. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3289. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3290. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3291. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3292. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3293. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3294. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  3295. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  3296. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3297. \draw (t1) to (rax);
  3298. \draw (t1) to (z);
  3299. \draw (z) to (y);
  3300. \draw (z) to (w);
  3301. \draw (x) to (w);
  3302. \draw (y) to (w);
  3303. \draw (v) to (w);
  3304. \draw (v) to (rsp);
  3305. \draw (w) to (rsp);
  3306. \draw (x) to (rsp);
  3307. \draw (y) to (rsp);
  3308. \path[-.,bend left=15] (z) edge node {} (rsp);
  3309. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3310. \draw (rax) to (rsp);
  3311. \end{tikzpicture}
  3312. \]
  3313. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3314. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3315. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3316. and \code{z}, whose colors are $0$ and $1$ respectively.
  3317. \[
  3318. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3319. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3320. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3321. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3322. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3323. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3324. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3325. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3326. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3327. \draw (t1) to (rax);
  3328. \draw (t1) to (z);
  3329. \draw (z) to (y);
  3330. \draw (z) to (w);
  3331. \draw (x) to (w);
  3332. \draw (y) to (w);
  3333. \draw (v) to (w);
  3334. \draw (v) to (rsp);
  3335. \draw (w) to (rsp);
  3336. \draw (x) to (rsp);
  3337. \draw (y) to (rsp);
  3338. \path[-.,bend left=15] (z) edge node {} (rsp);
  3339. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3340. \draw (rax) to (rsp);
  3341. \end{tikzpicture}
  3342. \]
  3343. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  3344. \[
  3345. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3346. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3347. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3348. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3349. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3350. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3351. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3352. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3353. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3354. \draw (t1) to (rax);
  3355. \draw (t1) to (z);
  3356. \draw (z) to (y);
  3357. \draw (z) to (w);
  3358. \draw (x) to (w);
  3359. \draw (y) to (w);
  3360. \draw (v) to (w);
  3361. \draw (v) to (rsp);
  3362. \draw (w) to (rsp);
  3363. \draw (x) to (rsp);
  3364. \draw (y) to (rsp);
  3365. \path[-.,bend left=15] (z) edge node {} (rsp);
  3366. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3367. \draw (rax) to (rsp);
  3368. \end{tikzpicture}
  3369. \]
  3370. In the last step of the algorithm, we color \code{x} with $1$.
  3371. \[
  3372. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3373. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3374. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3375. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3376. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3377. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  3378. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3379. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3380. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3381. \draw (t1) to (rax);
  3382. \draw (t1) to (z);
  3383. \draw (z) to (y);
  3384. \draw (z) to (w);
  3385. \draw (x) to (w);
  3386. \draw (y) to (w);
  3387. \draw (v) to (w);
  3388. \draw (v) to (rsp);
  3389. \draw (w) to (rsp);
  3390. \draw (x) to (rsp);
  3391. \draw (y) to (rsp);
  3392. \path[-.,bend left=15] (z) edge node {} (rsp);
  3393. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3394. \draw (rax) to (rsp);
  3395. \end{tikzpicture}
  3396. \]
  3397. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  3398. \small
  3399. \begin{tcolorbox}[title=Priority Queue]
  3400. A \emph{priority queue} is a collection of items in which the
  3401. removal of items is governed by priority. In a ``min'' queue,
  3402. lower priority items are removed first. An implementation is in
  3403. \code{priority\_queue.rkt} of the support code. \index{priority
  3404. queue} \index{minimum priority queue}
  3405. \begin{description}
  3406. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3407. priority queue that uses the $\itm{cmp}$ predicate to determine
  3408. whether its first argument has lower or equal priority to its
  3409. second argument.
  3410. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3411. items in the queue.
  3412. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3413. the item into the queue and returns a handle for the item in the
  3414. queue.
  3415. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3416. the lowest priority.
  3417. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3418. notifies the queue that the priority has decreased for the item
  3419. associated with the given handle.
  3420. \end{description}
  3421. \end{tcolorbox}
  3422. \end{wrapfigure}
  3423. We recommend creating an auxiliary function named \code{color-graph}
  3424. that takes an interference graph and a list of all the variables in
  3425. the program. This function should return a mapping of variables to
  3426. their colors (represented as natural numbers). By creating this helper
  3427. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  3428. when we add support for functions.
  3429. To prioritize the processing of highly saturated nodes inside the
  3430. \code{color-graph} function, we recommend using the priority queue
  3431. data structure (see the side bar on the right). In addition, you will
  3432. need to maintain a mapping from variables to their ``handles'' in the
  3433. priority queue so that you can notify the priority queue when their
  3434. saturation changes.
  3435. With the coloring complete, we finalize the assignment of variables to
  3436. registers and stack locations. We map the first $k$ colors to the $k$
  3437. registers and the rest of the colors to stack locations. Suppose for
  3438. the moment that we have just one register to use for register
  3439. allocation, \key{rcx}. Then we have the following map from colors to
  3440. locations.
  3441. \[
  3442. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3443. \]
  3444. Composing this mapping with the coloring, we arrive at the following
  3445. assignment of variables to locations.
  3446. \begin{gather*}
  3447. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  3448. \ttm{w} \mapsto \key{\%rcx}, \,
  3449. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3450. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3451. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3452. \ttm{t} \mapsto \key{\%rcx} \}
  3453. \end{gather*}
  3454. Adapt the code from the \code{assign-homes} pass
  3455. (Section~\ref{sec:assign-Rvar}) to replace the variables with their
  3456. assigned location. Applying the above assignment to our running
  3457. example, on the left, yields the program on the right.
  3458. % why frame size of 32? -JGS
  3459. \begin{center}
  3460. \begin{minipage}{0.3\textwidth}
  3461. \begin{lstlisting}
  3462. movq $1, v
  3463. movq $42, w
  3464. movq v, x
  3465. addq $7, x
  3466. movq x, y
  3467. movq x, z
  3468. addq w, z
  3469. movq y, t
  3470. negq t
  3471. movq z, %rax
  3472. addq t, %rax
  3473. jmp conclusion
  3474. \end{lstlisting}
  3475. \end{minipage}
  3476. $\Rightarrow\qquad$
  3477. \begin{minipage}{0.45\textwidth}
  3478. \begin{lstlisting}
  3479. movq $1, -8(%rbp)
  3480. movq $42, %rcx
  3481. movq -8(%rbp), -8(%rbp)
  3482. addq $7, -8(%rbp)
  3483. movq -8(%rbp), -16(%rbp)
  3484. movq -8(%rbp), -8(%rbp)
  3485. addq %rcx, -8(%rbp)
  3486. movq -16(%rbp), %rcx
  3487. negq %rcx
  3488. movq -8(%rbp), %rax
  3489. addq %rcx, %rax
  3490. jmp conclusion
  3491. \end{lstlisting}
  3492. \end{minipage}
  3493. \end{center}
  3494. \begin{exercise}\normalfont
  3495. %
  3496. Implement the compiler pass \code{allocate-registers}.
  3497. %
  3498. Create five programs that exercise all of the register allocation
  3499. algorithm, including spilling variables to the stack.
  3500. %
  3501. Replace \code{assign-homes} in the list of \code{passes} in the
  3502. \code{run-tests.rkt} script with the three new passes:
  3503. \code{uncover-live}, \code{build-interference}, and
  3504. \code{allocate-registers}.
  3505. %
  3506. Temporarily remove the \code{print-x86} pass from the list of passes
  3507. and the call to \code{compiler-tests}.
  3508. %
  3509. Run the script to test the register allocator.
  3510. \end{exercise}
  3511. \section{Patch Instructions}
  3512. \label{sec:patch-instructions}
  3513. The remaining step in the compilation to x86 is to ensure that the
  3514. instructions have at most one argument that is a memory access.
  3515. In the running example, the instruction \code{movq -8(\%rbp), -16(\%rbp)}
  3516. is problematic. The fix is to first move \code{-8(\%rbp)}
  3517. into \code{rax} and then move \code{rax} into \code{-16(\%rbp)}.
  3518. %
  3519. The two moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  3520. problematic, but they can be fixed by simply deleting them. In
  3521. general, we recommend deleting all the trivial moves whose source and
  3522. destination are the same location.
  3523. %
  3524. The following is the output of \code{patch-instructions} on the
  3525. running example.
  3526. \begin{center}
  3527. \begin{minipage}{0.4\textwidth}
  3528. \begin{lstlisting}
  3529. movq $1, -8(%rbp)
  3530. movq $42, %rcx
  3531. movq -8(%rbp), -8(%rbp)
  3532. addq $7, -8(%rbp)
  3533. movq -8(%rbp), -16(%rbp)
  3534. movq -8(%rbp), -8(%rbp)
  3535. addq %rcx, -8(%rbp)
  3536. movq -16(%rbp), %rcx
  3537. negq %rcx
  3538. movq -8(%rbp), %rax
  3539. addq %rcx, %rax
  3540. jmp conclusion
  3541. \end{lstlisting}
  3542. \end{minipage}
  3543. $\Rightarrow\qquad$
  3544. \begin{minipage}{0.45\textwidth}
  3545. \begin{lstlisting}
  3546. movq $1, -8(%rbp)
  3547. movq $42, %rcx
  3548. addq $7, -8(%rbp)
  3549. movq -8(%rbp), %rax
  3550. movq %rax, -16(%rbp)
  3551. addq %rcx, -8(%rbp)
  3552. movq -16(%rbp), %rcx
  3553. negq %rcx
  3554. movq -8(%rbp), %rax
  3555. addq %rcx, %rax
  3556. jmp conclusion
  3557. \end{lstlisting}
  3558. \end{minipage}
  3559. \end{center}
  3560. \begin{exercise}\normalfont
  3561. %
  3562. Implement the \code{patch-instructions} compiler pass.
  3563. %
  3564. Insert it after \code{allocate-registers} in the list of \code{passes}
  3565. in the \code{run-tests.rkt} script.
  3566. %
  3567. Run the script to test the \code{patch-instructions} pass.
  3568. \end{exercise}
  3569. \section{Print x86}
  3570. \label{sec:print-x86-reg-alloc}
  3571. \index{calling conventions}
  3572. \index{prelude}\index{conclusion}
  3573. Recall that the \code{print-x86} pass generates the prelude and
  3574. conclusion instructions to satisfy the x86 calling conventions
  3575. (Section~\ref{sec:calling-conventions}). With the addition of the
  3576. register allocator, the callee-saved registers used by the register
  3577. allocator must be saved in the prelude and restored in the conclusion.
  3578. In the \code{allocate-registers} pass, add an entry to the \itm{info}
  3579. of \code{X86Program} named \code{used-callee} that stores the set of
  3580. callee-saved registers that were assigned to variables. The
  3581. \code{print-x86} pass can then access this information to decide which
  3582. callee-saved registers need to be saved and restored.
  3583. %
  3584. When calculating the size of the frame to adjust the \code{rsp} in the
  3585. prelude, make sure to take into account the space used for saving the
  3586. callee-saved registers. Also, don't forget that the frame needs to be
  3587. a multiple of 16 bytes!
  3588. An overview of all of the passes involved in register allocation is
  3589. shown in Figure~\ref{fig:reg-alloc-passes}.
  3590. \begin{figure}[tbp]
  3591. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3592. \node (Rvar) at (0,2) {\large \LangVar{}};
  3593. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  3594. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  3595. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  3596. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  3597. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  3598. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  3599. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  3600. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  3601. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  3602. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  3603. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  3604. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-1);
  3605. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3606. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  3607. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3608. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3609. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3610. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3611. \end{tikzpicture}
  3612. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  3613. \label{fig:reg-alloc-passes}
  3614. \end{figure}
  3615. \begin{exercise}\normalfont
  3616. Update the \code{print-x86} pass as described in this section.
  3617. %
  3618. In the \code{run-tests.rkt} script, reinstate \code{print-x86} in the
  3619. list of passes and the call to \code{compiler-tests}.
  3620. %
  3621. Run the script to test the complete compiler for \LangVar{} that
  3622. performs register allocation.
  3623. \end{exercise}
  3624. \section{Challenge: Move Biasing}
  3625. \label{sec:move-biasing}
  3626. \index{move biasing}
  3627. This section describes an enhancement to the register allocator for
  3628. students looking for an extra challenge or who have a deeper interest
  3629. in register allocation.
  3630. To motivate the need for move biasing we return to the running example
  3631. but this time use all of the general purpose registers. So we have
  3632. the following mapping of color numbers to registers.
  3633. \[
  3634. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  3635. \]
  3636. Using the same assignment of variables to color numbers that was
  3637. produced by the register allocator described in the last section, we
  3638. get the following program.
  3639. \begin{center}
  3640. \begin{minipage}{0.3\textwidth}
  3641. \begin{lstlisting}
  3642. movq $1, v
  3643. movq $42, w
  3644. movq v, x
  3645. addq $7, x
  3646. movq x, y
  3647. movq x, z
  3648. addq w, z
  3649. movq y, t
  3650. negq t
  3651. movq z, %rax
  3652. addq t, %rax
  3653. jmp conclusion
  3654. \end{lstlisting}
  3655. \end{minipage}
  3656. $\Rightarrow\qquad$
  3657. \begin{minipage}{0.45\textwidth}
  3658. \begin{lstlisting}
  3659. movq $1, %rdx
  3660. movq $42, %rcx
  3661. movq %rdx, %rdx
  3662. addq $7, %rdx
  3663. movq %rdx, %rsi
  3664. movq %rdx, %rdx
  3665. addq %rcx, %rdx
  3666. movq %rsi, %rcx
  3667. negq %rcx
  3668. movq %rdx, %rax
  3669. addq %rcx, %rax
  3670. jmp conclusion
  3671. \end{lstlisting}
  3672. \end{minipage}
  3673. \end{center}
  3674. In the above output code there are two \key{movq} instructions that
  3675. can be removed because their source and target are the same. However,
  3676. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3677. register, we could instead remove three \key{movq} instructions. We
  3678. can accomplish this by taking into account which variables appear in
  3679. \key{movq} instructions with which other variables.
  3680. We say that two variables $p$ and $q$ are \emph{move
  3681. related}\index{move related} if they participate together in a
  3682. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3683. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3684. for a variable, it should prefer a color that has already been used
  3685. for a move-related variable (assuming that they do not interfere). Of
  3686. course, this preference should not override the preference for
  3687. registers over stack locations. This preference should be used as a
  3688. tie breaker when choosing between registers or when choosing between
  3689. stack locations.
  3690. We recommend representing the move relationships in a graph, similar
  3691. to how we represented interference. The following is the \emph{move
  3692. graph} for our running example.
  3693. \[
  3694. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3695. \node (rax) at (0,0) {$\ttm{rax}$};
  3696. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3697. \node (t) at (0,2) {$\ttm{t}$};
  3698. \node (z) at (3,2) {$\ttm{z}$};
  3699. \node (x) at (6,2) {$\ttm{x}$};
  3700. \node (y) at (3,0) {$\ttm{y}$};
  3701. \node (w) at (6,0) {$\ttm{w}$};
  3702. \node (v) at (9,0) {$\ttm{v}$};
  3703. \draw (v) to (x);
  3704. \draw (x) to (y);
  3705. \draw (x) to (z);
  3706. \draw (y) to (t);
  3707. \end{tikzpicture}
  3708. \]
  3709. Now we replay the graph coloring, pausing to see the coloring of
  3710. \code{y}. Recall the following configuration. The most saturated vertices
  3711. were \code{w} and \code{y}.
  3712. \[
  3713. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3714. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3715. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3716. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3717. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3718. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3719. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3720. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3721. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3722. \draw (t1) to (rax);
  3723. \draw (t1) to (z);
  3724. \draw (z) to (y);
  3725. \draw (z) to (w);
  3726. \draw (x) to (w);
  3727. \draw (y) to (w);
  3728. \draw (v) to (w);
  3729. \draw (v) to (rsp);
  3730. \draw (w) to (rsp);
  3731. \draw (x) to (rsp);
  3732. \draw (y) to (rsp);
  3733. \path[-.,bend left=15] (z) edge node {} (rsp);
  3734. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3735. \draw (rax) to (rsp);
  3736. \end{tikzpicture}
  3737. \]
  3738. %
  3739. Last time we chose to color \code{w} with $0$. But this time we see
  3740. that \code{w} is not move related to any vertex, but \code{y} is move
  3741. related to \code{t}. So we choose to color \code{y} the same color as
  3742. \code{t}, $0$.
  3743. \[
  3744. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3745. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3746. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3747. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3748. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3749. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3750. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  3751. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  3752. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3753. \draw (t1) to (rax);
  3754. \draw (t1) to (z);
  3755. \draw (z) to (y);
  3756. \draw (z) to (w);
  3757. \draw (x) to (w);
  3758. \draw (y) to (w);
  3759. \draw (v) to (w);
  3760. \draw (v) to (rsp);
  3761. \draw (w) to (rsp);
  3762. \draw (x) to (rsp);
  3763. \draw (y) to (rsp);
  3764. \path[-.,bend left=15] (z) edge node {} (rsp);
  3765. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3766. \draw (rax) to (rsp);
  3767. \end{tikzpicture}
  3768. \]
  3769. Now \code{w} is the most saturated, so we color it $2$.
  3770. \[
  3771. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3772. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3773. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3774. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3775. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3776. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  3777. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3778. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3779. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  3780. \draw (t1) to (rax);
  3781. \draw (t1) to (z);
  3782. \draw (z) to (y);
  3783. \draw (z) to (w);
  3784. \draw (x) to (w);
  3785. \draw (y) to (w);
  3786. \draw (v) to (w);
  3787. \draw (v) to (rsp);
  3788. \draw (w) to (rsp);
  3789. \draw (x) to (rsp);
  3790. \draw (y) to (rsp);
  3791. \path[-.,bend left=15] (z) edge node {} (rsp);
  3792. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3793. \draw (rax) to (rsp);
  3794. \end{tikzpicture}
  3795. \]
  3796. At this point, vertices \code{x} and \code{v} are most saturated, but
  3797. \code{x} is move related to \code{y} and \code{z}, so we color
  3798. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3799. \[
  3800. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3801. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3802. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3803. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3804. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3805. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  3806. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3807. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3808. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  3809. \draw (t1) to (rax);
  3810. \draw (t) to (z);
  3811. \draw (z) to (y);
  3812. \draw (z) to (w);
  3813. \draw (x) to (w);
  3814. \draw (y) to (w);
  3815. \draw (v) to (w);
  3816. \draw (v) to (rsp);
  3817. \draw (w) to (rsp);
  3818. \draw (x) to (rsp);
  3819. \draw (y) to (rsp);
  3820. \path[-.,bend left=15] (z) edge node {} (rsp);
  3821. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3822. \draw (rax) to (rsp);
  3823. \end{tikzpicture}
  3824. \]
  3825. So we have the following assignment of variables to registers.
  3826. \begin{gather*}
  3827. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3828. \ttm{w} \mapsto \key{\%rsi}, \,
  3829. \ttm{x} \mapsto \key{\%rcx}, \,
  3830. \ttm{y} \mapsto \key{\%rcx}, \,
  3831. \ttm{z} \mapsto \key{\%rdx}, \,
  3832. \ttm{t} \mapsto \key{\%rcx} \}
  3833. \end{gather*}
  3834. We apply this register assignment to the running example, on the left,
  3835. to obtain the code in the middle. The \code{patch-instructions} then
  3836. removes the three trivial moves to obtain the code on the right.
  3837. \begin{minipage}{0.25\textwidth}
  3838. \begin{lstlisting}
  3839. movq $1, v
  3840. movq $42, w
  3841. movq v, x
  3842. addq $7, x
  3843. movq x, y
  3844. movq x, z
  3845. addq w, z
  3846. movq y, t
  3847. negq t
  3848. movq z, %rax
  3849. addq t, %rax
  3850. jmp conclusion
  3851. \end{lstlisting}
  3852. \end{minipage}
  3853. $\Rightarrow\qquad$
  3854. \begin{minipage}{0.25\textwidth}
  3855. \begin{lstlisting}
  3856. movq $1, %rcx
  3857. movq $42, %rsi
  3858. movq %rcx, %rcx
  3859. addq $7, %rcx
  3860. movq %rcx, %rcx
  3861. movq %rcx, %rdx
  3862. addq %rsi, %rdx
  3863. movq %rcx, %rcx
  3864. negq %rcx
  3865. movq %rdx, %rax
  3866. addq %rcx, %rax
  3867. jmp conclusion
  3868. \end{lstlisting}
  3869. \end{minipage}
  3870. $\Rightarrow\qquad$
  3871. \begin{minipage}{0.25\textwidth}
  3872. \begin{lstlisting}
  3873. movq $1, %rcx
  3874. movq $42, %rsi
  3875. addq $7, %rcx
  3876. movq %rcx, %rdx
  3877. addq %rsi, %rdx
  3878. negq %rcx
  3879. movq %rdx, %rax
  3880. addq %rcx, %rax
  3881. jmp conclusion
  3882. \end{lstlisting}
  3883. \end{minipage}
  3884. \begin{exercise}\normalfont
  3885. Change your implementation of \code{allocate-registers} to take move
  3886. biasing into account. Create two new tests that include at least one
  3887. opportunity for move biasing and visually inspect the output x86
  3888. programs to make sure that your move biasing is working properly. Make
  3889. sure that your compiler still passes all of the tests.
  3890. \end{exercise}
  3891. \margincomment{\footnotesize To do: another neat challenge would be to do
  3892. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3893. %% \subsection{Output of the Running Example}
  3894. %% \label{sec:reg-alloc-output}
  3895. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3896. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3897. and move biasing. To demonstrate both the use of registers and the
  3898. stack, we have limited the register allocator to use just two
  3899. registers: \code{rbx} and \code{rcx}. In the prelude\index{prelude}
  3900. of the \code{main} function, we push \code{rbx} onto the stack because
  3901. it is a callee-saved register and it was assigned to variable by the
  3902. register allocator. We subtract \code{8} from the \code{rsp} at the
  3903. end of the prelude to reserve space for the one spilled variable.
  3904. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3905. Moving on the the \code{start} block, we see how the registers were
  3906. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3907. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3908. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3909. that the prelude saved the callee-save register \code{rbx} onto the
  3910. stack. The spilled variables must be placed lower on the stack than
  3911. the saved callee-save registers, so in this case \code{w} is placed at
  3912. \code{-16(\%rbp)}.
  3913. In the \code{conclusion}\index{conclusion}, we undo the work that was
  3914. done in the prelude. We move the stack pointer up by \code{8} bytes
  3915. (the room for spilled variables), then we pop the old values of
  3916. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  3917. \code{retq} to return control to the operating system.
  3918. \begin{figure}[tbp]
  3919. % var_test_28.rkt
  3920. % (use-minimal-set-of-registers! #t)
  3921. % and only rbx rcx
  3922. % tmp 0 rbx
  3923. % z 1 rcx
  3924. % y 0 rbx
  3925. % w 2 16(%rbp)
  3926. % v 0 rbx
  3927. % x 0 rbx
  3928. \begin{lstlisting}
  3929. start:
  3930. movq $1, %rbx
  3931. movq $42, -16(%rbp)
  3932. addq $7, %rbx
  3933. movq %rbx, %rcx
  3934. addq -16(%rbp), %rcx
  3935. negq %rbx
  3936. movq %rcx, %rax
  3937. addq %rbx, %rax
  3938. jmp conclusion
  3939. .globl main
  3940. main:
  3941. pushq %rbp
  3942. movq %rsp, %rbp
  3943. pushq %rbx
  3944. subq $8, %rsp
  3945. jmp start
  3946. conclusion:
  3947. addq $8, %rsp
  3948. popq %rbx
  3949. popq %rbp
  3950. retq
  3951. \end{lstlisting}
  3952. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3953. \label{fig:running-example-x86}
  3954. \end{figure}
  3955. % challenge: prioritize variables based on execution frequencies
  3956. % and the number of uses of a variable
  3957. % challenge: enhance the coloring algorithm using Chaitin's
  3958. % approach of prioritizing high-degree variables
  3959. % by removing low-degree variables (coloring them later)
  3960. % from the interference graph
  3961. \section{Further Reading}
  3962. \label{sec:register-allocation-further-reading}
  3963. Early register allocation algorithms were developed for Fortran
  3964. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  3965. of graph coloring began in the late 1970s and early 1980s with the
  3966. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  3967. algorithm is based on the following observation of
  3968. \citet{Kempe:1879aa} from the 1870s. If a graph $G$ has a vertex $v$
  3969. with degree lower than $k$, then $G$ is $k$ colorable if the subgraph
  3970. of $G$ with $v$ removed is also $k$ colorable. Suppose that the
  3971. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  3972. different colors, but since there are less than $k$ of them, there
  3973. will be one or more colors left over to use for coloring $v$ in $G$.
  3974. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  3975. less than $k$ from the graph and recursively colors the rest of the
  3976. graph. Upon returning from the recursion, it colors $v$ with one of
  3977. the available colors and returns. \citet{Chaitin:1982vn} augments
  3978. this algorithm to handle spilling as follows. If there are no vertices
  3979. of degree lower than $k$ then pick a vertex at random, spill it,
  3980. remove it from the graph, and proceed recursively to color the rest of
  3981. the graph.
  3982. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  3983. move-related and that don't interfere with each other, a process
  3984. called \emph{coalescing}. While coalescing decreases the number of
  3985. moves, it can make the graph more difficult to
  3986. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  3987. which two variables are merged only if they have fewer than $k$
  3988. neighbors of high degree. \citet{George:1996aa} observe that
  3989. conservative coalescing is sometimes too conservative and make it more
  3990. aggressive by iterating the coalescing with the removal of low-degree
  3991. vertices.
  3992. %
  3993. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  3994. also propose \emph{biased coloring} in which a variable is assigned to
  3995. the same color as another move-related variable if possible, as
  3996. discussed in Section~\ref{sec:move-biasing}.
  3997. %
  3998. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  3999. performs coalescing, graph coloring, and spill code insertion until
  4000. all variables have been assigned a location.
  4001. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  4002. spills variables that don't have to be: a high-degree variable can be
  4003. colorable if many of its neighbors are assigned the same color.
  4004. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  4005. high-degree vertex is not immediately spilled. Instead the decision is
  4006. deferred until after the recursive call, at which point it is apparent
  4007. whether there is actually an available color or not. We observe that
  4008. this algorithm is equivalent to the smallest-last ordering
  4009. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  4010. be registers and the rest to be stack locations.
  4011. %% biased coloring
  4012. Earlier editions of the compiler course at Indiana University
  4013. \citep{Dybvig:2010aa} were based on the algorithm of
  4014. \citet{Briggs:1994kx}.
  4015. The smallest-last ordering algorithm is one of many \emph{greedy}
  4016. coloring algorithms. A greedy coloring algorithm visits all the
  4017. vertices in a particular order and assigns each one the first
  4018. available color. An \emph{offline} greedy algorithm chooses the
  4019. ordering up-front, prior to assigning colors. The algorithm of
  4020. \citet{Chaitin:1981vl} should be considered offline because the vertex
  4021. ordering does not depend on the colors assigned, so the algorithm
  4022. could be split into two phases. Other orderings are possible. For
  4023. example, \citet{Chow:1984ys} order variables according an estimate of
  4024. runtime cost.
  4025. An \emph{online} greedy coloring algorithm uses information about the
  4026. current assignment of colors to influence the order in which the
  4027. remaining vertices are colored. The saturation-based algorithm
  4028. described in this chapter is one such algorithm. We choose to use
  4029. saturation-based coloring is because it is fun to introduce graph
  4030. coloring via Sudoku.
  4031. A register allocator may choose to map each variable to just one
  4032. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  4033. variable to one or more locations. The later can be achieved by
  4034. \emph{live range splitting}, where a variable is replaced by several
  4035. variables that each handle part of its live
  4036. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  4037. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  4038. %% replacement algorithm, bottom-up local
  4039. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  4040. %% Cooper: top-down (priority bassed), bottom-up
  4041. %% top-down
  4042. %% order variables by priority (estimated cost)
  4043. %% caveat: split variables into two groups:
  4044. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  4045. %% color the constrained ones first
  4046. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  4047. %% cite J. Cocke for an algorithm that colors variables
  4048. %% in a high-degree first ordering
  4049. %Register Allocation via Usage Counts, Freiburghouse CACM
  4050. \citet{Palsberg:2007si} observe that many of the interference graphs
  4051. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  4052. that is, every cycle with four or more edges has an edge which is not
  4053. part of the cycle but which connects two vertices on the cycle. Such
  4054. graphs can be optimally colored by the greedy algorithm with a vertex
  4055. ordering determined by maximum cardinality search.
  4056. In situations where compile time is of utmost importance, such as in
  4057. just-in-time compilers, graph coloring algorithms can be too expensive
  4058. and the linear scan of \citet{Poletto:1999uq} may be more appropriate.
  4059. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4060. \chapter{Booleans and Control Flow}
  4061. \label{ch:Rif}
  4062. \index{Boolean}
  4063. \index{control flow}
  4064. \index{conditional expression}
  4065. The \LangInt{} and \LangVar{} languages only have a single kind of
  4066. value, integers. In this chapter we add a second kind of value, the
  4067. Booleans, to create the \LangIf{} language. The Boolean values
  4068. \emph{true} and \emph{false} are written \key{\#t} and \key{\#f}
  4069. respectively in Racket. The \LangIf{} language includes several
  4070. operations that involve Booleans (\key{and}, \key{not}, \key{eq?},
  4071. \key{<}, etc.) and the conditional \key{if} expression. With the
  4072. addition of \key{if}, programs can have non-trivial control flow which
  4073. impacts \code{explicate-control} and liveness analysis. Also, because
  4074. we now have two kinds of values, we need to handle programs that apply
  4075. an operation to the wrong kind of value, such as \code{(not 1)}.
  4076. There are two language design options for such situations. One option
  4077. is to signal an error and the other is to provide a wider
  4078. interpretation of the operation. The Racket language uses a mixture of
  4079. these two options, depending on the operation and the kind of
  4080. value. For example, the result of \code{(not 1)} in Racket is
  4081. \code{\#f} because Racket treats non-zero integers as if they were
  4082. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  4083. error in Racket because \code{car} expects a pair.
  4084. Typed Racket makes similar design choices as Racket, except much of
  4085. the error detection happens at compile time instead of run time. Typed
  4086. Racket accepts and runs \code{(not 1)}, producing \code{\#f}. But in
  4087. the case of \code{(car 1)}, Typed Racket reports a compile-time error
  4088. because Typed Racket expects the type of the argument to be of the
  4089. form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  4090. The \LangIf{} language performs type checking during compilation like
  4091. Typed Racket. In Chapter~\ref{ch:type-dynamic} we study the
  4092. alternative choice, that is, a dynamically typed language like Racket.
  4093. The \LangIf{} language is a subset of Typed Racket; for some
  4094. operations we are more restrictive, for example, rejecting
  4095. \code{(not 1)}.
  4096. This chapter is organized as follows. We begin by defining the syntax
  4097. and interpreter for the \LangIf{} language
  4098. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  4099. checking and build a type checker for \LangIf{}
  4100. (Section~\ref{sec:type-check-Rif}). To compile \LangIf{} we need to
  4101. enlarge the intermediate language \LangCVar{} into \LangCIf{}
  4102. (Section~\ref{sec:Cif}) and \LangXInt{} into \LangXIf{}
  4103. (Section~\ref{sec:x86-if}). The remaining sections of this chapter
  4104. discuss how our compiler passes change to accommodate Booleans and
  4105. conditional control flow. There is one new pass, named \code{shrink},
  4106. that translates some operators into others, thereby reducing the
  4107. number of operators that need to be handled in later passes. The
  4108. largest changes occur in \code{explicate-control}, to translate
  4109. \code{if} expressions into control-flow graphs
  4110. (Section~\ref{sec:explicate-control-Rif}). Regarding register
  4111. allocation, the liveness analysis now has multiple basic blocks to
  4112. process and there is the interesting question of how to handle
  4113. conditional jumps.
  4114. \section{The \LangIf{} Language}
  4115. \label{sec:lang-if}
  4116. The concrete syntax of the \LangIf{} language is defined in
  4117. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  4118. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  4119. \LangVar{} (shown in gray), the Boolean literals \code{\#t} and
  4120. \code{\#f}, and the conditional \code{if} expression. We expand the
  4121. operators to include
  4122. \begin{enumerate}
  4123. \item subtraction on integers,
  4124. \item the logical operators \key{and}, \key{or} and \key{not},
  4125. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  4126. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  4127. comparing integers.
  4128. \end{enumerate}
  4129. We reorganize the abstract syntax for the primitive operations in
  4130. Figure~\ref{fig:Rif-syntax}, using only one grammar rule for all of
  4131. them. This means that the grammar no longer checks whether the arity
  4132. of an operators matches the number of arguments. That responsibility
  4133. is moved to the type checker for \LangIf{}, which we introduce in
  4134. Section~\ref{sec:type-check-Rif}.
  4135. \begin{figure}[tp]
  4136. \centering
  4137. \fbox{
  4138. \begin{minipage}{0.96\textwidth}
  4139. \[
  4140. \begin{array}{lcl}
  4141. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4142. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4143. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  4144. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  4145. &\mid& \itm{bool}
  4146. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  4147. \mid (\key{not}\;\Exp) \\
  4148. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  4149. \LangIf{} &::=& \Exp
  4150. \end{array}
  4151. \]
  4152. \end{minipage}
  4153. }
  4154. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  4155. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  4156. \label{fig:Rif-concrete-syntax}
  4157. \end{figure}
  4158. \begin{figure}[tp]
  4159. \centering
  4160. \fbox{
  4161. \begin{minipage}{0.96\textwidth}
  4162. \[
  4163. \begin{array}{lcl}
  4164. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  4165. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  4166. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  4167. \mid \code{and} \mid \code{or} \mid \code{not} \\
  4168. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4169. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  4170. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4171. \LangIf{} &::=& \PROGRAM{\code{'()}}{\Exp}
  4172. \end{array}
  4173. \]
  4174. \end{minipage}
  4175. }
  4176. \caption{The abstract syntax of \LangIf{}.}
  4177. \label{fig:Rif-syntax}
  4178. \end{figure}
  4179. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  4180. which inherits from the interpreter for \LangVar{}
  4181. (Figure~\ref{fig:interp-Rvar}). The literals \code{\#t} and \code{\#f}
  4182. evaluate to the corresponding Boolean values. The conditional
  4183. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  4184. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  4185. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  4186. operations \code{not} and \code{and} behave as you might expect, but
  4187. note that the \code{and} operation is short-circuiting. That is, given
  4188. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  4189. evaluated if $e_1$ evaluates to \code{\#f}.
  4190. With the increase in the number of primitive operations, the
  4191. interpreter would become repetitive without some care. We refactor
  4192. the case for \code{Prim}, moving the code that differs with each
  4193. operation into the \code{interp-op} method shown in in
  4194. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  4195. separately because of its short-circuiting behavior.
  4196. \begin{figure}[tbp]
  4197. \begin{lstlisting}
  4198. (define interp-Rif-class
  4199. (class interp-Rvar-class
  4200. (super-new)
  4201. (define/public (interp-op op) ...)
  4202. (define/override ((interp-exp env) e)
  4203. (define recur (interp-exp env))
  4204. (match e
  4205. [(Bool b) b]
  4206. [(If cnd thn els)
  4207. (match (recur cnd)
  4208. [#t (recur thn)]
  4209. [#f (recur els)])]
  4210. [(Prim 'and (list e1 e2))
  4211. (match (recur e1)
  4212. [#t (match (recur e2) [#t #t] [#f #f])]
  4213. [#f #f])]
  4214. [(Prim op args)
  4215. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  4216. [else ((super interp-exp env) e)]))
  4217. ))
  4218. (define (interp-Rif p)
  4219. (send (new interp-Rif-class) interp-program p))
  4220. \end{lstlisting}
  4221. \caption{Interpreter for the \LangIf{} language. (See
  4222. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  4223. \label{fig:interp-Rif}
  4224. \end{figure}
  4225. \begin{figure}[tbp]
  4226. \begin{lstlisting}
  4227. (define/public (interp-op op)
  4228. (match op
  4229. ['+ fx+]
  4230. ['- fx-]
  4231. ['read read-fixnum]
  4232. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  4233. ['or (lambda (v1 v2)
  4234. (cond [(and (boolean? v1) (boolean? v2))
  4235. (or v1 v2)]))]
  4236. ['eq? (lambda (v1 v2)
  4237. (cond [(or (and (fixnum? v1) (fixnum? v2))
  4238. (and (boolean? v1) (boolean? v2))
  4239. (and (vector? v1) (vector? v2)))
  4240. (eq? v1 v2)]))]
  4241. ['< (lambda (v1 v2)
  4242. (cond [(and (fixnum? v1) (fixnum? v2))
  4243. (< v1 v2)]))]
  4244. ['<= (lambda (v1 v2)
  4245. (cond [(and (fixnum? v1) (fixnum? v2))
  4246. (<= v1 v2)]))]
  4247. ['> (lambda (v1 v2)
  4248. (cond [(and (fixnum? v1) (fixnum? v2))
  4249. (> v1 v2)]))]
  4250. ['>= (lambda (v1 v2)
  4251. (cond [(and (fixnum? v1) (fixnum? v2))
  4252. (>= v1 v2)]))]
  4253. [else (error 'interp-op "unknown operator")]))
  4254. \end{lstlisting}
  4255. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  4256. \label{fig:interp-op-Rif}
  4257. \end{figure}
  4258. \section{Type Checking \LangIf{} Programs}
  4259. \label{sec:type-check-Rif}
  4260. \index{type checking}
  4261. \index{semantic analysis}
  4262. It is helpful to think about type checking in two complementary
  4263. ways. A type checker predicts the type of value that will be produced
  4264. by each expression in the program. For \LangIf{}, we have just two types,
  4265. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4266. \begin{lstlisting}
  4267. (+ 10 (- (+ 12 20)))
  4268. \end{lstlisting}
  4269. produces an \key{Integer} while
  4270. \begin{lstlisting}
  4271. (and (not #f) #t)
  4272. \end{lstlisting}
  4273. produces a \key{Boolean}.
  4274. Another way to think about type checking is that it enforces a set of
  4275. rules about which operators can be applied to which kinds of
  4276. values. For example, our type checker for \LangIf{} signals an error
  4277. for the below expression
  4278. \begin{lstlisting}
  4279. (not (+ 10 (- (+ 12 20))))
  4280. \end{lstlisting}
  4281. The subexpression \code{(+ 10 (- (+ 12 20)))} has type \key{Integer}
  4282. but the type checker enforces the rule that the argument of \code{not}
  4283. must be a \key{Boolean}.
  4284. We implement type checking using classes and methods because they
  4285. provide the open recursion needed to reuse code as we extend the type
  4286. checker in later chapters, analogous to the use of classes and methods
  4287. for the interpreters (Section~\ref{sec:extensible-interp}).
  4288. We separate the type checker for the \LangVar{} fragment into its own
  4289. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  4290. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  4291. from the type checker for \LangVar{}. These type checkers are in the
  4292. files \code{type-check-Rvar.rkt} and \code{type-check-Rif.rkt} of the
  4293. support code.
  4294. %
  4295. Each type checker is a structurally recursive function over the AST.
  4296. Given an input expression \code{e}, the type checker either signals an
  4297. error or returns an expression and its type (\key{Integer} or
  4298. \key{Boolean}). It returns an expression because there are situations
  4299. in which we want to change or update the expression.
  4300. Next we discuss the \code{match} cases in \code{type-check-exp} of
  4301. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  4302. \code{Integer}. To handle variables, the type checker uses the
  4303. environment \code{env} to map variables to types. Consider the case
  4304. for \key{let}. We type check the initializing expression to obtain
  4305. its type \key{T} and then associate type \code{T} with the variable
  4306. \code{x} in the environment used to type check the body of the
  4307. \key{let}. Thus, when the type checker encounters a use of variable
  4308. \code{x}, it can find its type in the environment. Regarding
  4309. primitive operators, we recursively analyze the arguments and then
  4310. invoke \code{type-check-op} to check whether the argument types are
  4311. allowed.
  4312. Several auxiliary methods are used in the type checker. The method
  4313. \code{operator-types} defines a dictionary that maps the operator
  4314. names to their parameter and return types. The \code{type-equal?}
  4315. method determines whether two types are equal, which for now simply
  4316. dispatches to \code{equal?} (deep equality). The
  4317. \code{check-type-equal?} method triggers an error if the two types are
  4318. not equal. The \code{type-check-op} method looks up the operator in
  4319. the \code{operator-types} dictionary and then checks whether the
  4320. argument types are equal to the parameter types. The result is the
  4321. return type of the operator.
  4322. \begin{figure}[tbp]
  4323. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4324. (define type-check-Rvar-class
  4325. (class object%
  4326. (super-new)
  4327. (define/public (operator-types)
  4328. '((+ . ((Integer Integer) . Integer))
  4329. (- . ((Integer) . Integer))
  4330. (read . (() . Integer))))
  4331. (define/public (type-equal? t1 t2) (equal? t1 t2))
  4332. (define/public (check-type-equal? t1 t2 e)
  4333. (unless (type-equal? t1 t2)
  4334. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  4335. (define/public (type-check-op op arg-types e)
  4336. (match (dict-ref (operator-types) op)
  4337. [`(,param-types . ,return-type)
  4338. (for ([at arg-types] [pt param-types])
  4339. (check-type-equal? at pt e))
  4340. return-type]
  4341. [else (error 'type-check-op "unrecognized ~a" op)]))
  4342. (define/public (type-check-exp env)
  4343. (lambda (e)
  4344. (match e
  4345. [(Int n) (values (Int n) 'Integer)]
  4346. [(Var x) (values (Var x) (dict-ref env x))]
  4347. [(Let x e body)
  4348. (define-values (e^ Te) ((type-check-exp env) e))
  4349. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  4350. (values (Let x e^ b) Tb)]
  4351. [(Prim op es)
  4352. (define-values (new-es ts)
  4353. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  4354. (values (Prim op new-es) (type-check-op op ts e))]
  4355. [else (error 'type-check-exp "couldn't match" e)])))
  4356. (define/public (type-check-program e)
  4357. (match e
  4358. [(Program info body)
  4359. (define-values (body^ Tb) ((type-check-exp '()) body))
  4360. (check-type-equal? Tb 'Integer body)
  4361. (Program info body^)]
  4362. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  4363. ))
  4364. (define (type-check-Rvar p)
  4365. (send (new type-check-Rvar-class) type-check-program p))
  4366. \end{lstlisting}
  4367. \caption{Type checker for the \LangVar{} language.}
  4368. \label{fig:type-check-Rvar}
  4369. \end{figure}
  4370. \begin{figure}[tbp]
  4371. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4372. (define type-check-Rif-class
  4373. (class type-check-Rvar-class
  4374. (super-new)
  4375. (inherit check-type-equal?)
  4376. (define/override (operator-types)
  4377. (append '((- . ((Integer Integer) . Integer))
  4378. (and . ((Boolean Boolean) . Boolean))
  4379. (or . ((Boolean Boolean) . Boolean))
  4380. (< . ((Integer Integer) . Boolean))
  4381. (<= . ((Integer Integer) . Boolean))
  4382. (> . ((Integer Integer) . Boolean))
  4383. (>= . ((Integer Integer) . Boolean))
  4384. (not . ((Boolean) . Boolean))
  4385. )
  4386. (super operator-types)))
  4387. (define/override (type-check-exp env)
  4388. (lambda (e)
  4389. (match e
  4390. [(Prim 'eq? (list e1 e2))
  4391. (define-values (e1^ T1) ((type-check-exp env) e1))
  4392. (define-values (e2^ T2) ((type-check-exp env) e2))
  4393. (check-type-equal? T1 T2 e)
  4394. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  4395. [(Bool b) (values (Bool b) 'Boolean)]
  4396. [(If cnd thn els)
  4397. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  4398. (define-values (thn^ Tt) ((type-check-exp env) thn))
  4399. (define-values (els^ Te) ((type-check-exp env) els))
  4400. (check-type-equal? Tc 'Boolean e)
  4401. (check-type-equal? Tt Te e)
  4402. (values (If cnd^ thn^ els^) Te)]
  4403. [else ((super type-check-exp env) e)])))
  4404. ))
  4405. (define (type-check-Rif p)
  4406. (send (new type-check-Rif-class) type-check-program p))
  4407. \end{lstlisting}
  4408. \caption{Type checker for the \LangIf{} language.}
  4409. \label{fig:type-check-Rif}
  4410. \end{figure}
  4411. Next we discuss the type checker for \LangIf{} in
  4412. Figure~\ref{fig:type-check-Rif}. The operator \code{eq?} requires the
  4413. two arguments to have the same type. The type of a Boolean constant is
  4414. \code{Boolean}. The condition of an \code{if} must be of
  4415. \code{Boolean} type and the two branches must have the same type. The
  4416. \code{operator-types} function adds dictionary entries for the other
  4417. new operators.
  4418. \begin{exercise}\normalfont
  4419. Create 10 new test programs in \LangIf{}. Half of the programs should
  4420. have a type error. For those programs, create an empty file with the
  4421. same base name but with file extension \code{.tyerr}. For example, if
  4422. the test \code{cond\_test\_14.rkt} is expected to error, then create
  4423. an empty file named \code{cond\_test\_14.tyerr}. This indicates to
  4424. \code{interp-tests} and \code{compiler-tests} that a type error is
  4425. expected. The other half of the test programs should not have type
  4426. errors.
  4427. In the \code{run-tests.rkt} script, change the second argument of
  4428. \code{interp-tests} and \code{compiler-tests} to
  4429. \code{type-check-Rif}, which causes the type checker to run prior to
  4430. the compiler passes. Temporarily change the \code{passes} to an empty
  4431. list and run the script, thereby checking that the new test programs
  4432. either type check or not as intended.
  4433. \end{exercise}
  4434. \section{The \LangCIf{} Intermediate Language}
  4435. \label{sec:Cif}
  4436. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  4437. \LangCIf{} intermediate language. (The concrete syntax is in the
  4438. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  4439. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  4440. operators to the \Exp{} non-terminal and the literals \key{\#t} and
  4441. \key{\#f} to the \Arg{} non-terminal.
  4442. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  4443. statements to the \Tail{} non-terminal. The condition of an \code{if}
  4444. statement is a comparison operation and the branches are \code{goto}
  4445. statements, making it straightforward to compile \code{if} statements
  4446. to x86.
  4447. \begin{figure}[tp]
  4448. \fbox{
  4449. \begin{minipage}{0.96\textwidth}
  4450. \small
  4451. \[
  4452. \begin{array}{lcl}
  4453. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4454. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4455. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4456. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4457. &\mid& \UNIOP{\key{'not}}{\Atm}
  4458. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4459. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4460. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4461. \mid \GOTO{\itm{label}} \\
  4462. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4463. \LangCIf{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  4464. \end{array}
  4465. \]
  4466. \end{minipage}
  4467. }
  4468. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  4469. (Figure~\ref{fig:c0-syntax}).}
  4470. \label{fig:c1-syntax}
  4471. \end{figure}
  4472. \section{The \LangXIf{} Language}
  4473. \label{sec:x86-if}
  4474. \index{x86} To implement the new logical operations, the comparison
  4475. operations, and the \key{if} expression, we need to delve further into
  4476. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  4477. define the concrete and abstract syntax for the \LangXIf{} subset
  4478. of x86, which includes instructions for logical operations,
  4479. comparisons, and conditional jumps.
  4480. One challenge is that x86 does not provide an instruction that
  4481. directly implements logical negation (\code{not} in \LangIf{} and
  4482. \LangCIf{}). However, the \code{xorq} instruction can be used to
  4483. encode \code{not}. The \key{xorq} instruction takes two arguments,
  4484. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  4485. bit of its arguments, and writes the results into its second argument.
  4486. Recall the truth table for exclusive-or:
  4487. \begin{center}
  4488. \begin{tabular}{l|cc}
  4489. & 0 & 1 \\ \hline
  4490. 0 & 0 & 1 \\
  4491. 1 & 1 & 0
  4492. \end{tabular}
  4493. \end{center}
  4494. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  4495. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  4496. for the bit $1$, the result is the opposite of the second bit. Thus,
  4497. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  4498. the first argument:
  4499. \[
  4500. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  4501. \qquad\Rightarrow\qquad
  4502. \begin{array}{l}
  4503. \key{movq}~ \Arg\key{,} \Var\\
  4504. \key{xorq}~ \key{\$1,} \Var
  4505. \end{array}
  4506. \]
  4507. \begin{figure}[tp]
  4508. \fbox{
  4509. \begin{minipage}{0.96\textwidth}
  4510. \[
  4511. \begin{array}{lcl}
  4512. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4513. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4514. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  4515. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4516. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  4517. \key{subq} \; \Arg\key{,} \Arg \mid
  4518. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  4519. && \gray{ \key{callq} \; \itm{label} \mid
  4520. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  4521. && \gray{ \itm{label}\key{:}\; \Instr }
  4522. \mid \key{xorq}~\Arg\key{,}~\Arg
  4523. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  4524. && \key{set}cc~\Arg
  4525. \mid \key{movzbq}~\Arg\key{,}~\Arg
  4526. \mid \key{j}cc~\itm{label}
  4527. \\
  4528. \LangXIf{} &::= & \gray{ \key{.globl main} }\\
  4529. & & \gray{ \key{main:} \; \Instr\ldots }
  4530. \end{array}
  4531. \]
  4532. \end{minipage}
  4533. }
  4534. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  4535. \label{fig:x86-1-concrete}
  4536. \end{figure}
  4537. \begin{figure}[tp]
  4538. \fbox{
  4539. \begin{minipage}{0.98\textwidth}
  4540. \small
  4541. \[
  4542. \begin{array}{lcl}
  4543. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4544. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4545. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4546. \mid \BYTEREG{\itm{bytereg}} \\
  4547. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4548. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  4549. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  4550. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4551. \mid \UNIINSTR{\code{negq}}{\Arg} } \\
  4552. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4553. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4554. &\mid& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  4555. \mid \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  4556. &\mid& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  4557. \mid \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  4558. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4559. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  4560. \LangXIf{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  4561. \end{array}
  4562. \]
  4563. \end{minipage}
  4564. }
  4565. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  4566. \label{fig:x86-1}
  4567. \end{figure}
  4568. Next we consider the x86 instructions that are relevant for compiling
  4569. the comparison operations. The \key{cmpq} instruction compares its two
  4570. arguments to determine whether one argument is less than, equal, or
  4571. greater than the other argument. The \key{cmpq} instruction is unusual
  4572. regarding the order of its arguments and where the result is
  4573. placed. The argument order is backwards: if you want to test whether
  4574. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4575. \key{cmpq} is placed in the special EFLAGS register. This register
  4576. cannot be accessed directly but it can be queried by a number of
  4577. instructions, including the \key{set} instruction. The instruction
  4578. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  4579. depending on whether the comparison comes out according to the
  4580. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  4581. for less-or-equal, \key{g} for greater, \key{ge} for
  4582. greater-or-equal). The \key{set} instruction has an annoying quirk in
  4583. that its destination argument must be single byte register, such as
  4584. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  4585. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  4586. instruction can be used to move from a single byte register to a
  4587. normal 64-bit register. The abstract syntax for the \code{set}
  4588. instruction differs from the concrete syntax in that it separates the
  4589. instruction name from the condition code.
  4590. The x86 instruction for conditional jump is relevant to the
  4591. compilation of \key{if} expressions. The instruction
  4592. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  4593. the instruction after \itm{label} depending on whether the result in
  4594. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  4595. jump instruction falls through to the next instruction. Like the
  4596. abstract syntax for \code{set}, the abstract syntax for conditional
  4597. jump separates the instruction name from the condition code. For
  4598. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4599. the conditional jump instruction relies on the EFLAGS register, it is
  4600. common for it to be immediately preceded by a \key{cmpq} instruction
  4601. to set the EFLAGS register.
  4602. \section{Shrink the \LangIf{} Language}
  4603. \label{sec:shrink-Rif}
  4604. The \LangIf{} language includes several operators that are easily
  4605. expressible with other operators. For example, subtraction is
  4606. expressible using addition and negation.
  4607. \[
  4608. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  4609. \]
  4610. Several of the comparison operations are expressible using less-than
  4611. and logical negation.
  4612. \[
  4613. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  4614. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  4615. \]
  4616. The \key{let} is needed in the above translation to ensure that
  4617. expression $e_1$ is evaluated before $e_2$.
  4618. By performing these translations in the front-end of the compiler, the
  4619. later passes of the compiler do not need to deal with these operators,
  4620. making the passes shorter.
  4621. %% On the other hand, sometimes
  4622. %% these translations make it more difficult to generate the most
  4623. %% efficient code with respect to the number of instructions. However,
  4624. %% these differences typically do not affect the number of accesses to
  4625. %% memory, which is the primary factor that determines execution time on
  4626. %% modern computer architectures.
  4627. \begin{exercise}\normalfont
  4628. Implement the pass \code{shrink} to remove subtraction, \key{and},
  4629. \key{or}, \key{<=}, \key{>}, and \key{>=} from the language by
  4630. translating them to other constructs in \LangIf{}.
  4631. %
  4632. Create six test programs that involve these operators.
  4633. %
  4634. In the \code{run-tests.rkt} script, add the following entry for
  4635. \code{shrink} to the list of passes (it should be the only pass at
  4636. this point).
  4637. \begin{lstlisting}
  4638. (list "shrink" shrink interp-Rif type-check-Rif)
  4639. \end{lstlisting}
  4640. This instructs \code{interp-tests} to run the intepreter
  4641. \code{interp-Rif} and the type checker \code{type-check-Rif} on the
  4642. output of \code{shrink}.
  4643. %
  4644. Run the script to test your compiler on all the test programs.
  4645. \end{exercise}
  4646. \section{Uniquify Variables}
  4647. \label{sec:uniquify-Rif}
  4648. Add cases to \code{uniquify-exp} to handle Boolean constants and
  4649. \code{if} expressions.
  4650. \begin{exercise}\normalfont
  4651. Update the \code{uniquify-exp} for \LangIf{} and add the following
  4652. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  4653. \begin{lstlisting}
  4654. (list "uniquify" uniquify interp-Rif type-check-Rif)
  4655. \end{lstlisting}
  4656. Run the script to test your compiler.
  4657. \end{exercise}
  4658. \section{Remove Complex Operands}
  4659. \label{sec:remove-complex-opera-Rif}
  4660. The output language for this pass is \LangIfANF{}
  4661. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  4662. \LangIf{}. The \code{Bool} form is an atomic expressions but
  4663. \code{If} is not. All three sub-expressions of an \code{If} are
  4664. allowed to be complex expressions but the operands of \code{not} and
  4665. the comparisons must be atoms.
  4666. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4667. \code{rco-atom} functions according to whether the output needs to be
  4668. \Exp{} or \Atm{} as specified in the grammar for \LangIfANF{}.
  4669. Regarding \code{If}, it is particularly important to \textbf{not}
  4670. replace its condition with a temporary variable because that would
  4671. interfere with the generation of high-quality output in the
  4672. \code{explicate-control} pass.
  4673. \begin{figure}[tp]
  4674. \centering
  4675. \fbox{
  4676. \begin{minipage}{0.96\textwidth}
  4677. \[
  4678. \begin{array}{rcl}
  4679. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4680. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4681. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4682. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4683. &\mid& \UNIOP{\key{not}}{\Atm} \\
  4684. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4685. R^{\dagger}_2 &::=& \PROGRAM{\code{()}}{\Exp}
  4686. \end{array}
  4687. \]
  4688. \end{minipage}
  4689. }
  4690. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  4691. \label{fig:Rif-anf-syntax}
  4692. \end{figure}
  4693. \begin{exercise}\normalfont
  4694. %
  4695. Add cases for Boolean constants and \code{if} to the \code{rco-atom}
  4696. and \code{rco-exp} functions in \code{compiler.rkt}.
  4697. %
  4698. Create three new \LangInt{} programs that exercise the interesting
  4699. code in this pass.
  4700. %
  4701. In the \code{run-tests.rkt} script, add the following entry to the
  4702. list of \code{passes} and then run the script to test your compiler.
  4703. \begin{lstlisting}
  4704. (list "remove-complex" remove-complex-opera* interp-Rif type-check-Rif)
  4705. \end{lstlisting}
  4706. \end{exercise}
  4707. \section{Explicate Control}
  4708. \label{sec:explicate-control-Rif}
  4709. Recall that the purpose of \code{explicate-control} is to make the
  4710. order of evaluation explicit in the syntax of the program. With the
  4711. addition of \key{if} this get more interesting.
  4712. As a motivating example, consider the following program that has an
  4713. \key{if} expression nested in the predicate of another \key{if}.
  4714. % cond_test_41.rkt
  4715. \begin{center}
  4716. \begin{minipage}{0.96\textwidth}
  4717. \begin{lstlisting}
  4718. (let ([x (read)])
  4719. (let ([y (read)])
  4720. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4721. (+ y 2)
  4722. (+ y 10))))
  4723. \end{lstlisting}
  4724. \end{minipage}
  4725. \end{center}
  4726. %
  4727. The naive way to compile \key{if} and the comparison would be to
  4728. handle each of them in isolation, regardless of their context. Each
  4729. comparison would be translated into a \key{cmpq} instruction followed
  4730. by a couple instructions to move the result from the EFLAGS register
  4731. into a general purpose register or stack location. Each \key{if} would
  4732. be translated into a \key{cmpq} instruction followed by a conditional
  4733. jump. The generated code for the inner \key{if} in the above example
  4734. would be as follows.
  4735. \begin{center}
  4736. \begin{minipage}{0.96\textwidth}
  4737. \begin{lstlisting}
  4738. ...
  4739. cmpq $1, x ;; (< x 1)
  4740. setl %al
  4741. movzbq %al, tmp
  4742. cmpq $1, tmp ;; (if ...)
  4743. je then_branch_1
  4744. jmp else_branch_1
  4745. ...
  4746. \end{lstlisting}
  4747. \end{minipage}
  4748. \end{center}
  4749. However, if we take context into account we can do better and reduce
  4750. the use of \key{cmpq} instructions for accessing the EFLAG register.
  4751. Our goal will be compile \key{if} expressions so that the relevant
  4752. comparison instruction appears directly before the conditional jump.
  4753. For example, we want to generate the following code for the inner
  4754. \code{if}.
  4755. \begin{center}
  4756. \begin{minipage}{0.96\textwidth}
  4757. \begin{lstlisting}
  4758. ...
  4759. cmpq $1, x
  4760. je then_branch_1
  4761. jmp else_branch_1
  4762. ...
  4763. \end{lstlisting}
  4764. \end{minipage}
  4765. \end{center}
  4766. One way to achieve this is to reorganize the code at the level of
  4767. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  4768. the following code.
  4769. \begin{center}
  4770. \begin{minipage}{0.96\textwidth}
  4771. \begin{lstlisting}
  4772. (let ([x (read)])
  4773. (let ([y (read)])
  4774. (if (< x 1)
  4775. (if (eq? x 0)
  4776. (+ y 2)
  4777. (+ y 10))
  4778. (if (eq? x 2)
  4779. (+ y 2)
  4780. (+ y 10)))))
  4781. \end{lstlisting}
  4782. \end{minipage}
  4783. \end{center}
  4784. Unfortunately, this approach duplicates the two branches from the
  4785. outer \code{if} and a compiler must never duplicate code!
  4786. We need a way to perform the above transformation but without
  4787. duplicating code. That is, we need a way for different parts of a
  4788. program to refer to the same piece of code. At the level of x86
  4789. assembly this is straightforward because we can label the code for
  4790. each branch and insert jumps in all the places that need to execute
  4791. the branch. In our intermediate language, we need to move away from
  4792. abstract syntax \emph{trees} and instead use \emph{graphs}. In
  4793. particular, we use a standard program representation called a
  4794. \emph{control flow graph} (CFG), due to Frances Elizabeth
  4795. \citet{Allen:1970uq}. \index{control-flow graph} Each vertex is a
  4796. labeled sequence of code, called a \emph{basic block}, and each edge
  4797. represents a jump to another block. The \key{CProgram} construct of
  4798. \LangCVar{} and \LangCIf{} contains a control flow graph represented
  4799. as an alist mapping labels to basic blocks. Each basic block is
  4800. represented by the $\Tail$ non-terminal.
  4801. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4802. \code{remove-complex-opera*} pass and then the
  4803. \code{explicate-control} pass on the example program. We walk through
  4804. the output program and then discuss the algorithm.
  4805. %
  4806. Following the order of evaluation in the output of
  4807. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4808. and then the comparison \lstinline{(< x 1)} in the predicate of the
  4809. inner \key{if}. In the output of \code{explicate-control}, in the
  4810. block labeled \code{start}, is two assignment statements followed by a
  4811. \code{if} statement that branches to \code{block40} or
  4812. \code{block41}. The blocks associated with those labels contain the
  4813. translations of the code \lstinline{(eq? x 0)} and \lstinline{(eq? x 2)},
  4814. respectively. In particular, we start \code{block40} with the
  4815. comparison \lstinline{(eq? x 0)} and then branch to \code{block38} or
  4816. \code{block39}, the two branches of the outer \key{if}, i.e.,
  4817. \lstinline{(+ y 2)} and \lstinline{(+ y 10)}. The story for
  4818. \code{block41} is similar.
  4819. \begin{figure}[tbp]
  4820. \begin{tabular}{lll}
  4821. \begin{minipage}{0.4\textwidth}
  4822. % cond_test_41.rkt
  4823. \begin{lstlisting}
  4824. (let ([x (read)])
  4825. (let ([y (read)])
  4826. (if (if (< x 1)
  4827. (eq? x 0)
  4828. (eq? x 2))
  4829. (+ y 2)
  4830. (+ y 10))))
  4831. \end{lstlisting}
  4832. \hspace{40pt}$\Downarrow$
  4833. \begin{lstlisting}
  4834. (let ([x (read)])
  4835. (let ([y (read)])
  4836. (if (if (< x 1)
  4837. (eq? x 0)
  4838. (eq? x 2))
  4839. (+ y 2)
  4840. (+ y 10))))
  4841. \end{lstlisting}
  4842. \end{minipage}
  4843. &
  4844. $\Rightarrow$
  4845. &
  4846. \begin{minipage}{0.55\textwidth}
  4847. \begin{lstlisting}
  4848. start:
  4849. x = (read);
  4850. y = (read);
  4851. if (< x 1) goto block40;
  4852. else goto block41;
  4853. block40:
  4854. if (eq? x 0) goto block38;
  4855. else goto block39;
  4856. block41:
  4857. if (eq? x 2) goto block38;
  4858. else goto block39;
  4859. block38:
  4860. return (+ y 2);
  4861. block39:
  4862. return (+ y 10);
  4863. \end{lstlisting}
  4864. \end{minipage}
  4865. \end{tabular}
  4866. \caption{Translation from \LangIf{} to \LangCIf{}
  4867. via the \code{explicate-control}.}
  4868. \label{fig:explicate-control-s1-38}
  4869. \end{figure}
  4870. %% The nice thing about the output of \code{explicate-control} is that
  4871. %% there are no unnecessary comparisons and every comparison is part of a
  4872. %% conditional jump.
  4873. %% The down-side of this output is that it includes
  4874. %% trivial blocks, such as the blocks labeled \code{block92} through
  4875. %% \code{block95}, that only jump to another block. We discuss a solution
  4876. %% to this problem in Section~\ref{sec:opt-jumps}.
  4877. Recall that in Section~\ref{sec:explicate-control-Rvar} we implement
  4878. \code{explicate-control} for \LangVar{} using two mutually recursive
  4879. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4880. former function translates expressions in tail position whereas the
  4881. later function translates expressions on the right-hand-side of a
  4882. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  4883. have a new kind of position to deal with: the predicate position of
  4884. the \key{if}. We need another function, \code{explicate-pred}, that
  4885. takes an \LangIf{} expression and two blocks for the then-branch and
  4886. else-branch. The output of \code{explicate-pred} is a block.
  4887. %
  4888. In the following paragraphs we discuss specific cases in the
  4889. \code{explicate-pred} function as well as additions to the
  4890. \code{explicate-tail} and \code{explicate-assign} functions.
  4891. \begin{figure}[tbp]
  4892. \begin{lstlisting}
  4893. (define (explicate-pred cnd thn els)
  4894. (match cnd
  4895. [(Var x) ___]
  4896. [(Let x rhs body) ___]
  4897. [(Prim 'not (list e)) ___]
  4898. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  4899. (IfStmt (Prim op arg*) (force (block->goto thn))
  4900. (force (block->goto els)))]
  4901. [(Bool b) (if b thn els)]
  4902. [(If cnd^ thn^ els^) ___]
  4903. [else (error "explicate-pred unhandled case" cnd)]))
  4904. \end{lstlisting}
  4905. \caption{Skeleton for the \key{explicate-pred} auxiliary function.}
  4906. \label{fig:explicate-pred}
  4907. \end{figure}
  4908. The skeleton for the \code{explicate-pred} function is given in
  4909. Figure~\ref{fig:explicate-pred}. It has a case for every expression
  4910. that can have type \code{Boolean}. We detail a few cases here and
  4911. leave the rest for the reader. The input to this function is an
  4912. expression and two blocks, \code{thn} and \code{els}, for the two
  4913. branches of the enclosing \key{if}.
  4914. %
  4915. Consider the case for Boolean constants in
  4916. Figure~\ref{fig:explicate-pred}. We perform a kind of partial
  4917. evaluation\index{partial evaluation} and output either the \code{thn}
  4918. or \code{els} branch depending on whether the constant is true or
  4919. false. This case demonstrates that we sometimes discard the \code{thn}
  4920. or \code{els} blocks that are input to \code{explicate-pred}.
  4921. The case for \key{if} in \code{explicate-pred} is particularly
  4922. illuminating because it deals with the challenges we discussed above
  4923. regarding nested \key{if} expressions
  4924. (Figure~\ref{fig:explicate-control-s1-38}). The \lstinline{thn^} and
  4925. \lstinline{els^} branches of the \key{if} inherit their context from
  4926. the current one, that is, predicate context. So you should recursively
  4927. apply \code{explicate-pred} to the \lstinline{thn^} and
  4928. \lstinline{els^} branches. For both of those recursive calls, pass
  4929. \code{thn} and \code{els} as the extra parameters. Thus, \code{thn}
  4930. and \code{els} may get used twice, once inside each recursive call. As
  4931. discussed above, to avoid duplicating code, we need to add them to the
  4932. control-flow graph so that we can instead refer to them by name and
  4933. execute them with a \key{goto}. However, as we saw in the cases above
  4934. for Boolean constants, the blocks \code{thn} and \code{els} may not
  4935. get used at all and we don't want to prematurely add them to the
  4936. control-flow graph if they end up being discarded.
  4937. The solution to this conundrum is to use \emph{lazy
  4938. evaluation}\index{lazy evaluation}\citep{Friedman:1976aa} to delay
  4939. adding the blocks to the control-flow graph until the points where we
  4940. know they will be used. Racket provides support for lazy evaluation
  4941. with the
  4942. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  4943. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  4944. \index{delay} creates a \emph{promise}\index{promise} in which the
  4945. evaluation of the expressions is postponed. When \key{(force}
  4946. $p$\key{)}\index{force} is applied to a promise $p$ for the first
  4947. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  4948. $e_n$ is cached in the promise and returned. If \code{force} is
  4949. applied again to the same promise, then the cached result is returned.
  4950. If \code{force} is applied to an argument that is not a promise,
  4951. \code{force} simply returns the argument.
  4952. We use lazy evaluation for the input and output blocks of the
  4953. functions \code{explicate-pred} and \code{explicate-assign} and for
  4954. the output block of \code{explicate-tail}. So instead of taking and
  4955. returning blocks, they take and return promises. Furthermore, when we
  4956. come to a situation in which we a block might be used more than once,
  4957. as in the case for \code{if} in \code{explicate-pred}, we transform
  4958. the promise into a new promise that will add the block to the
  4959. control-flow graph and return a \code{goto}. The following auxiliary
  4960. function named \code{block->goto} accomplishes this task. It begins
  4961. with \code{delay} to create a promise. When forced, this promise will
  4962. force the original promise. If that returns a \code{goto} (because the
  4963. block was already added to the control-flow graph), then we return the
  4964. \code{goto}. Otherwise we add the block to the control-flow graph with
  4965. another auxiliary function named \code{add-node}. That function
  4966. returns the label for the new block, which we use to create a
  4967. \code{goto}.
  4968. \begin{lstlisting}
  4969. (define (block->goto block)
  4970. (delay
  4971. (define b (force block))
  4972. (match b
  4973. [(Goto label) (Goto label)]
  4974. [else (Goto (add-node b))])))
  4975. \end{lstlisting}
  4976. Returning to the discussion of \code{explicate-pred}
  4977. (Figure~\ref{fig:explicate-pred}), consider the case for comparison
  4978. operators. This is one of the base cases of the recursive function so
  4979. we translate the comparison to an \code{if} statement. We apply
  4980. \code{block->goto} to \code{thn} and \code{els} to obtain two promises
  4981. that will add then to the control-flow graph, which we can immediately
  4982. \code{force} to obtain the two goto's that form the branches of the
  4983. \code{if} statement.
  4984. %% Getting back to the case for \code{if} in \code{explicate-pred}, we
  4985. %% make the recursive calls to \code{explicate-pred} on the ``then'' and
  4986. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  4987. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  4988. %% results from the two recursive calls. We complete the case for
  4989. %% \code{if} by recursively apply \code{explicate-pred} to the condition
  4990. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  4991. %% the result $B_5$.
  4992. %% \[
  4993. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4994. %% \quad\Rightarrow\quad
  4995. %% B_5
  4996. %% \]
  4997. The \code{explicate-tail} and \code{explicate-assign} functions need
  4998. additional cases for Boolean constants and \key{if}.
  4999. %
  5000. In the cases for \code{if}, the two branches inherit the current
  5001. context, so in \code{explicate-tail} they are in tail position and in
  5002. \code{explicate-assign} they are in assignment position. The
  5003. \code{cont} parameter of \code{explicate-assign} is used in both
  5004. recursive calls, so make sure to use \code{block->goto} on it.
  5005. %% In the case for \code{if} in \code{explicate-tail}, the two branches
  5006. %% inherit the current context, so they are in tail position. Thus, the
  5007. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  5008. %% \code{explicate-tail}.
  5009. %% %
  5010. %% We need to pass $B_0$ as the accumulator argument for both of these
  5011. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  5012. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  5013. %% to the control-flow graph and obtain a promised goto $G_0$.
  5014. %% %
  5015. %% Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  5016. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  5017. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  5018. %% \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  5019. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  5020. %% \[
  5021. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  5022. %% \]
  5023. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  5024. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  5025. %% should not be confused with the labels for the blocks that appear in
  5026. %% the generated code. We initially construct unlabeled blocks; we only
  5027. %% attach labels to blocks when we add them to the control-flow graph, as
  5028. %% we see in the next case.
  5029. %% Next consider the case for \key{if} in the \code{explicate-assign}
  5030. %% function. The context of the \key{if} is an assignment to some
  5031. %% variable $x$ and then the control continues to some promised block
  5032. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  5033. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  5034. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  5035. %% branches of the \key{if} inherit the current context, so they are in
  5036. %% assignment positions. Let $B_2$ be the result of applying
  5037. %% \code{explicate-assign} to the ``then'' branch, variable $x$, and
  5038. %% $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  5039. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  5040. %% the result of applying \code{explicate-pred} to the predicate
  5041. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  5042. %% translates to the promise $B_4$.
  5043. %% \[
  5044. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  5045. %% \]
  5046. %% This completes the description of \code{explicate-control} for \LangIf{}.
  5047. The way in which the \code{shrink} pass transforms logical operations
  5048. such as \code{and} and \code{or} can impact the quality of code
  5049. generated by \code{explicate-control}. For example, consider the
  5050. following program.
  5051. % cond_test_21.rkt
  5052. \begin{lstlisting}
  5053. (if (and (eq? (read) 0) (eq? (read) 1))
  5054. 0
  5055. 42)
  5056. \end{lstlisting}
  5057. The \code{and} operation should transform into something that the
  5058. \code{explicate-pred} function can still analyze and descend through to
  5059. reach the underlying \code{eq?} conditions. Ideally, your
  5060. \code{explicate-control} pass should generate code similar to the
  5061. following for the above program.
  5062. \begin{center}
  5063. \begin{lstlisting}
  5064. start:
  5065. tmp1 = (read);
  5066. if (eq? tmp1 0) goto block40;
  5067. else goto block39;
  5068. block40:
  5069. tmp2 = (read);
  5070. if (eq? tmp2 1) goto block38;
  5071. else goto block39;
  5072. block38:
  5073. return 0;
  5074. block39:
  5075. return 42;
  5076. \end{lstlisting}
  5077. \end{center}
  5078. \begin{exercise}\normalfont
  5079. Implement the pass \code{explicate-control} by adding the cases for
  5080. Boolean constants and \key{if} to the \code{explicate-tail} and
  5081. \code{explicate-assign}. Implement the auxiliary function
  5082. \code{explicate-pred} for predicate contexts.
  5083. %
  5084. Create test cases that exercise all of the new cases in the code for
  5085. this pass.
  5086. %
  5087. Add the following entry to the list of \code{passes} in
  5088. \code{run-tests.rkt} and then run this script to test your compiler.
  5089. \begin{lstlisting}
  5090. (list "explicate-control" explicate-control interp-Cif type-check-Cif)
  5091. \end{lstlisting}
  5092. \end{exercise}
  5093. \section{Select Instructions}
  5094. \label{sec:select-Rif}
  5095. \index{instruction selection}
  5096. The \code{select-instructions} pass translate \LangCIf{} to
  5097. \LangXIfVar{}. Recall that we implement this pass using three
  5098. auxiliary functions, one for each of the non-terminals $\Atm$,
  5099. $\Stmt$, and $\Tail$.
  5100. For $\Atm$, we have new cases for the Booleans. We take the usual
  5101. approach of encoding them as integers, with true as 1 and false as 0.
  5102. \[
  5103. \key{\#t} \Rightarrow \key{1}
  5104. \qquad
  5105. \key{\#f} \Rightarrow \key{0}
  5106. \]
  5107. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  5108. be implemented in terms of \code{xorq} as we discussed at the
  5109. beginning of this section. Given an assignment
  5110. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  5111. if the left-hand side $\itm{var}$ is
  5112. the same as $\Atm$, then just the \code{xorq} suffices.
  5113. \[
  5114. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  5115. \quad\Rightarrow\quad
  5116. \key{xorq}~\key{\$}1\key{,}~\Var
  5117. \]
  5118. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  5119. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  5120. x86. Then we have
  5121. \[
  5122. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  5123. \quad\Rightarrow\quad
  5124. \begin{array}{l}
  5125. \key{movq}~\Arg\key{,}~\Var\\
  5126. \key{xorq}~\key{\$}1\key{,}~\Var
  5127. \end{array}
  5128. \]
  5129. Next consider the cases for \code{eq?} and less-than comparison.
  5130. Translating these operations to x86 is slightly involved due to the
  5131. unusual nature of the \key{cmpq} instruction discussed above. We
  5132. recommend translating an assignment from \code{eq?} into the following
  5133. sequence of three instructions. \\
  5134. \begin{tabular}{lll}
  5135. \begin{minipage}{0.4\textwidth}
  5136. \begin{lstlisting}
  5137. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  5138. \end{lstlisting}
  5139. \end{minipage}
  5140. &
  5141. $\Rightarrow$
  5142. &
  5143. \begin{minipage}{0.4\textwidth}
  5144. \begin{lstlisting}
  5145. cmpq |$\Arg_2$|, |$\Arg_1$|
  5146. sete %al
  5147. movzbq %al, |$\Var$|
  5148. \end{lstlisting}
  5149. \end{minipage}
  5150. \end{tabular} \\
  5151. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  5152. and \key{if} statements. Both are straightforward to translate to
  5153. x86. A \key{goto} becomes a jump instruction.
  5154. \[
  5155. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  5156. \]
  5157. An \key{if} statement becomes a compare instruction followed by a
  5158. conditional jump (for the ``then'' branch) and the fall-through is to
  5159. a regular jump (for the ``else'' branch).\\
  5160. \begin{tabular}{lll}
  5161. \begin{minipage}{0.4\textwidth}
  5162. \begin{lstlisting}
  5163. if (eq? |$\Atm_1$| |$\Atm_2$|) goto |$\ell_1$|;
  5164. else goto |$\ell_2$|;
  5165. \end{lstlisting}
  5166. \end{minipage}
  5167. &
  5168. $\Rightarrow$
  5169. &
  5170. \begin{minipage}{0.4\textwidth}
  5171. \begin{lstlisting}
  5172. cmpq |$\Arg_2$|, |$\Arg_1$|
  5173. je |$\ell_1$|
  5174. jmp |$\ell_2$|
  5175. \end{lstlisting}
  5176. \end{minipage}
  5177. \end{tabular} \\
  5178. \begin{exercise}\normalfont
  5179. Expand your \code{select-instructions} pass to handle the new features
  5180. of the \LangIf{} language.
  5181. %
  5182. Add the following entry to the list of \code{passes} in
  5183. \code{run-tests.rkt}
  5184. \begin{lstlisting}
  5185. (list "select-instructions" select-instructions interp-pseudo-x86-1)
  5186. \end{lstlisting}
  5187. %
  5188. Run the script to test your compiler on all the test programs.
  5189. \end{exercise}
  5190. \section{Register Allocation}
  5191. \label{sec:register-allocation-Rif}
  5192. \index{register allocation}
  5193. The changes required for \LangIf{} affect liveness analysis, building the
  5194. interference graph, and assigning homes, but the graph coloring
  5195. algorithm itself does not change.
  5196. \subsection{Liveness Analysis}
  5197. \label{sec:liveness-analysis-Rif}
  5198. \index{liveness analysis}
  5199. Recall that for \LangVar{} we implemented liveness analysis for a single
  5200. basic block (Section~\ref{sec:liveness-analysis-Rvar}). With the
  5201. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  5202. produces many basic blocks arranged in a control-flow graph. We
  5203. recommend that you create a new auxiliary function named
  5204. \code{uncover-live-CFG} that applies liveness analysis to a
  5205. control-flow graph.
  5206. The first question we is: what order should we process the basic
  5207. blocks in the control-flow graph? Recall that to perform liveness
  5208. analysis on a basic block we need to know its live-after set. If a
  5209. basic block has no successors (i.e. no out-edges in the control flow
  5210. graph), then it has an empty live-after set and we can immediately
  5211. apply liveness analysis to it. If a basic block has some successors,
  5212. then we need to complete liveness analysis on those blocks first. In
  5213. graph theory, a sequence of nodes is in \emph{topological
  5214. order}\index{topological order} if each vertex comes before its
  5215. successors. We need the opposite, so we can transpose the graph
  5216. before computing a topological order.
  5217. %
  5218. Use the \code{tsort} and \code{transpose} functions of the Racket
  5219. \code{graph} package to accomplish this.
  5220. %
  5221. As an aside, a topological ordering is only guaranteed to exist if the
  5222. graph does not contain any cycles. That is indeed the case for the
  5223. control-flow graphs that we generate from \LangIf{} programs.
  5224. However, in Chapter~\ref{ch:Rwhile} we add loops to \LangLoop{} and
  5225. learn how to handle cycles in the control-flow graph.
  5226. You'll need to construct a directed graph to represent the
  5227. control-flow graph. Do not use the \code{directed-graph} of the
  5228. \code{graph} package because that only allows at most one edge between
  5229. each pair of vertices, but a control-flow graph may have multiple
  5230. edges between a pair of vertices. The \code{multigraph.rkt} file in
  5231. the support code implements a graph representation that allows
  5232. multiple edges between a pair of vertices.
  5233. The next question is how to analyze jump instructions. Recall that in
  5234. Section~\ref{sec:liveness-analysis-Rvar} we maintain an alist named
  5235. \code{label->live} that maps each label to the set of live locations
  5236. at the beginning of its block. We use \code{label->live} to determine
  5237. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  5238. that we have many basic blocks, \code{label->live} needs to be updated
  5239. as we process the blocks. In particular, after performing liveness
  5240. analysis on a block, we take the live-before set of its first
  5241. instruction and associate that with the block's label in the
  5242. \code{label->live}.
  5243. In \LangXIfVar{} we also have the conditional jump
  5244. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  5245. this instruction is particularly interesting because during
  5246. compilation we do not know which way a conditional jump will go. So
  5247. we do not know whether to use the live-before set for the following
  5248. instruction or the live-before set for the $\itm{label}$. However,
  5249. there is no harm to the correctness of the compiler if we classify
  5250. more locations as live than the ones that are truly live during a
  5251. particular execution of the instruction. Thus, we can take the union
  5252. of the live-before sets from the following instruction and from the
  5253. mapping for $\itm{label}$ in \code{label->live}.
  5254. The auxiliary functions for computing the variables in an
  5255. instruction's argument and for computing the variables read-from ($R$)
  5256. or written-to ($W$) by an instruction need to be updated to handle the
  5257. new kinds of arguments and instructions in \LangXIfVar{}.
  5258. \begin{exercise}\normalfont
  5259. Update the \code{uncover-live} pass and implement the
  5260. \code{uncover-live-CFG} auxiliary function to apply liveness analysis
  5261. to the control-flow graph. Add the following entry to the list of
  5262. \code{passes} in the \code{run-tests.rkt} script.
  5263. \begin{lstlisting}
  5264. (list "uncover-live" uncover-live interp-pseudo-x86-1)
  5265. \end{lstlisting}
  5266. \end{exercise}
  5267. \subsection{Build the Interference Graph}
  5268. \label{sec:build-interference-Rif}
  5269. Many of the new instructions in \LangXIfVar{} can be handled in the
  5270. same way as the instructions in \LangXVar{}. Thus, if your code was
  5271. already quite general, it will not need to be changed to handle the
  5272. new instructions. If you code is not general enough, we recommend that
  5273. you change your code to be more general. For example, you can factor
  5274. out the computing of the the read and write sets for each kind of
  5275. instruction into two auxiliary functions.
  5276. Note that the \key{movzbq} instruction requires some special care,
  5277. similar to the \key{movq} instruction. See rule number 1 in
  5278. Section~\ref{sec:build-interference}.
  5279. \begin{exercise}\normalfont
  5280. Update the \code{build-interference} pass for \LangXIfVar{} and add the
  5281. following entries to the list of \code{passes} in the
  5282. \code{run-tests.rkt} script.
  5283. \begin{lstlisting}
  5284. (list "build-interference" build-interference interp-pseudo-x86-1)
  5285. (list "allocate-registers" allocate-registers interp-x86-1)
  5286. \end{lstlisting}
  5287. Run the script to test your compiler on all the \LangIf{} test
  5288. programs.
  5289. \end{exercise}
  5290. \section{Patch Instructions}
  5291. The second argument of the \key{cmpq} instruction must not be an
  5292. immediate value (such as an integer). So if you are comparing two
  5293. immediates, we recommend inserting a \key{movq} instruction to put the
  5294. second argument in \key{rax}. Also, recall that instructions may have
  5295. at most one memory reference.
  5296. %
  5297. The second argument of the \key{movzbq} must be a register.
  5298. %
  5299. There are no special restrictions on the jump instructions.
  5300. \begin{exercise}\normalfont
  5301. %
  5302. Update \code{patch-instructions} pass for \LangXIfVar{}.
  5303. %
  5304. Add the following entry to the list of \code{passes} in
  5305. \code{run-tests.rkt} and then run this script to test your compiler.
  5306. \begin{lstlisting}
  5307. (list "patch-instructions" patch-instructions interp-x86-1)
  5308. \end{lstlisting}
  5309. \end{exercise}
  5310. \begin{figure}[tbp]
  5311. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5312. \node (Rif) at (0,2) {\large \LangIf{}};
  5313. \node (Rif-2) at (3,2) {\large \LangIf{}};
  5314. \node (Rif-3) at (6,2) {\large \LangIf{}};
  5315. \node (Rif-4) at (9,2) {\large \LangIf{}};
  5316. \node (Rif-5) at (12,2) {\large \LangIf{}};
  5317. \node (C1-1) at (3,0) {\large \LangCIf{}};
  5318. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  5319. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  5320. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  5321. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  5322. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  5323. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  5324. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  5325. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  5326. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  5327. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  5328. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  5329. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  5330. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5331. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  5332. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5333. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5334. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  5335. \end{tikzpicture}
  5336. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  5337. \label{fig:Rif-passes}
  5338. \end{figure}
  5339. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  5340. compilation of \LangIf{}.
  5341. \section{An Example Translation}
  5342. Figure~\ref{fig:if-example-x86} shows a simple example program in
  5343. \LangIf{} translated to x86, showing the results of
  5344. \code{explicate-control}, \code{select-instructions}, and the final
  5345. x86 assembly code.
  5346. \begin{figure}[tbp]
  5347. \begin{tabular}{lll}
  5348. \begin{minipage}{0.4\textwidth}
  5349. % cond_test_20.rkt
  5350. \begin{lstlisting}
  5351. (if (eq? (read) 1) 42 0)
  5352. \end{lstlisting}
  5353. $\Downarrow$
  5354. \begin{lstlisting}
  5355. start:
  5356. tmp7951 = (read);
  5357. if (eq? tmp7951 1)
  5358. goto block7952;
  5359. else
  5360. goto block7953;
  5361. block7952:
  5362. return 42;
  5363. block7953:
  5364. return 0;
  5365. \end{lstlisting}
  5366. $\Downarrow$
  5367. \begin{lstlisting}
  5368. start:
  5369. callq read_int
  5370. movq %rax, tmp7951
  5371. cmpq $1, tmp7951
  5372. je block7952
  5373. jmp block7953
  5374. block7953:
  5375. movq $0, %rax
  5376. jmp conclusion
  5377. block7952:
  5378. movq $42, %rax
  5379. jmp conclusion
  5380. \end{lstlisting}
  5381. \end{minipage}
  5382. &
  5383. $\Rightarrow\qquad$
  5384. \begin{minipage}{0.4\textwidth}
  5385. \begin{lstlisting}
  5386. start:
  5387. callq read_int
  5388. movq %rax, %rcx
  5389. cmpq $1, %rcx
  5390. je block7952
  5391. jmp block7953
  5392. block7953:
  5393. movq $0, %rax
  5394. jmp conclusion
  5395. block7952:
  5396. movq $42, %rax
  5397. jmp conclusion
  5398. .globl main
  5399. main:
  5400. pushq %rbp
  5401. movq %rsp, %rbp
  5402. pushq %r13
  5403. pushq %r12
  5404. pushq %rbx
  5405. pushq %r14
  5406. subq $0, %rsp
  5407. jmp start
  5408. conclusion:
  5409. addq $0, %rsp
  5410. popq %r14
  5411. popq %rbx
  5412. popq %r12
  5413. popq %r13
  5414. popq %rbp
  5415. retq
  5416. \end{lstlisting}
  5417. \end{minipage}
  5418. \end{tabular}
  5419. \caption{Example compilation of an \key{if} expression to x86.}
  5420. \label{fig:if-example-x86}
  5421. \end{figure}
  5422. \section{Challenge: Remove Jumps}
  5423. \label{sec:opt-jumps}
  5424. %% Recall that in the example output of \code{explicate-control} in
  5425. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  5426. %% \code{block60} are trivial blocks, they do nothing but jump to another
  5427. %% block. The first goal of this challenge assignment is to remove those
  5428. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  5429. %% \code{explicate-control} on the left and shows the result of bypassing
  5430. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  5431. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  5432. %% \code{block55}. The optimized code on the right of
  5433. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  5434. %% \code{then} branch jumping directly to \code{block55}. The story is
  5435. %% similar for the \code{else} branch, as well as for the two branches in
  5436. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  5437. %% have been optimized in this way, there are no longer any jumps to
  5438. %% blocks \code{block57} through \code{block60}, so they can be removed.
  5439. %% \begin{figure}[tbp]
  5440. %% \begin{tabular}{lll}
  5441. %% \begin{minipage}{0.4\textwidth}
  5442. %% \begin{lstlisting}
  5443. %% block62:
  5444. %% tmp54 = (read);
  5445. %% if (eq? tmp54 2) then
  5446. %% goto block59;
  5447. %% else
  5448. %% goto block60;
  5449. %% block61:
  5450. %% tmp53 = (read);
  5451. %% if (eq? tmp53 0) then
  5452. %% goto block57;
  5453. %% else
  5454. %% goto block58;
  5455. %% block60:
  5456. %% goto block56;
  5457. %% block59:
  5458. %% goto block55;
  5459. %% block58:
  5460. %% goto block56;
  5461. %% block57:
  5462. %% goto block55;
  5463. %% block56:
  5464. %% return (+ 700 77);
  5465. %% block55:
  5466. %% return (+ 10 32);
  5467. %% start:
  5468. %% tmp52 = (read);
  5469. %% if (eq? tmp52 1) then
  5470. %% goto block61;
  5471. %% else
  5472. %% goto block62;
  5473. %% \end{lstlisting}
  5474. %% \end{minipage}
  5475. %% &
  5476. %% $\Rightarrow$
  5477. %% &
  5478. %% \begin{minipage}{0.55\textwidth}
  5479. %% \begin{lstlisting}
  5480. %% block62:
  5481. %% tmp54 = (read);
  5482. %% if (eq? tmp54 2) then
  5483. %% goto block55;
  5484. %% else
  5485. %% goto block56;
  5486. %% block61:
  5487. %% tmp53 = (read);
  5488. %% if (eq? tmp53 0) then
  5489. %% goto block55;
  5490. %% else
  5491. %% goto block56;
  5492. %% block56:
  5493. %% return (+ 700 77);
  5494. %% block55:
  5495. %% return (+ 10 32);
  5496. %% start:
  5497. %% tmp52 = (read);
  5498. %% if (eq? tmp52 1) then
  5499. %% goto block61;
  5500. %% else
  5501. %% goto block62;
  5502. %% \end{lstlisting}
  5503. %% \end{minipage}
  5504. %% \end{tabular}
  5505. %% \caption{Optimize jumps by removing trivial blocks.}
  5506. %% \label{fig:optimize-jumps}
  5507. %% \end{figure}
  5508. %% The name of this pass is \code{optimize-jumps}. We recommend
  5509. %% implementing this pass in two phases. The first phrase builds a hash
  5510. %% table that maps labels to possibly improved labels. The second phase
  5511. %% changes the target of each \code{goto} to use the improved label. If
  5512. %% the label is for a trivial block, then the hash table should map the
  5513. %% label to the first non-trivial block that can be reached from this
  5514. %% label by jumping through trivial blocks. If the label is for a
  5515. %% non-trivial block, then the hash table should map the label to itself;
  5516. %% we do not want to change jumps to non-trivial blocks.
  5517. %% The first phase can be accomplished by constructing an empty hash
  5518. %% table, call it \code{short-cut}, and then iterating over the control
  5519. %% flow graph. Each time you encouter a block that is just a \code{goto},
  5520. %% then update the hash table, mapping the block's source to the target
  5521. %% of the \code{goto}. Also, the hash table may already have mapped some
  5522. %% labels to the block's source, to you must iterate through the hash
  5523. %% table and update all of those so that they instead map to the target
  5524. %% of the \code{goto}.
  5525. %% For the second phase, we recommend iterating through the $\Tail$ of
  5526. %% each block in the program, updating the target of every \code{goto}
  5527. %% according to the mapping in \code{short-cut}.
  5528. %% \begin{exercise}\normalfont
  5529. %% Implement the \code{optimize-jumps} pass as a transformation from
  5530. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  5531. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  5532. %% example programs. Then check that your compiler still passes all of
  5533. %% your tests.
  5534. %% \end{exercise}
  5535. There is an opportunity for optimizing jumps that is apparent in the
  5536. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  5537. ends with a jump to \code{block7953} and there are no other jumps to
  5538. \code{block7953} in the rest of the program. In this situation we can
  5539. avoid the runtime overhead of this jump by merging \code{block7953}
  5540. into the preceding block, in this case the \code{start} block.
  5541. Figure~\ref{fig:remove-jumps} shows the output of
  5542. \code{select-instructions} on the left and the result of this
  5543. optimization on the right.
  5544. \begin{figure}[tbp]
  5545. \begin{tabular}{lll}
  5546. \begin{minipage}{0.5\textwidth}
  5547. % cond_test_20.rkt
  5548. \begin{lstlisting}
  5549. start:
  5550. callq read_int
  5551. movq %rax, tmp7951
  5552. cmpq $1, tmp7951
  5553. je block7952
  5554. jmp block7953
  5555. block7953:
  5556. movq $0, %rax
  5557. jmp conclusion
  5558. block7952:
  5559. movq $42, %rax
  5560. jmp conclusion
  5561. \end{lstlisting}
  5562. \end{minipage}
  5563. &
  5564. $\Rightarrow\qquad$
  5565. \begin{minipage}{0.4\textwidth}
  5566. \begin{lstlisting}
  5567. start:
  5568. callq read_int
  5569. movq %rax, tmp7951
  5570. cmpq $1, tmp7951
  5571. je block7952
  5572. movq $0, %rax
  5573. jmp conclusion
  5574. block7952:
  5575. movq $42, %rax
  5576. jmp conclusion
  5577. \end{lstlisting}
  5578. \end{minipage}
  5579. \end{tabular}
  5580. \caption{Merging basic blocks by removing unnecessary jumps.}
  5581. \label{fig:remove-jumps}
  5582. \end{figure}
  5583. \begin{exercise}\normalfont
  5584. %
  5585. Implement a pass named \code{remove-jumps} that merges basic blocks
  5586. into their preceding basic block, when there is only one preceding
  5587. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  5588. %
  5589. In the \code{run-tests.rkt} script, add the following entry to the
  5590. list of \code{passes} between \code{allocate-registers}
  5591. and \code{patch-instructions}.
  5592. \begin{lstlisting}
  5593. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  5594. \end{lstlisting}
  5595. Run this script to test your compiler.
  5596. %
  5597. Check that \code{remove-jumps} accomplishes the goal of merging basic
  5598. blocks on several test programs.
  5599. \end{exercise}
  5600. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5601. \chapter{Tuples and Garbage Collection}
  5602. \label{ch:Rvec}
  5603. \index{tuple}
  5604. \index{vector}
  5605. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  5606. all the IR grammars are spelled out! \\ --Jeremy}
  5607. \margincomment{\scriptsize Be more explicit about how to deal with
  5608. the root stack. \\ --Jeremy}
  5609. In this chapter we study the implementation of mutable tuples, called
  5610. vectors in Racket. This language feature is the first to use the
  5611. computer's \emph{heap}\index{heap} because the lifetime of a Racket
  5612. tuple is indefinite, that is, a tuple lives forever from the
  5613. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  5614. is important to reclaim the space associated with a tuple when it is
  5615. no longer needed, which is why we also study \emph{garbage collection}
  5616. \emph{garbage collection} techniques in this chapter.
  5617. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  5618. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  5619. language of Chapter~\ref{ch:Rif} with vectors and Racket's
  5620. \code{void} value. The reason for including the later is that the
  5621. \code{vector-set!} operation returns a value of type
  5622. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5623. called the \code{Unit} type in the programming languages
  5624. literature. Racket's \code{Void} type is inhabited by a single value
  5625. \code{void} which corresponds to \code{unit} or \code{()} in the
  5626. literature~\citep{Pierce:2002hj}.}.
  5627. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5628. copying live objects back and forth between two halves of the
  5629. heap. The garbage collector requires coordination with the compiler so
  5630. that it can see all of the \emph{root} pointers, that is, pointers in
  5631. registers or on the procedure call stack.
  5632. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5633. discuss all the necessary changes and additions to the compiler
  5634. passes, including a new compiler pass named \code{expose-allocation}.
  5635. \section{The \LangVec{} Language}
  5636. \label{sec:r3}
  5637. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  5638. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  5639. \LangVec{} language includes three new forms: \code{vector} for creating a
  5640. tuple, \code{vector-ref} for reading an element of a tuple, and
  5641. \code{vector-set!} for writing to an element of a tuple. The program
  5642. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5643. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5644. the 3-tuple, demonstrating that tuples are first-class values. The
  5645. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5646. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5647. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5648. 1-tuple. So the result of the program is \code{42}.
  5649. \begin{figure}[tbp]
  5650. \centering
  5651. \fbox{
  5652. \begin{minipage}{0.96\textwidth}
  5653. \[
  5654. \begin{array}{lcl}
  5655. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5656. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}\\
  5657. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5658. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5659. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5660. \mid \LP\key{and}\;\Exp\;\Exp\RP
  5661. \mid \LP\key{or}\;\Exp\;\Exp\RP
  5662. \mid \LP\key{not}\;\Exp\RP } \\
  5663. &\mid& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  5664. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5665. &\mid& \LP\key{vector}\;\Exp\ldots\RP
  5666. \mid \LP\key{vector-length}\;\Exp\RP \\
  5667. &\mid& \LP\key{vector-ref}\;\Exp\;\Int\RP
  5668. \mid \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  5669. &\mid& \LP\key{void}\RP \mid \LP\key{has-type}~\Exp~\Type\RP\\
  5670. \LangVec{} &::=& \Exp
  5671. \end{array}
  5672. \]
  5673. \end{minipage}
  5674. }
  5675. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  5676. (Figure~\ref{fig:Rif-concrete-syntax}).}
  5677. \label{fig:Rvec-concrete-syntax}
  5678. \end{figure}
  5679. \begin{figure}[tbp]
  5680. \begin{lstlisting}
  5681. (let ([t (vector 40 #t (vector 2))])
  5682. (if (vector-ref t 1)
  5683. (+ (vector-ref t 0)
  5684. (vector-ref (vector-ref t 2) 0))
  5685. 44))
  5686. \end{lstlisting}
  5687. \caption{Example program that creates tuples and reads from them.}
  5688. \label{fig:vector-eg}
  5689. \end{figure}
  5690. \begin{figure}[tp]
  5691. \centering
  5692. \fbox{
  5693. \begin{minipage}{0.96\textwidth}
  5694. \[
  5695. \begin{array}{lcl}
  5696. \itm{op} &::=& \ldots \mid \code{vector} \mid \code{vector-length} \\
  5697. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5698. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5699. \mid \BOOL{\itm{bool}}
  5700. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5701. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  5702. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  5703. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5704. \LangVec{} &::=& \PROGRAM{\key{'()}}{\Exp}
  5705. \end{array}
  5706. \]
  5707. \end{minipage}
  5708. }
  5709. \caption{The abstract syntax of \LangVec{}.}
  5710. \label{fig:Rvec-syntax}
  5711. \end{figure}
  5712. \index{allocate}
  5713. \index{heap allocate}
  5714. Tuples are our first encounter with heap-allocated data, which raises
  5715. several interesting issues. First, variable binding performs a
  5716. shallow-copy when dealing with tuples, which means that different
  5717. variables can refer to the same tuple, that is, different variables
  5718. can be \emph{aliases} for the same entity. Consider the following
  5719. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5720. Thus, the mutation through \code{t2} is visible when referencing the
  5721. tuple from \code{t1}, so the result of this program is \code{42}.
  5722. \index{alias}\index{mutation}
  5723. \begin{center}
  5724. \begin{minipage}{0.96\textwidth}
  5725. \begin{lstlisting}
  5726. (let ([t1 (vector 3 7)])
  5727. (let ([t2 t1])
  5728. (let ([_ (vector-set! t2 0 42)])
  5729. (vector-ref t1 0))))
  5730. \end{lstlisting}
  5731. \end{minipage}
  5732. \end{center}
  5733. The next issue concerns the lifetime of tuples. Of course, they are
  5734. created by the \code{vector} form, but when does their lifetime end?
  5735. Notice that \LangVec{} does not include an operation for deleting
  5736. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5737. of static scoping. For example, the following program returns
  5738. \code{42} even though the variable \code{w} goes out of scope prior to
  5739. the \code{vector-ref} that reads from the vector it was bound to.
  5740. \begin{center}
  5741. \begin{minipage}{0.96\textwidth}
  5742. \begin{lstlisting}
  5743. (let ([v (vector (vector 44))])
  5744. (let ([x (let ([w (vector 42)])
  5745. (let ([_ (vector-set! v 0 w)])
  5746. 0))])
  5747. (+ x (vector-ref (vector-ref v 0) 0))))
  5748. \end{lstlisting}
  5749. \end{minipage}
  5750. \end{center}
  5751. From the perspective of programmer-observable behavior, tuples live
  5752. forever. Of course, if they really lived forever, then many programs
  5753. would run out of memory.\footnote{The \LangVec{} language does not have
  5754. looping or recursive functions, so it is nigh impossible to write a
  5755. program in \LangVec{} that will run out of memory. However, we add
  5756. recursive functions in the next Chapter!} A Racket implementation
  5757. must therefore perform automatic garbage collection.
  5758. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  5759. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  5760. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  5761. terms of the corresponding operations in Racket. One subtle point is
  5762. that the \code{vector-set!} operation returns the \code{\#<void>}
  5763. value. The \code{\#<void>} value can be passed around just like other
  5764. values inside an \LangVec{} program and a \code{\#<void>} value can be
  5765. compared for equality with another \code{\#<void>} value. However,
  5766. there are no other operations specific to the the \code{\#<void>}
  5767. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  5768. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  5769. otherwise.
  5770. \begin{figure}[tbp]
  5771. \begin{lstlisting}
  5772. (define interp-Rvec-class
  5773. (class interp-Rif-class
  5774. (super-new)
  5775. (define/override (interp-op op)
  5776. (match op
  5777. ['eq? (lambda (v1 v2)
  5778. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5779. (and (boolean? v1) (boolean? v2))
  5780. (and (vector? v1) (vector? v2))
  5781. (and (void? v1) (void? v2)))
  5782. (eq? v1 v2)]))]
  5783. ['vector vector]
  5784. ['vector-length vector-length]
  5785. ['vector-ref vector-ref]
  5786. ['vector-set! vector-set!]
  5787. [else (super interp-op op)]
  5788. ))
  5789. (define/override ((interp-exp env) e)
  5790. (define recur (interp-exp env))
  5791. (match e
  5792. [(HasType e t) (recur e)]
  5793. [(Void) (void)]
  5794. [else ((super interp-exp env) e)]
  5795. ))
  5796. ))
  5797. (define (interp-Rvec p)
  5798. (send (new interp-Rvec-class) interp-program p))
  5799. \end{lstlisting}
  5800. \caption{Interpreter for the \LangVec{} language.}
  5801. \label{fig:interp-Rvec}
  5802. \end{figure}
  5803. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  5804. deserves some explanation. When allocating a vector, we need to know
  5805. which elements of the vector are pointers (i.e. are also vectors). We
  5806. can obtain this information during type checking. The type checker in
  5807. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  5808. expression, it also wraps every \key{vector} creation with the form
  5809. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  5810. %
  5811. To create the s-expression for the \code{Vector} type in
  5812. Figure~\ref{fig:type-check-Rvec}, we use the
  5813. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5814. operator} \code{,@} to insert the list \code{t*} without its usual
  5815. start and end parentheses. \index{unquote-slicing}
  5816. \begin{figure}[tp]
  5817. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5818. (define type-check-Rvec-class
  5819. (class type-check-Rif-class
  5820. (super-new)
  5821. (inherit check-type-equal?)
  5822. (define/override (type-check-exp env)
  5823. (lambda (e)
  5824. (define recur (type-check-exp env))
  5825. (match e
  5826. [(Void) (values (Void) 'Void)]
  5827. [(Prim 'vector es)
  5828. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5829. (define t `(Vector ,@t*))
  5830. (values (HasType (Prim 'vector e*) t) t)]
  5831. [(Prim 'vector-ref (list e1 (Int i)))
  5832. (define-values (e1^ t) (recur e1))
  5833. (match t
  5834. [`(Vector ,ts ...)
  5835. (unless (and (0 . <= . i) (i . < . (length ts)))
  5836. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5837. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  5838. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5839. [(Prim 'vector-set! (list e1 (Int i) arg) )
  5840. (define-values (e-vec t-vec) (recur e1))
  5841. (define-values (e-arg^ t-arg) (recur arg))
  5842. (match t-vec
  5843. [`(Vector ,ts ...)
  5844. (unless (and (0 . <= . i) (i . < . (length ts)))
  5845. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5846. (check-type-equal? (list-ref ts i) t-arg e)
  5847. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5848. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  5849. [(Prim 'vector-length (list e))
  5850. (define-values (e^ t) (recur e))
  5851. (match t
  5852. [`(Vector ,ts ...)
  5853. (values (Prim 'vector-length (list e^)) 'Integer)]
  5854. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5855. [(Prim 'eq? (list arg1 arg2))
  5856. (define-values (e1 t1) (recur arg1))
  5857. (define-values (e2 t2) (recur arg2))
  5858. (match* (t1 t2)
  5859. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  5860. [(other wise) (check-type-equal? t1 t2 e)])
  5861. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  5862. [(HasType (Prim 'vector es) t)
  5863. ((type-check-exp env) (Prim 'vector es))]
  5864. [(HasType e1 t)
  5865. (define-values (e1^ t^) (recur e1))
  5866. (check-type-equal? t t^ e)
  5867. (values (HasType e1^ t) t)]
  5868. [else ((super type-check-exp env) e)]
  5869. )))
  5870. ))
  5871. (define (type-check-Rvec p)
  5872. (send (new type-check-Rvec-class) type-check-program p))
  5873. \end{lstlisting}
  5874. \caption{Type checker for the \LangVec{} language.}
  5875. \label{fig:type-check-Rvec}
  5876. \end{figure}
  5877. \section{Garbage Collection}
  5878. \label{sec:GC}
  5879. Here we study a relatively simple algorithm for garbage collection
  5880. that is the basis of state-of-the-art garbage
  5881. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5882. particular, we describe a two-space copying
  5883. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5884. perform the
  5885. copy~\citep{Cheney:1970aa}.
  5886. \index{copying collector}
  5887. \index{two-space copying collector}
  5888. Figure~\ref{fig:copying-collector} gives a
  5889. coarse-grained depiction of what happens in a two-space collector,
  5890. showing two time steps, prior to garbage collection (on the top) and
  5891. after garbage collection (on the bottom). In a two-space collector,
  5892. the heap is divided into two parts named the FromSpace and the
  5893. ToSpace. Initially, all allocations go to the FromSpace until there is
  5894. not enough room for the next allocation request. At that point, the
  5895. garbage collector goes to work to make more room.
  5896. \index{ToSpace}
  5897. \index{FromSpace}
  5898. The garbage collector must be careful not to reclaim tuples that will
  5899. be used by the program in the future. Of course, it is impossible in
  5900. general to predict what a program will do, but we can over approximate
  5901. the will-be-used tuples by preserving all tuples that could be
  5902. accessed by \emph{any} program given the current computer state. A
  5903. program could access any tuple whose address is in a register or on
  5904. the procedure call stack. These addresses are called the \emph{root
  5905. set}\index{root set}. In addition, a program could access any tuple that is
  5906. transitively reachable from the root set. Thus, it is safe for the
  5907. garbage collector to reclaim the tuples that are not reachable in this
  5908. way.
  5909. So the goal of the garbage collector is twofold:
  5910. \begin{enumerate}
  5911. \item preserve all tuple that are reachable from the root set via a
  5912. path of pointers, that is, the \emph{live} tuples, and
  5913. \item reclaim the memory of everything else, that is, the
  5914. \emph{garbage}.
  5915. \end{enumerate}
  5916. A copying collector accomplishes this by copying all of the live
  5917. objects from the FromSpace into the ToSpace and then performs a sleight
  5918. of hand, treating the ToSpace as the new FromSpace and the old
  5919. FromSpace as the new ToSpace. In the example of
  5920. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5921. root set, one in a register and two on the stack. All of the live
  5922. objects have been copied to the ToSpace (the right-hand side of
  5923. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5924. pointer relationships. For example, the pointer in the register still
  5925. points to a 2-tuple whose first element is a 3-tuple and whose second
  5926. element is a 2-tuple. There are four tuples that are not reachable
  5927. from the root set and therefore do not get copied into the ToSpace.
  5928. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5929. created by a well-typed program in \LangVec{} because it contains a
  5930. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  5931. We design the garbage collector to deal with cycles to begin with so
  5932. we will not need to revisit this issue.
  5933. \begin{figure}[tbp]
  5934. \centering
  5935. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5936. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5937. \caption{A copying collector in action.}
  5938. \label{fig:copying-collector}
  5939. \end{figure}
  5940. There are many alternatives to copying collectors (and their bigger
  5941. siblings, the generational collectors) when its comes to garbage
  5942. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5943. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5944. collectors are that allocation is fast (just a comparison and pointer
  5945. increment), there is no fragmentation, cyclic garbage is collected,
  5946. and the time complexity of collection only depends on the amount of
  5947. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5948. main disadvantages of a two-space copying collector is that it uses a
  5949. lot of space and takes a long time to perform the copy, though these
  5950. problems are ameliorated in generational collectors. Racket and
  5951. Scheme programs tend to allocate many small objects and generate a lot
  5952. of garbage, so copying and generational collectors are a good fit.
  5953. Garbage collection is an active research topic, especially concurrent
  5954. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5955. developing new techniques and revisiting old
  5956. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5957. meet every year at the International Symposium on Memory Management to
  5958. present these findings.
  5959. \subsection{Graph Copying via Cheney's Algorithm}
  5960. \label{sec:cheney}
  5961. \index{Cheney's algorithm}
  5962. Let us take a closer look at the copying of the live objects. The
  5963. allocated objects and pointers can be viewed as a graph and we need to
  5964. copy the part of the graph that is reachable from the root set. To
  5965. make sure we copy all of the reachable vertices in the graph, we need
  5966. an exhaustive graph traversal algorithm, such as depth-first search or
  5967. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5968. such algorithms take into account the possibility of cycles by marking
  5969. which vertices have already been visited, so as to ensure termination
  5970. of the algorithm. These search algorithms also use a data structure
  5971. such as a stack or queue as a to-do list to keep track of the vertices
  5972. that need to be visited. We use breadth-first search and a trick
  5973. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5974. and copying tuples into the ToSpace.
  5975. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5976. copy progresses. The queue is represented by a chunk of contiguous
  5977. memory at the beginning of the ToSpace, using two pointers to track
  5978. the front and the back of the queue. The algorithm starts by copying
  5979. all tuples that are immediately reachable from the root set into the
  5980. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5981. old tuple to indicate that it has been visited. We discuss how this
  5982. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5983. pointers inside the copied tuples in the queue still point back to the
  5984. FromSpace. Once the initial queue has been created, the algorithm
  5985. enters a loop in which it repeatedly processes the tuple at the front
  5986. of the queue and pops it off the queue. To process a tuple, the
  5987. algorithm copies all the tuple that are directly reachable from it to
  5988. the ToSpace, placing them at the back of the queue. The algorithm then
  5989. updates the pointers in the popped tuple so they point to the newly
  5990. copied tuples.
  5991. \begin{figure}[tbp]
  5992. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5993. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5994. \label{fig:cheney}
  5995. \end{figure}
  5996. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5997. tuple whose second element is $42$ to the back of the queue. The other
  5998. pointer goes to a tuple that has already been copied, so we do not
  5999. need to copy it again, but we do need to update the pointer to the new
  6000. location. This can be accomplished by storing a \emph{forwarding
  6001. pointer} to the new location in the old tuple, back when we initially
  6002. copied the tuple into the ToSpace. This completes one step of the
  6003. algorithm. The algorithm continues in this way until the front of the
  6004. queue is empty, that is, until the front catches up with the back.
  6005. \subsection{Data Representation}
  6006. \label{sec:data-rep-gc}
  6007. The garbage collector places some requirements on the data
  6008. representations used by our compiler. First, the garbage collector
  6009. needs to distinguish between pointers and other kinds of data. There
  6010. are several ways to accomplish this.
  6011. \begin{enumerate}
  6012. \item Attached a tag to each object that identifies what type of
  6013. object it is~\citep{McCarthy:1960dz}.
  6014. \item Store different types of objects in different
  6015. regions~\citep{Steele:1977ab}.
  6016. \item Use type information from the program to either generate
  6017. type-specific code for collecting or to generate tables that can
  6018. guide the
  6019. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  6020. \end{enumerate}
  6021. Dynamically typed languages, such as Lisp, need to tag objects
  6022. anyways, so option 1 is a natural choice for those languages.
  6023. However, \LangVec{} is a statically typed language, so it would be
  6024. unfortunate to require tags on every object, especially small and
  6025. pervasive objects like integers and Booleans. Option 3 is the
  6026. best-performing choice for statically typed languages, but comes with
  6027. a relatively high implementation complexity. To keep this chapter
  6028. within a 2-week time budget, we recommend a combination of options 1
  6029. and 2, using separate strategies for the stack and the heap.
  6030. Regarding the stack, we recommend using a separate stack for pointers,
  6031. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  6032. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  6033. is, when a local variable needs to be spilled and is of type
  6034. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  6035. stack instead of the normal procedure call stack. Furthermore, we
  6036. always spill vector-typed variables if they are live during a call to
  6037. the collector, thereby ensuring that no pointers are in registers
  6038. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  6039. example from Figure~\ref{fig:copying-collector} and contrasts it with
  6040. the data layout using a root stack. The root stack contains the two
  6041. pointers from the regular stack and also the pointer in the second
  6042. register.
  6043. \begin{figure}[tbp]
  6044. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  6045. \caption{Maintaining a root stack to facilitate garbage collection.}
  6046. \label{fig:shadow-stack}
  6047. \end{figure}
  6048. The problem of distinguishing between pointers and other kinds of data
  6049. also arises inside of each tuple on the heap. We solve this problem by
  6050. attaching a tag, an extra 64-bits, to each
  6051. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  6052. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  6053. that we have drawn the bits in a big-endian way, from right-to-left,
  6054. with bit location 0 (the least significant bit) on the far right,
  6055. which corresponds to the direction of the x86 shifting instructions
  6056. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  6057. is dedicated to specifying which elements of the tuple are pointers,
  6058. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  6059. indicates there is a pointer and a 0 bit indicates some other kind of
  6060. data. The pointer mask starts at bit location 7. We have limited
  6061. tuples to a maximum size of 50 elements, so we just need 50 bits for
  6062. the pointer mask. The tag also contains two other pieces of
  6063. information. The length of the tuple (number of elements) is stored in
  6064. bits location 1 through 6. Finally, the bit at location 0 indicates
  6065. whether the tuple has yet to be copied to the ToSpace. If the bit has
  6066. value 1, then this tuple has not yet been copied. If the bit has
  6067. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  6068. of a pointer are always zero anyways because our tuples are 8-byte
  6069. aligned.)
  6070. \begin{figure}[tbp]
  6071. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  6072. \caption{Representation of tuples in the heap.}
  6073. \label{fig:tuple-rep}
  6074. \end{figure}
  6075. \subsection{Implementation of the Garbage Collector}
  6076. \label{sec:organize-gz}
  6077. \index{prelude}
  6078. An implementation of the copying collector is provided in the
  6079. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  6080. interface to the garbage collector that is used by the compiler. The
  6081. \code{initialize} function creates the FromSpace, ToSpace, and root
  6082. stack and should be called in the prelude of the \code{main}
  6083. function. The arguments of \code{initialize} are the root stack size
  6084. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  6085. good choice for both. The \code{initialize} function puts the address
  6086. of the beginning of the FromSpace into the global variable
  6087. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  6088. the address that is 1-past the last element of the FromSpace. (We use
  6089. half-open intervals to represent chunks of
  6090. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  6091. points to the first element of the root stack.
  6092. As long as there is room left in the FromSpace, your generated code
  6093. can allocate tuples simply by moving the \code{free\_ptr} forward.
  6094. %
  6095. The amount of room left in FromSpace is the difference between the
  6096. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  6097. function should be called when there is not enough room left in the
  6098. FromSpace for the next allocation. The \code{collect} function takes
  6099. a pointer to the current top of the root stack (one past the last item
  6100. that was pushed) and the number of bytes that need to be
  6101. allocated. The \code{collect} function performs the copying collection
  6102. and leaves the heap in a state such that the next allocation will
  6103. succeed.
  6104. \begin{figure}[tbp]
  6105. \begin{lstlisting}
  6106. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  6107. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  6108. int64_t* free_ptr;
  6109. int64_t* fromspace_begin;
  6110. int64_t* fromspace_end;
  6111. int64_t** rootstack_begin;
  6112. \end{lstlisting}
  6113. \caption{The compiler's interface to the garbage collector.}
  6114. \label{fig:gc-header}
  6115. \end{figure}
  6116. %% \begin{exercise}
  6117. %% In the file \code{runtime.c} you will find the implementation of
  6118. %% \code{initialize} and a partial implementation of \code{collect}.
  6119. %% The \code{collect} function calls another function, \code{cheney},
  6120. %% to perform the actual copy, and that function is left to the reader
  6121. %% to implement. The following is the prototype for \code{cheney}.
  6122. %% \begin{lstlisting}
  6123. %% static void cheney(int64_t** rootstack_ptr);
  6124. %% \end{lstlisting}
  6125. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  6126. %% rootstack (which is an array of pointers). The \code{cheney} function
  6127. %% also communicates with \code{collect} through the global
  6128. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  6129. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  6130. %% the ToSpace:
  6131. %% \begin{lstlisting}
  6132. %% static int64_t* tospace_begin;
  6133. %% static int64_t* tospace_end;
  6134. %% \end{lstlisting}
  6135. %% The job of the \code{cheney} function is to copy all the live
  6136. %% objects (reachable from the root stack) into the ToSpace, update
  6137. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  6138. %% update the root stack so that it points to the objects in the
  6139. %% ToSpace, and finally to swap the global pointers for the FromSpace
  6140. %% and ToSpace.
  6141. %% \end{exercise}
  6142. %% \section{Compiler Passes}
  6143. %% \label{sec:code-generation-gc}
  6144. The introduction of garbage collection has a non-trivial impact on our
  6145. compiler passes. We introduce a new compiler pass named
  6146. \code{expose-allocation}. We make
  6147. significant changes to \code{select-instructions},
  6148. \code{build-interference}, \code{allocate-registers}, and
  6149. \code{print-x86} and make minor changes in several more passes. The
  6150. following program will serve as our running example. It creates two
  6151. tuples, one nested inside the other. Both tuples have length one. The
  6152. program accesses the element in the inner tuple tuple via two vector
  6153. references.
  6154. % tests/s2_17.rkt
  6155. \begin{lstlisting}
  6156. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  6157. \end{lstlisting}
  6158. \section{Shrink}
  6159. \label{sec:shrink-Rvec}
  6160. Recall that the \code{shrink} pass translates the primitives operators
  6161. into a smaller set of primitives. Because this pass comes after type
  6162. checking, but before the passes that require the type information in
  6163. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  6164. to wrap \code{HasType} around each AST node that it generates.
  6165. \section{Expose Allocation}
  6166. \label{sec:expose-allocation}
  6167. The pass \code{expose-allocation} lowers the \code{vector} creation
  6168. form into a conditional call to the collector followed by the
  6169. allocation. We choose to place the \code{expose-allocation} pass
  6170. before \code{remove-complex-opera*} because the code generated by
  6171. \code{expose-allocation} contains complex operands. We also place
  6172. \code{expose-allocation} before \code{explicate-control} because
  6173. \code{expose-allocation} introduces new variables using \code{let},
  6174. but \code{let} is gone after \code{explicate-control}.
  6175. The output of \code{expose-allocation} is a language \LangAlloc{} that
  6176. extends \LangVec{} with the three new forms that we use in the translation
  6177. of the \code{vector} form.
  6178. \[
  6179. \begin{array}{lcl}
  6180. \Exp &::=& \cdots
  6181. \mid (\key{collect} \,\itm{int})
  6182. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  6183. \mid (\key{global-value} \,\itm{name})
  6184. \end{array}
  6185. \]
  6186. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  6187. $n$ bytes. It will become a call to the \code{collect} function in
  6188. \code{runtime.c} in \code{select-instructions}. The
  6189. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  6190. \index{allocate}
  6191. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  6192. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  6193. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  6194. a global variable, such as \code{free\_ptr}.
  6195. In the following, we show the transformation for the \code{vector}
  6196. form into 1) a sequence of let-bindings for the initializing
  6197. expressions, 2) a conditional call to \code{collect}, 3) a call to
  6198. \code{allocate}, and 4) the initialization of the vector. In the
  6199. following, \itm{len} refers to the length of the vector and
  6200. \itm{bytes} is how many total bytes need to be allocated for the
  6201. vector, which is 8 for the tag plus \itm{len} times 8.
  6202. \begin{lstlisting}
  6203. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  6204. |$\Longrightarrow$|
  6205. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  6206. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  6207. (global-value fromspace_end))
  6208. (void)
  6209. (collect |\itm{bytes}|))])
  6210. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  6211. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  6212. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  6213. |$v$|) ... )))) ...)
  6214. \end{lstlisting}
  6215. In the above, we suppressed all of the \code{has-type} forms in the
  6216. output for the sake of readability. The placement of the initializing
  6217. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  6218. sequence of \code{vector-set!} is important, as those expressions may
  6219. trigger garbage collection and we cannot have an allocated but
  6220. uninitialized tuple on the heap during a collection.
  6221. Figure~\ref{fig:expose-alloc-output} shows the output of the
  6222. \code{expose-allocation} pass on our running example.
  6223. \begin{figure}[tbp]
  6224. % tests/s2_17.rkt
  6225. \begin{lstlisting}
  6226. (vector-ref
  6227. (vector-ref
  6228. (let ([vecinit7976
  6229. (let ([vecinit7972 42])
  6230. (let ([collectret7974
  6231. (if (< (+ (global-value free_ptr) 16)
  6232. (global-value fromspace_end))
  6233. (void)
  6234. (collect 16)
  6235. )])
  6236. (let ([alloc7971 (allocate 1 (Vector Integer))])
  6237. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  6238. alloc7971)
  6239. )
  6240. )
  6241. )
  6242. ])
  6243. (let ([collectret7978
  6244. (if (< (+ (global-value free_ptr) 16)
  6245. (global-value fromspace_end))
  6246. (void)
  6247. (collect 16)
  6248. )])
  6249. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  6250. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  6251. alloc7975)
  6252. )
  6253. )
  6254. )
  6255. 0)
  6256. 0)
  6257. \end{lstlisting}
  6258. \caption{Output of the \code{expose-allocation} pass, minus
  6259. all of the \code{has-type} forms.}
  6260. \label{fig:expose-alloc-output}
  6261. \end{figure}
  6262. \section{Remove Complex Operands}
  6263. \label{sec:remove-complex-opera-Rvec}
  6264. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  6265. should all be treated as complex operands.
  6266. %% A new case for
  6267. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  6268. %% handled carefully to prevent the \code{Prim} node from being separated
  6269. %% from its enclosing \code{HasType}.
  6270. Figure~\ref{fig:Rvec-anf-syntax}
  6271. shows the grammar for the output language \LangVecANF{} of this
  6272. pass, which is \LangVec{} in administrative normal form.
  6273. \begin{figure}[tp]
  6274. \centering
  6275. \fbox{
  6276. \begin{minipage}{0.96\textwidth}
  6277. \small
  6278. \[
  6279. \begin{array}{rcl}
  6280. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  6281. \mid \VOID{} \\
  6282. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  6283. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  6284. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6285. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  6286. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  6287. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  6288. \mid \LP\key{GlobalValue}~\Var\RP\\
  6289. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  6290. R^{\dagger}_3 &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  6291. \end{array}
  6292. \]
  6293. \end{minipage}
  6294. }
  6295. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  6296. \label{fig:Rvec-anf-syntax}
  6297. \end{figure}
  6298. \section{Explicate Control and the \LangCVec{} language}
  6299. \label{sec:explicate-control-r3}
  6300. \begin{figure}[tp]
  6301. \fbox{
  6302. \begin{minipage}{0.96\textwidth}
  6303. \small
  6304. \[
  6305. \begin{array}{lcl}
  6306. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6307. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6308. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6309. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6310. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6311. &\mid& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  6312. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  6313. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  6314. &\mid& \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP\\
  6315. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  6316. \mid \LP\key{Collect} \,\itm{int}\RP \\
  6317. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6318. \mid \GOTO{\itm{label}} } \\
  6319. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6320. \LangCVec{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  6321. \end{array}
  6322. \]
  6323. \end{minipage}
  6324. }
  6325. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  6326. (Figure~\ref{fig:c1-syntax}).}
  6327. \label{fig:c2-syntax}
  6328. \end{figure}
  6329. The output of \code{explicate-control} is a program in the
  6330. intermediate language \LangCVec{}, whose abstract syntax is defined in
  6331. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  6332. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  6333. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  6334. \key{vector-set!}, and \key{global-value} expressions and the
  6335. \code{collect} statement. The \code{explicate-control} pass can treat
  6336. these new forms much like the other expression forms that we've
  6337. already encoutered.
  6338. \section{Select Instructions and the \LangXGlobal{} Language}
  6339. \label{sec:select-instructions-gc}
  6340. \index{instruction selection}
  6341. %% void (rep as zero)
  6342. %% allocate
  6343. %% collect (callq collect)
  6344. %% vector-ref
  6345. %% vector-set!
  6346. %% global (postpone)
  6347. In this pass we generate x86 code for most of the new operations that
  6348. were needed to compile tuples, including \code{Allocate},
  6349. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  6350. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  6351. the later has a different concrete syntax (see
  6352. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  6353. \index{x86}
  6354. The \code{vector-ref} and \code{vector-set!} forms translate into
  6355. \code{movq} instructions. (The plus one in the offset is to get past
  6356. the tag at the beginning of the tuple representation.)
  6357. \begin{lstlisting}
  6358. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  6359. |$\Longrightarrow$|
  6360. movq |$\itm{vec}'$|, %r11
  6361. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  6362. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  6363. |$\Longrightarrow$|
  6364. movq |$\itm{vec}'$|, %r11
  6365. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  6366. movq $0, |$\itm{lhs'}$|
  6367. \end{lstlisting}
  6368. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  6369. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  6370. register \code{r11} ensures that offset expression
  6371. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  6372. removing \code{r11} from consideration by the register allocating.
  6373. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  6374. \code{rax}. Then the generated code for \code{vector-set!} would be
  6375. \begin{lstlisting}
  6376. movq |$\itm{vec}'$|, %rax
  6377. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  6378. movq $0, |$\itm{lhs}'$|
  6379. \end{lstlisting}
  6380. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  6381. \code{patch-instructions} would insert a move through \code{rax}
  6382. as follows.
  6383. \begin{lstlisting}
  6384. movq |$\itm{vec}'$|, %rax
  6385. movq |$\itm{arg}'$|, %rax
  6386. movq %rax, |$8(n+1)$|(%rax)
  6387. movq $0, |$\itm{lhs}'$|
  6388. \end{lstlisting}
  6389. But the above sequence of instructions does not work because we're
  6390. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  6391. $\itm{arg}'$) at the same time!
  6392. We compile the \code{allocate} form to operations on the
  6393. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  6394. is the next free address in the FromSpace, so we copy it into
  6395. \code{r11} and then move it forward by enough space for the tuple
  6396. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  6397. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  6398. initialize the \itm{tag} and finally copy the address in \code{r11} to
  6399. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  6400. tag is organized. We recommend using the Racket operations
  6401. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  6402. during compilation. The type annotation in the \code{vector} form is
  6403. used to determine the pointer mask region of the tag.
  6404. \begin{lstlisting}
  6405. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  6406. |$\Longrightarrow$|
  6407. movq free_ptr(%rip), %r11
  6408. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  6409. movq $|$\itm{tag}$|, 0(%r11)
  6410. movq %r11, |$\itm{lhs}'$|
  6411. \end{lstlisting}
  6412. The \code{collect} form is compiled to a call to the \code{collect}
  6413. function in the runtime. The arguments to \code{collect} are 1) the
  6414. top of the root stack and 2) the number of bytes that need to be
  6415. allocated. We use another dedicated register, \code{r15}, to
  6416. store the pointer to the top of the root stack. So \code{r15} is not
  6417. available for use by the register allocator.
  6418. \begin{lstlisting}
  6419. (collect |$\itm{bytes}$|)
  6420. |$\Longrightarrow$|
  6421. movq %r15, %rdi
  6422. movq $|\itm{bytes}|, %rsi
  6423. callq collect
  6424. \end{lstlisting}
  6425. \begin{figure}[tp]
  6426. \fbox{
  6427. \begin{minipage}{0.96\textwidth}
  6428. \[
  6429. \begin{array}{lcl}
  6430. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  6431. \LangXGlobal{} &::= & \gray{ \key{.globl main} }\\
  6432. & & \gray{ \key{main:} \; \Instr\ldots }
  6433. \end{array}
  6434. \]
  6435. \end{minipage}
  6436. }
  6437. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  6438. \label{fig:x86-2-concrete}
  6439. \end{figure}
  6440. \begin{figure}[tp]
  6441. \fbox{
  6442. \begin{minipage}{0.96\textwidth}
  6443. \small
  6444. \[
  6445. \begin{array}{lcl}
  6446. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6447. \mid \BYTEREG{\Reg}} \\
  6448. &\mid& (\key{Global}~\Var) \\
  6449. \LangXGlobal{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  6450. \end{array}
  6451. \]
  6452. \end{minipage}
  6453. }
  6454. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  6455. \label{fig:x86-2}
  6456. \end{figure}
  6457. The concrete and abstract syntax of the \LangXGlobal{} language is
  6458. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  6459. differs from \LangXIf{} just in the addition of the form for global
  6460. variables.
  6461. %
  6462. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  6463. \code{select-instructions} pass on the running example.
  6464. \begin{figure}[tbp]
  6465. \centering
  6466. % tests/s2_17.rkt
  6467. \begin{minipage}[t]{0.5\textwidth}
  6468. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6469. block35:
  6470. movq free_ptr(%rip), alloc9024
  6471. addq $16, free_ptr(%rip)
  6472. movq alloc9024, %r11
  6473. movq $131, 0(%r11)
  6474. movq alloc9024, %r11
  6475. movq vecinit9025, 8(%r11)
  6476. movq $0, initret9026
  6477. movq alloc9024, %r11
  6478. movq 8(%r11), tmp9034
  6479. movq tmp9034, %r11
  6480. movq 8(%r11), %rax
  6481. jmp conclusion
  6482. block36:
  6483. movq $0, collectret9027
  6484. jmp block35
  6485. block38:
  6486. movq free_ptr(%rip), alloc9020
  6487. addq $16, free_ptr(%rip)
  6488. movq alloc9020, %r11
  6489. movq $3, 0(%r11)
  6490. movq alloc9020, %r11
  6491. movq vecinit9021, 8(%r11)
  6492. movq $0, initret9022
  6493. movq alloc9020, vecinit9025
  6494. movq free_ptr(%rip), tmp9031
  6495. movq tmp9031, tmp9032
  6496. addq $16, tmp9032
  6497. movq fromspace_end(%rip), tmp9033
  6498. cmpq tmp9033, tmp9032
  6499. jl block36
  6500. jmp block37
  6501. block37:
  6502. movq %r15, %rdi
  6503. movq $16, %rsi
  6504. callq 'collect
  6505. jmp block35
  6506. block39:
  6507. movq $0, collectret9023
  6508. jmp block38
  6509. \end{lstlisting}
  6510. \end{minipage}
  6511. \begin{minipage}[t]{0.45\textwidth}
  6512. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6513. start:
  6514. movq $42, vecinit9021
  6515. movq free_ptr(%rip), tmp9028
  6516. movq tmp9028, tmp9029
  6517. addq $16, tmp9029
  6518. movq fromspace_end(%rip), tmp9030
  6519. cmpq tmp9030, tmp9029
  6520. jl block39
  6521. jmp block40
  6522. block40:
  6523. movq %r15, %rdi
  6524. movq $16, %rsi
  6525. callq 'collect
  6526. jmp block38
  6527. \end{lstlisting}
  6528. \end{minipage}
  6529. \caption{Output of the \code{select-instructions} pass.}
  6530. \label{fig:select-instr-output-gc}
  6531. \end{figure}
  6532. \clearpage
  6533. \section{Register Allocation}
  6534. \label{sec:reg-alloc-gc}
  6535. \index{register allocation}
  6536. As discussed earlier in this chapter, the garbage collector needs to
  6537. access all the pointers in the root set, that is, all variables that
  6538. are vectors. It will be the responsibility of the register allocator
  6539. to make sure that:
  6540. \begin{enumerate}
  6541. \item the root stack is used for spilling vector-typed variables, and
  6542. \item if a vector-typed variable is live during a call to the
  6543. collector, it must be spilled to ensure it is visible to the
  6544. collector.
  6545. \end{enumerate}
  6546. The later responsibility can be handled during construction of the
  6547. interference graph, by adding interference edges between the call-live
  6548. vector-typed variables and all the callee-saved registers. (They
  6549. already interfere with the caller-saved registers.) The type
  6550. information for variables is in the \code{Program} form, so we
  6551. recommend adding another parameter to the \code{build-interference}
  6552. function to communicate this alist.
  6553. The spilling of vector-typed variables to the root stack can be
  6554. handled after graph coloring, when choosing how to assign the colors
  6555. (integers) to registers and stack locations. The \code{Program} output
  6556. of this pass changes to also record the number of spills to the root
  6557. stack.
  6558. % build-interference
  6559. %
  6560. % callq
  6561. % extra parameter for var->type assoc. list
  6562. % update 'program' and 'if'
  6563. % allocate-registers
  6564. % allocate spilled vectors to the rootstack
  6565. % don't change color-graph
  6566. \section{Print x86}
  6567. \label{sec:print-x86-gc}
  6568. \index{prelude}\index{conclusion}
  6569. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  6570. \code{print-x86} pass on the running example. In the prelude and
  6571. conclusion of the \code{main} function, we treat the root stack very
  6572. much like the regular stack in that we move the root stack pointer
  6573. (\code{r15}) to make room for the spills to the root stack, except
  6574. that the root stack grows up instead of down. For the running
  6575. example, there was just one spill so we increment \code{r15} by 8
  6576. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  6577. One issue that deserves special care is that there may be a call to
  6578. \code{collect} prior to the initializing assignments for all the
  6579. variables in the root stack. We do not want the garbage collector to
  6580. accidentally think that some uninitialized variable is a pointer that
  6581. needs to be followed. Thus, we zero-out all locations on the root
  6582. stack in the prelude of \code{main}. In
  6583. Figure~\ref{fig:print-x86-output-gc}, the instruction
  6584. %
  6585. \lstinline{movq $0, (%r15)}
  6586. %
  6587. accomplishes this task. The garbage collector tests each root to see
  6588. if it is null prior to dereferencing it.
  6589. \begin{figure}[htbp]
  6590. \begin{minipage}[t]{0.5\textwidth}
  6591. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6592. block35:
  6593. movq free_ptr(%rip), %rcx
  6594. addq $16, free_ptr(%rip)
  6595. movq %rcx, %r11
  6596. movq $131, 0(%r11)
  6597. movq %rcx, %r11
  6598. movq -8(%r15), %rax
  6599. movq %rax, 8(%r11)
  6600. movq $0, %rdx
  6601. movq %rcx, %r11
  6602. movq 8(%r11), %rcx
  6603. movq %rcx, %r11
  6604. movq 8(%r11), %rax
  6605. jmp conclusion
  6606. block36:
  6607. movq $0, %rcx
  6608. jmp block35
  6609. block38:
  6610. movq free_ptr(%rip), %rcx
  6611. addq $16, free_ptr(%rip)
  6612. movq %rcx, %r11
  6613. movq $3, 0(%r11)
  6614. movq %rcx, %r11
  6615. movq %rbx, 8(%r11)
  6616. movq $0, %rdx
  6617. movq %rcx, -8(%r15)
  6618. movq free_ptr(%rip), %rcx
  6619. addq $16, %rcx
  6620. movq fromspace_end(%rip), %rdx
  6621. cmpq %rdx, %rcx
  6622. jl block36
  6623. movq %r15, %rdi
  6624. movq $16, %rsi
  6625. callq collect
  6626. jmp block35
  6627. block39:
  6628. movq $0, %rcx
  6629. jmp block38
  6630. \end{lstlisting}
  6631. \end{minipage}
  6632. \begin{minipage}[t]{0.45\textwidth}
  6633. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6634. start:
  6635. movq $42, %rbx
  6636. movq free_ptr(%rip), %rdx
  6637. addq $16, %rdx
  6638. movq fromspace_end(%rip), %rcx
  6639. cmpq %rcx, %rdx
  6640. jl block39
  6641. movq %r15, %rdi
  6642. movq $16, %rsi
  6643. callq collect
  6644. jmp block38
  6645. .globl main
  6646. main:
  6647. pushq %rbp
  6648. movq %rsp, %rbp
  6649. pushq %r13
  6650. pushq %r12
  6651. pushq %rbx
  6652. pushq %r14
  6653. subq $0, %rsp
  6654. movq $16384, %rdi
  6655. movq $16384, %rsi
  6656. callq initialize
  6657. movq rootstack_begin(%rip), %r15
  6658. movq $0, (%r15)
  6659. addq $8, %r15
  6660. jmp start
  6661. conclusion:
  6662. subq $8, %r15
  6663. addq $0, %rsp
  6664. popq %r14
  6665. popq %rbx
  6666. popq %r12
  6667. popq %r13
  6668. popq %rbp
  6669. retq
  6670. \end{lstlisting}
  6671. \end{minipage}
  6672. \caption{Output of the \code{print-x86} pass.}
  6673. \label{fig:print-x86-output-gc}
  6674. \end{figure}
  6675. \begin{figure}[p]
  6676. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6677. \node (Rvec) at (0,2) {\large \LangVec{}};
  6678. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  6679. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  6680. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  6681. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  6682. \node (C2-4) at (3,0) {\large \LangCVec{}};
  6683. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  6684. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  6685. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  6686. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  6687. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  6688. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  6689. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  6690. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  6691. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  6692. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  6693. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  6694. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  6695. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  6696. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6697. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6698. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6699. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6700. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  6701. \end{tikzpicture}
  6702. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  6703. \label{fig:Rvec-passes}
  6704. \end{figure}
  6705. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  6706. for the compilation of \LangVec{}.
  6707. \section{Challenge: Simple Structures}
  6708. \label{sec:simple-structures}
  6709. \index{struct}
  6710. \index{structure}
  6711. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6712. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  6713. Recall that a \code{struct} in Typed Racket is a user-defined data
  6714. type that contains named fields and that is heap allocated, similar to
  6715. a vector. The following is an example of a structure definition, in
  6716. this case the definition of a \code{point} type.
  6717. \begin{lstlisting}
  6718. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6719. \end{lstlisting}
  6720. \begin{figure}[tbp]
  6721. \centering
  6722. \fbox{
  6723. \begin{minipage}{0.96\textwidth}
  6724. \[
  6725. \begin{array}{lcl}
  6726. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6727. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6728. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6729. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6730. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6731. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6732. \mid (\key{and}\;\Exp\;\Exp)
  6733. \mid (\key{or}\;\Exp\;\Exp)
  6734. \mid (\key{not}\;\Exp) } \\
  6735. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6736. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6737. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6738. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6739. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6740. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6741. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6742. \LangStruct{} &::=& \Def \ldots \; \Exp
  6743. \end{array}
  6744. \]
  6745. \end{minipage}
  6746. }
  6747. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  6748. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6749. \label{fig:r3s-concrete-syntax}
  6750. \end{figure}
  6751. An instance of a structure is created using function call syntax, with
  6752. the name of the structure in the function position:
  6753. \begin{lstlisting}
  6754. (point 7 12)
  6755. \end{lstlisting}
  6756. Function-call syntax is also used to read the value in a field of a
  6757. structure. The function name is formed by the structure name, a dash,
  6758. and the field name. The following example uses \code{point-x} and
  6759. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6760. instances.
  6761. \begin{center}
  6762. \begin{lstlisting}
  6763. (let ([pt1 (point 7 12)])
  6764. (let ([pt2 (point 4 3)])
  6765. (+ (- (point-x pt1) (point-x pt2))
  6766. (- (point-y pt1) (point-y pt2)))))
  6767. \end{lstlisting}
  6768. \end{center}
  6769. Similarly, to write to a field of a structure, use its set function,
  6770. whose name starts with \code{set-}, followed by the structure name,
  6771. then a dash, then the field name, and concluded with an exclamation
  6772. mark. The following example uses \code{set-point-x!} to change the
  6773. \code{x} field from \code{7} to \code{42}.
  6774. \begin{center}
  6775. \begin{lstlisting}
  6776. (let ([pt (point 7 12)])
  6777. (let ([_ (set-point-x! pt 42)])
  6778. (point-x pt)))
  6779. \end{lstlisting}
  6780. \end{center}
  6781. \begin{exercise}\normalfont
  6782. Extend your compiler with support for simple structures, compiling
  6783. \LangStruct{} to x86 assembly code. Create five new test cases that use
  6784. structures and test your compiler.
  6785. \end{exercise}
  6786. \section{Challenge: Generational Collection}
  6787. The copying collector described in Section~\ref{sec:GC} can incur
  6788. significant runtime overhead because the call to \code{collect} takes
  6789. time proportional to all of the live data. One way to reduce this
  6790. overhead is to reduce how much data is inspected in each call to
  6791. \code{collect}. In particular, researchers have observed that recently
  6792. allocated data is more likely to become garbage then data that has
  6793. survived one or more previous calls to \code{collect}. This insight
  6794. motivated the creation of \emph{generational garbage collectors}
  6795. \index{generational garbage collector} that
  6796. 1) segregates data according to its age into two or more generations,
  6797. 2) allocates less space for younger generations, so collecting them is
  6798. faster, and more space for the older generations, and 3) performs
  6799. collection on the younger generations more frequently then for older
  6800. generations~\citep{Wilson:1992fk}.
  6801. For this challenge assignment, the goal is to adapt the copying
  6802. collector implemented in \code{runtime.c} to use two generations, one
  6803. for young data and one for old data. Each generation consists of a
  6804. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6805. \code{collect} function to use the two generations.
  6806. \begin{enumerate}
  6807. \item Copy the young generation's FromSpace to its ToSpace then switch
  6808. the role of the ToSpace and FromSpace
  6809. \item If there is enough space for the requested number of bytes in
  6810. the young FromSpace, then return from \code{collect}.
  6811. \item If there is not enough space in the young FromSpace for the
  6812. requested bytes, then move the data from the young generation to the
  6813. old one with the following steps:
  6814. \begin{enumerate}
  6815. \item If there is enough room in the old FromSpace, copy the young
  6816. FromSpace to the old FromSpace and then return.
  6817. \item If there is not enough room in the old FromSpace, then collect
  6818. the old generation by copying the old FromSpace to the old ToSpace
  6819. and swap the roles of the old FromSpace and ToSpace.
  6820. \item If there is enough room now, copy the young FromSpace to the
  6821. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6822. and ToSpace for the old generation. Copy the young FromSpace and
  6823. the old FromSpace into the larger FromSpace for the old
  6824. generation and then return.
  6825. \end{enumerate}
  6826. \end{enumerate}
  6827. We recommend that you generalize the \code{cheney} function so that it
  6828. can be used for all the copies mentioned above: between the young
  6829. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6830. between the young FromSpace and old FromSpace. This can be
  6831. accomplished by adding parameters to \code{cheney} that replace its
  6832. use of the global variables \code{fromspace\_begin},
  6833. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6834. Note that the collection of the young generation does not traverse the
  6835. old generation. This introduces a potential problem: there may be
  6836. young data that is only reachable through pointers in the old
  6837. generation. If these pointers are not taken into account, the
  6838. collector could throw away young data that is live! One solution,
  6839. called \emph{pointer recording}, is to maintain a set of all the
  6840. pointers from the old generation into the new generation and consider
  6841. this set as part of the root set. To maintain this set, the compiler
  6842. must insert extra instructions around every \code{vector-set!}. If the
  6843. vector being modified is in the old generation, and if the value being
  6844. written is a pointer into the new generation, than that pointer must
  6845. be added to the set. Also, if the value being overwritten was a
  6846. pointer into the new generation, then that pointer should be removed
  6847. from the set.
  6848. \begin{exercise}\normalfont
  6849. Adapt the \code{collect} function in \code{runtime.c} to implement
  6850. generational garbage collection, as outlined in this section.
  6851. Update the code generation for \code{vector-set!} to implement
  6852. pointer recording. Make sure that your new compiler and runtime
  6853. passes your test suite.
  6854. \end{exercise}
  6855. % Further Reading
  6856. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6857. \chapter{Functions}
  6858. \label{ch:Rfun}
  6859. \index{function}
  6860. This chapter studies the compilation of functions similar to those
  6861. found in the C language. This corresponds to a subset of Typed Racket
  6862. in which only top-level function definitions are allowed. This kind of
  6863. function is an important stepping stone to implementing
  6864. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6865. is the topic of Chapter~\ref{ch:Rlam}.
  6866. \section{The \LangFun{} Language}
  6867. The concrete and abstract syntax for function definitions and function
  6868. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  6869. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  6870. \LangFun{} begin with zero or more function definitions. The function
  6871. names from these definitions are in-scope for the entire program,
  6872. including all other function definitions (so the ordering of function
  6873. definitions does not matter). The concrete syntax for function
  6874. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6875. where the first expression must
  6876. evaluate to a function and the rest are the arguments.
  6877. The abstract syntax for function application is
  6878. $\APPLY{\Exp}{\Exp\ldots}$.
  6879. %% The syntax for function application does not include an explicit
  6880. %% keyword, which is error prone when using \code{match}. To alleviate
  6881. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6882. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6883. Functions are first-class in the sense that a function pointer
  6884. \index{function pointer} is data and can be stored in memory or passed
  6885. as a parameter to another function. Thus, we introduce a function
  6886. type, written
  6887. \begin{lstlisting}
  6888. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6889. \end{lstlisting}
  6890. for a function whose $n$ parameters have the types $\Type_1$ through
  6891. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6892. these functions (with respect to Racket functions) is that they are
  6893. not lexically scoped. That is, the only external entities that can be
  6894. referenced from inside a function body are other globally-defined
  6895. functions. The syntax of \LangFun{} prevents functions from being nested
  6896. inside each other.
  6897. \begin{figure}[tp]
  6898. \centering
  6899. \fbox{
  6900. \begin{minipage}{0.96\textwidth}
  6901. \small
  6902. \[
  6903. \begin{array}{lcl}
  6904. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6905. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6906. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6907. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6908. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6909. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6910. \mid (\key{and}\;\Exp\;\Exp)
  6911. \mid (\key{or}\;\Exp\;\Exp)
  6912. \mid (\key{not}\;\Exp)} \\
  6913. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6914. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6915. (\key{vector-ref}\;\Exp\;\Int)} \\
  6916. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6917. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6918. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6919. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6920. \LangFun{} &::=& \Def \ldots \; \Exp
  6921. \end{array}
  6922. \]
  6923. \end{minipage}
  6924. }
  6925. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6926. \label{fig:Rfun-concrete-syntax}
  6927. \end{figure}
  6928. \begin{figure}[tp]
  6929. \centering
  6930. \fbox{
  6931. \begin{minipage}{0.96\textwidth}
  6932. \small
  6933. \[
  6934. \begin{array}{lcl}
  6935. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6936. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6937. &\mid& \gray{ \BOOL{\itm{bool}}
  6938. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6939. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6940. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6941. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6942. \LangFun{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6943. \end{array}
  6944. \]
  6945. \end{minipage}
  6946. }
  6947. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  6948. \label{fig:Rfun-syntax}
  6949. \end{figure}
  6950. The program in Figure~\ref{fig:Rfun-function-example} is a
  6951. representative example of defining and using functions in \LangFun{}. We
  6952. define a function \code{map-vec} that applies some other function
  6953. \code{f} to both elements of a vector and returns a new
  6954. vector containing the results. We also define a function \code{add1}.
  6955. The program applies
  6956. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6957. \code{(vector 1 42)}, from which we return the \code{42}.
  6958. \begin{figure}[tbp]
  6959. \begin{lstlisting}
  6960. (define (map-vec [f : (Integer -> Integer)]
  6961. [v : (Vector Integer Integer)])
  6962. : (Vector Integer Integer)
  6963. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6964. (define (add1 [x : Integer]) : Integer
  6965. (+ x 1))
  6966. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6967. \end{lstlisting}
  6968. \caption{Example of using functions in \LangFun{}.}
  6969. \label{fig:Rfun-function-example}
  6970. \end{figure}
  6971. The definitional interpreter for \LangFun{} is in
  6972. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  6973. responsible for setting up the mutual recursion between the top-level
  6974. function definitions. We use the classic back-patching \index{back-patching}
  6975. approach that uses mutable variables and makes two passes over the function
  6976. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6977. top-level environment using a mutable cons cell for each function
  6978. definition. Note that the \code{lambda} value for each function is
  6979. incomplete; it does not yet include the environment. Once the
  6980. top-level environment is constructed, we then iterate over it and
  6981. update the \code{lambda} values to use the top-level environment.
  6982. \begin{figure}[tp]
  6983. \begin{lstlisting}
  6984. (define interp-Rfun-class
  6985. (class interp-Rvec-class
  6986. (super-new)
  6987. (define/override ((interp-exp env) e)
  6988. (define recur (interp-exp env))
  6989. (match e
  6990. [(Var x) (unbox (dict-ref env x))]
  6991. [(Let x e body)
  6992. (define new-env (dict-set env x (box (recur e))))
  6993. ((interp-exp new-env) body)]
  6994. [(Apply fun args)
  6995. (define fun-val (recur fun))
  6996. (define arg-vals (for/list ([e args]) (recur e)))
  6997. (match fun-val
  6998. [`(function (,xs ...) ,body ,fun-env)
  6999. (define params-args (for/list ([x xs] [arg arg-vals])
  7000. (cons x (box arg))))
  7001. (define new-env (append params-args fun-env))
  7002. ((interp-exp new-env) body)]
  7003. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  7004. [else ((super interp-exp env) e)]
  7005. ))
  7006. (define/public (interp-def d)
  7007. (match d
  7008. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  7009. (cons f (box `(function ,xs ,body ())))]))
  7010. (define/override (interp-program p)
  7011. (match p
  7012. [(ProgramDefsExp info ds body)
  7013. (let ([top-level (for/list ([d ds]) (interp-def d))])
  7014. (for/list ([f (in-dict-values top-level)])
  7015. (set-box! f (match (unbox f)
  7016. [`(function ,xs ,body ())
  7017. `(function ,xs ,body ,top-level)])))
  7018. ((interp-exp top-level) body))]))
  7019. ))
  7020. (define (interp-Rfun p)
  7021. (send (new interp-Rfun-class) interp-program p))
  7022. \end{lstlisting}
  7023. \caption{Interpreter for the \LangFun{} language.}
  7024. \label{fig:interp-Rfun}
  7025. \end{figure}
  7026. \margincomment{TODO: explain type checker}
  7027. The type checker for \LangFun{} is is in Figure~\ref{fig:type-check-Rfun}.
  7028. \begin{figure}[tp]
  7029. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7030. (define type-check-Rfun-class
  7031. (class type-check-Rvec-class
  7032. (super-new)
  7033. (inherit check-type-equal?)
  7034. (define/public (type-check-apply env e es)
  7035. (define-values (e^ ty) ((type-check-exp env) e))
  7036. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  7037. ((type-check-exp env) e)))
  7038. (match ty
  7039. [`(,ty^* ... -> ,rt)
  7040. (for ([arg-ty ty*] [param-ty ty^*])
  7041. (check-type-equal? arg-ty param-ty (Apply e es)))
  7042. (values e^ e* rt)]))
  7043. (define/override (type-check-exp env)
  7044. (lambda (e)
  7045. (match e
  7046. [(FunRef f)
  7047. (values (FunRef f) (dict-ref env f))]
  7048. [(Apply e es)
  7049. (define-values (e^ es^ rt) (type-check-apply env e es))
  7050. (values (Apply e^ es^) rt)]
  7051. [(Call e es)
  7052. (define-values (e^ es^ rt) (type-check-apply env e es))
  7053. (values (Call e^ es^) rt)]
  7054. [else ((super type-check-exp env) e)])))
  7055. (define/public (type-check-def env)
  7056. (lambda (e)
  7057. (match e
  7058. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  7059. (define new-env (append (map cons xs ps) env))
  7060. (define-values (body^ ty^) ((type-check-exp new-env) body))
  7061. (check-type-equal? ty^ rt body)
  7062. (Def f p:t* rt info body^)])))
  7063. (define/public (fun-def-type d)
  7064. (match d
  7065. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  7066. (define/override (type-check-program e)
  7067. (match e
  7068. [(ProgramDefsExp info ds body)
  7069. (define new-env (for/list ([d ds])
  7070. (cons (Def-name d) (fun-def-type d))))
  7071. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  7072. (define-values (body^ ty) ((type-check-exp new-env) body))
  7073. (check-type-equal? ty 'Integer body)
  7074. (ProgramDefsExp info ds^ body^)]))))
  7075. (define (type-check-Rfun p)
  7076. (send (new type-check-Rfun-class) type-check-program p))
  7077. \end{lstlisting}
  7078. \caption{Type checker for the \LangFun{} language.}
  7079. \label{fig:type-check-Rfun}
  7080. \end{figure}
  7081. \section{Functions in x86}
  7082. \label{sec:fun-x86}
  7083. \margincomment{\tiny Make sure callee-saved registers are discussed
  7084. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  7085. \margincomment{\tiny Talk about the return address on the
  7086. stack and what callq and retq does.\\ --Jeremy }
  7087. The x86 architecture provides a few features to support the
  7088. implementation of functions. We have already seen that x86 provides
  7089. labels so that one can refer to the location of an instruction, as is
  7090. needed for jump instructions. Labels can also be used to mark the
  7091. beginning of the instructions for a function. Going further, we can
  7092. obtain the address of a label by using the \key{leaq} instruction and
  7093. PC-relative addressing. For example, the following puts the
  7094. address of the \code{add1} label into the \code{rbx} register.
  7095. \begin{lstlisting}
  7096. leaq add1(%rip), %rbx
  7097. \end{lstlisting}
  7098. The instruction pointer register \key{rip} (aka. the program counter
  7099. \index{program counter}) always points to the next instruction to be
  7100. executed. When combined with an label, as in \code{add1(\%rip)}, the
  7101. linker computes the distance $d$ between the address of \code{add1}
  7102. and where the \code{rip} would be at that moment and then changes
  7103. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  7104. the address of \code{add1}.
  7105. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  7106. jump to a function whose location is given by a label. To support
  7107. function calls in this chapter we instead will be jumping to a
  7108. function whose location is given by an address in a register, that is,
  7109. we need to make an \emph{indirect function call}. The x86 syntax for
  7110. this is a \code{callq} instruction but with an asterisk before the
  7111. register name.\index{indirect function call}
  7112. \begin{lstlisting}
  7113. callq *%rbx
  7114. \end{lstlisting}
  7115. \subsection{Calling Conventions}
  7116. \index{calling conventions}
  7117. The \code{callq} instruction provides partial support for implementing
  7118. functions: it pushes the return address on the stack and it jumps to
  7119. the target. However, \code{callq} does not handle
  7120. \begin{enumerate}
  7121. \item parameter passing,
  7122. \item pushing frames on the procedure call stack and popping them off,
  7123. or
  7124. \item determining how registers are shared by different functions.
  7125. \end{enumerate}
  7126. Regarding (1) parameter passing, recall that the following six
  7127. registers are used to pass arguments to a function, in this order.
  7128. \begin{lstlisting}
  7129. rdi rsi rdx rcx r8 r9
  7130. \end{lstlisting}
  7131. If there are
  7132. more than six arguments, then the convention is to use space on the
  7133. frame of the caller for the rest of the arguments. However, to ease
  7134. the implementation of efficient tail calls
  7135. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  7136. arguments.
  7137. %
  7138. Also recall that the register \code{rax} is for the return value of
  7139. the function.
  7140. \index{prelude}\index{conclusion}
  7141. Regarding (2) frames \index{frame} and the procedure call stack,
  7142. \index{procedure call stack} recall from Section~\ref{sec:x86} that
  7143. the stack grows down, with each function call using a chunk of space
  7144. called a frame. The caller sets the stack pointer, register
  7145. \code{rsp}, to the last data item in its frame. The callee must not
  7146. change anything in the caller's frame, that is, anything that is at or
  7147. above the stack pointer. The callee is free to use locations that are
  7148. below the stack pointer.
  7149. Recall that we are storing variables of vector type on the root stack.
  7150. So the prelude needs to move the root stack pointer \code{r15} up and
  7151. the conclusion needs to move the root stack pointer back down. Also,
  7152. the prelude must initialize to \code{0} this frame's slots in the root
  7153. stack to signal to the garbage collector that those slots do not yet
  7154. contain a pointer to a vector. Otherwise the garbage collector will
  7155. interpret the garbage bits in those slots as memory addresses and try
  7156. to traverse them, causing serious mayhem!
  7157. Regarding (3) the sharing of registers between different functions,
  7158. recall from Section~\ref{sec:calling-conventions} that the registers
  7159. are divided into two groups, the caller-saved registers and the
  7160. callee-saved registers. The caller should assume that all the
  7161. caller-saved registers get overwritten with arbitrary values by the
  7162. callee. That is why we recommend in
  7163. Section~\ref{sec:calling-conventions} that variables that are live
  7164. during a function call should not be assigned to caller-saved
  7165. registers.
  7166. On the flip side, if the callee wants to use a callee-saved register,
  7167. the callee must save the contents of those registers on their stack
  7168. frame and then put them back prior to returning to the caller. That
  7169. is why we recommended in Section~\ref{sec:calling-conventions} that if
  7170. the register allocator assigns a variable to a callee-saved register,
  7171. then the prelude of the \code{main} function must save that register
  7172. to the stack and the conclusion of \code{main} must restore it. This
  7173. recommendation now generalizes to all functions.
  7174. Also recall that the base pointer, register \code{rbp}, is used as a
  7175. point-of-reference within a frame, so that each local variable can be
  7176. accessed at a fixed offset from the base pointer
  7177. (Section~\ref{sec:x86}).
  7178. %
  7179. Figure~\ref{fig:call-frames} shows the general layout of the caller
  7180. and callee frames.
  7181. \begin{figure}[tbp]
  7182. \centering
  7183. \begin{tabular}{r|r|l|l} \hline
  7184. Caller View & Callee View & Contents & Frame \\ \hline
  7185. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  7186. 0(\key{\%rbp}) & & old \key{rbp} \\
  7187. -8(\key{\%rbp}) & & callee-saved $1$ \\
  7188. \ldots & & \ldots \\
  7189. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  7190. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  7191. \ldots & & \ldots \\
  7192. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  7193. %% & & \\
  7194. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  7195. %% & \ldots & \ldots \\
  7196. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  7197. \hline
  7198. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  7199. & 0(\key{\%rbp}) & old \key{rbp} \\
  7200. & -8(\key{\%rbp}) & callee-saved $1$ \\
  7201. & \ldots & \ldots \\
  7202. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  7203. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  7204. & \ldots & \ldots \\
  7205. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  7206. \end{tabular}
  7207. \caption{Memory layout of caller and callee frames.}
  7208. \label{fig:call-frames}
  7209. \end{figure}
  7210. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  7211. %% local variables and for storing the values of callee-saved registers
  7212. %% (we shall refer to all of these collectively as ``locals''), and that
  7213. %% at the beginning of a function we move the stack pointer \code{rsp}
  7214. %% down to make room for them.
  7215. %% We recommend storing the local variables
  7216. %% first and then the callee-saved registers, so that the local variables
  7217. %% can be accessed using \code{rbp} the same as before the addition of
  7218. %% functions.
  7219. %% To make additional room for passing arguments, we shall
  7220. %% move the stack pointer even further down. We count how many stack
  7221. %% arguments are needed for each function call that occurs inside the
  7222. %% body of the function and find their maximum. Adding this number to the
  7223. %% number of locals gives us how much the \code{rsp} should be moved at
  7224. %% the beginning of the function. In preparation for a function call, we
  7225. %% offset from \code{rsp} to set up the stack arguments. We put the first
  7226. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  7227. %% so on.
  7228. %% Upon calling the function, the stack arguments are retrieved by the
  7229. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  7230. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  7231. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  7232. %% the layout of the caller and callee frames. Notice how important it is
  7233. %% that we correctly compute the maximum number of arguments needed for
  7234. %% function calls; if that number is too small then the arguments and
  7235. %% local variables will smash into each other!
  7236. \subsection{Efficient Tail Calls}
  7237. \label{sec:tail-call}
  7238. In general, the amount of stack space used by a program is determined
  7239. by the longest chain of nested function calls. That is, if function
  7240. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  7241. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  7242. $n$ can grow quite large in the case of recursive or mutually
  7243. recursive functions. However, in some cases we can arrange to use only
  7244. constant space, i.e. $O(1)$, instead of $O(n)$.
  7245. If a function call is the last action in a function body, then that
  7246. call is said to be a \emph{tail call}\index{tail call}.
  7247. For example, in the following
  7248. program, the recursive call to \code{tail-sum} is a tail call.
  7249. \begin{center}
  7250. \begin{lstlisting}
  7251. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  7252. (if (eq? n 0)
  7253. r
  7254. (tail-sum (- n 1) (+ n r))))
  7255. (+ (tail-sum 5 0) 27)
  7256. \end{lstlisting}
  7257. \end{center}
  7258. At a tail call, the frame of the caller is no longer needed, so we
  7259. can pop the caller's frame before making the tail call. With this
  7260. approach, a recursive function that only makes tail calls will only
  7261. use $O(1)$ stack space. Functional languages like Racket typically
  7262. rely heavily on recursive functions, so they typically guarantee that
  7263. all tail calls will be optimized in this way.
  7264. \index{frame}
  7265. However, some care is needed with regards to argument passing in tail
  7266. calls. As mentioned above, for arguments beyond the sixth, the
  7267. convention is to use space in the caller's frame for passing
  7268. arguments. But for a tail call we pop the caller's frame and can no
  7269. longer use it. Another alternative is to use space in the callee's
  7270. frame for passing arguments. However, this option is also problematic
  7271. because the caller and callee's frame overlap in memory. As we begin
  7272. to copy the arguments from their sources in the caller's frame, the
  7273. target locations in the callee's frame might overlap with the sources
  7274. for later arguments! We solve this problem by not using the stack for
  7275. passing more than six arguments but instead using the heap, as we
  7276. describe in the Section~\ref{sec:limit-functions-r4}.
  7277. As mentioned above, for a tail call we pop the caller's frame prior to
  7278. making the tail call. The instructions for popping a frame are the
  7279. instructions that we usually place in the conclusion of a
  7280. function. Thus, we also need to place such code immediately before
  7281. each tail call. These instructions include restoring the callee-saved
  7282. registers, so it is good that the argument passing registers are all
  7283. caller-saved registers.
  7284. One last note regarding which instruction to use to make the tail
  7285. call. When the callee is finished, it should not return to the current
  7286. function, but it should return to the function that called the current
  7287. one. Thus, the return address that is already on the stack is the
  7288. right one, and we should not use \key{callq} to make the tail call, as
  7289. that would unnecessarily overwrite the return address. Instead we can
  7290. simply use the \key{jmp} instruction. Like the indirect function call,
  7291. we write an \emph{indirect jump}\index{indirect jump} with a register
  7292. prefixed with an asterisk. We recommend using \code{rax} to hold the
  7293. jump target because the preceding conclusion overwrites just about
  7294. everything else.
  7295. \begin{lstlisting}
  7296. jmp *%rax
  7297. \end{lstlisting}
  7298. \section{Shrink \LangFun{}}
  7299. \label{sec:shrink-r4}
  7300. The \code{shrink} pass performs a minor modification to ease the
  7301. later passes. This pass introduces an explicit \code{main} function
  7302. and changes the top \code{ProgramDefsExp} form to
  7303. \code{ProgramDefs} as follows.
  7304. \begin{lstlisting}
  7305. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  7306. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  7307. \end{lstlisting}
  7308. where $\itm{mainDef}$ is
  7309. \begin{lstlisting}
  7310. (Def 'main '() 'Integer '() |$\Exp'$|)
  7311. \end{lstlisting}
  7312. \section{Reveal Functions and the \LangFunRef{} language}
  7313. \label{sec:reveal-functions-r4}
  7314. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  7315. respect: it conflates the use of function names and local
  7316. variables. This is a problem because we need to compile the use of a
  7317. function name differently than the use of a local variable; we need to
  7318. use \code{leaq} to convert the function name (a label in x86) to an
  7319. address in a register. Thus, it is a good idea to create a new pass
  7320. that changes function references from just a symbol $f$ to
  7321. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  7322. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  7323. The concrete syntax for a function reference is $\CFUNREF{f}$.
  7324. \begin{figure}[tp]
  7325. \centering
  7326. \fbox{
  7327. \begin{minipage}{0.96\textwidth}
  7328. \[
  7329. \begin{array}{lcl}
  7330. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  7331. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7332. \LangFunRef{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  7333. \end{array}
  7334. \]
  7335. \end{minipage}
  7336. }
  7337. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  7338. (Figure~\ref{fig:Rfun-syntax}).}
  7339. \label{fig:f1-syntax}
  7340. \end{figure}
  7341. %% Distinguishing between calls in tail position and non-tail position
  7342. %% requires the pass to have some notion of context. We recommend using
  7343. %% two mutually recursive functions, one for processing expressions in
  7344. %% tail position and another for the rest.
  7345. Placing this pass after \code{uniquify} will make sure that there are
  7346. no local variables and functions that share the same name. On the
  7347. other hand, \code{reveal-functions} needs to come before the
  7348. \code{explicate-control} pass because that pass helps us compile
  7349. \code{FunRef} forms into assignment statements.
  7350. \section{Limit Functions}
  7351. \label{sec:limit-functions-r4}
  7352. Recall that we wish to limit the number of function parameters to six
  7353. so that we do not need to use the stack for argument passing, which
  7354. makes it easier to implement efficient tail calls. However, because
  7355. the input language \LangFun{} supports arbitrary numbers of function
  7356. arguments, we have some work to do!
  7357. This pass transforms functions and function calls that involve more
  7358. than six arguments to pass the first five arguments as usual, but it
  7359. packs the rest of the arguments into a vector and passes it as the
  7360. sixth argument.
  7361. Each function definition with too many parameters is transformed as
  7362. follows.
  7363. \begin{lstlisting}
  7364. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  7365. |$\Rightarrow$|
  7366. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  7367. \end{lstlisting}
  7368. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  7369. the occurrences of the later parameters with vector references.
  7370. \begin{lstlisting}
  7371. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  7372. \end{lstlisting}
  7373. For function calls with too many arguments, the \code{limit-functions}
  7374. pass transforms them in the following way.
  7375. \begin{tabular}{lll}
  7376. \begin{minipage}{0.2\textwidth}
  7377. \begin{lstlisting}
  7378. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  7379. \end{lstlisting}
  7380. \end{minipage}
  7381. &
  7382. $\Rightarrow$
  7383. &
  7384. \begin{minipage}{0.4\textwidth}
  7385. \begin{lstlisting}
  7386. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  7387. \end{lstlisting}
  7388. \end{minipage}
  7389. \end{tabular}
  7390. \section{Remove Complex Operands}
  7391. \label{sec:rco-r4}
  7392. The primary decisions to make for this pass is whether to classify
  7393. \code{FunRef} and \code{Apply} as either atomic or complex
  7394. expressions. Recall that a simple expression will eventually end up as
  7395. just an immediate argument of an x86 instruction. Function
  7396. application will be translated to a sequence of instructions, so
  7397. \code{Apply} must be classified as complex expression.
  7398. On the other hand, the arguments of \code{Apply} should be
  7399. atomic expressions.
  7400. %
  7401. Regarding \code{FunRef}, as discussed above, the function label needs
  7402. to be converted to an address using the \code{leaq} instruction. Thus,
  7403. even though \code{FunRef} seems rather simple, it needs to be
  7404. classified as a complex expression so that we generate an assignment
  7405. statement with a left-hand side that can serve as the target of the
  7406. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  7407. output language \LangFunANF{} of this pass.
  7408. \begin{figure}[tp]
  7409. \centering
  7410. \fbox{
  7411. \begin{minipage}{0.96\textwidth}
  7412. \small
  7413. \[
  7414. \begin{array}{rcl}
  7415. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  7416. \mid \VOID{} } \\
  7417. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  7418. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  7419. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7420. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7421. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  7422. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  7423. \mid \LP\key{GlobalValue}~\Var\RP }\\
  7424. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  7425. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7426. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  7427. \end{array}
  7428. \]
  7429. \end{minipage}
  7430. }
  7431. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  7432. \label{fig:Rfun-anf-syntax}
  7433. \end{figure}
  7434. \section{Explicate Control and the \LangCFun{} language}
  7435. \label{sec:explicate-control-r4}
  7436. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  7437. output of \key{explicate-control}. (The concrete syntax is given in
  7438. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  7439. functions for assignment and tail contexts should be updated with
  7440. cases for \code{Apply} and \code{FunRef} and the function for
  7441. predicate context should be updated for \code{Apply} but not
  7442. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  7443. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  7444. tail position \code{Apply} becomes \code{TailCall}. We recommend
  7445. defining a new auxiliary function for processing function definitions.
  7446. This code is similar to the case for \code{Program} in \LangVec{}. The
  7447. top-level \code{explicate-control} function that handles the
  7448. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  7449. all the function definitions.
  7450. \begin{figure}[tp]
  7451. \fbox{
  7452. \begin{minipage}{0.96\textwidth}
  7453. \small
  7454. \[
  7455. \begin{array}{lcl}
  7456. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7457. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7458. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7459. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7460. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7461. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  7462. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  7463. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  7464. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  7465. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  7466. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7467. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7468. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7469. \mid \GOTO{\itm{label}} } \\
  7470. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7471. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  7472. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  7473. \LangCFun{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7474. \end{array}
  7475. \]
  7476. \end{minipage}
  7477. }
  7478. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  7479. \label{fig:c3-syntax}
  7480. \end{figure}
  7481. \section{Select Instructions and the \LangXIndCall{} Language}
  7482. \label{sec:select-r4}
  7483. \index{instruction selection}
  7484. The output of select instructions is a program in the \LangXIndCall{}
  7485. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  7486. \index{x86}
  7487. \begin{figure}[tp]
  7488. \fbox{
  7489. \begin{minipage}{0.96\textwidth}
  7490. \small
  7491. \[
  7492. \begin{array}{lcl}
  7493. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  7494. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  7495. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  7496. \Instr &::=& \ldots
  7497. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  7498. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  7499. \Block &::= & \Instr\ldots \\
  7500. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  7501. \LangXIndCall{} &::= & \Def\ldots
  7502. \end{array}
  7503. \]
  7504. \end{minipage}
  7505. }
  7506. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  7507. \label{fig:x86-3-concrete}
  7508. \end{figure}
  7509. \begin{figure}[tp]
  7510. \fbox{
  7511. \begin{minipage}{0.96\textwidth}
  7512. \small
  7513. \[
  7514. \begin{array}{lcl}
  7515. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7516. \mid \BYTEREG{\Reg} } \\
  7517. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  7518. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  7519. \mid \TAILJMP{\Arg}{\itm{int}}\\
  7520. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  7521. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  7522. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  7523. \LangXIndCall{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7524. \end{array}
  7525. \]
  7526. \end{minipage}
  7527. }
  7528. \caption{The abstract syntax of \LangXIndCall{} (extends
  7529. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  7530. \label{fig:x86-3}
  7531. \end{figure}
  7532. An assignment of a function reference to a variable becomes a
  7533. load-effective-address instruction as follows: \\
  7534. \begin{tabular}{lcl}
  7535. \begin{minipage}{0.35\textwidth}
  7536. \begin{lstlisting}
  7537. |$\itm{lhs}$| = (fun-ref |$f$|);
  7538. \end{lstlisting}
  7539. \end{minipage}
  7540. &
  7541. $\Rightarrow$\qquad\qquad
  7542. &
  7543. \begin{minipage}{0.3\textwidth}
  7544. \begin{lstlisting}
  7545. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  7546. \end{lstlisting}
  7547. \end{minipage}
  7548. \end{tabular} \\
  7549. Regarding function definitions, we need to remove the parameters and
  7550. instead perform parameter passing using the conventions discussed in
  7551. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  7552. registers. We recommend turning the parameters into local variables
  7553. and generating instructions at the beginning of the function to move
  7554. from the argument passing registers to these local variables.
  7555. \begin{lstlisting}
  7556. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  7557. |$\Rightarrow$|
  7558. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  7559. \end{lstlisting}
  7560. The $G'$ control-flow graph is the same as $G$ except that the
  7561. \code{start} block is modified to add the instructions for moving from
  7562. the argument registers to the parameter variables. So the \code{start}
  7563. block of $G$ shown on the left is changed to the code on the right.
  7564. \begin{center}
  7565. \begin{minipage}{0.3\textwidth}
  7566. \begin{lstlisting}
  7567. start:
  7568. |$\itm{instr}_1$|
  7569. |$\vdots$|
  7570. |$\itm{instr}_n$|
  7571. \end{lstlisting}
  7572. \end{minipage}
  7573. $\Rightarrow$
  7574. \begin{minipage}{0.3\textwidth}
  7575. \begin{lstlisting}
  7576. start:
  7577. movq %rdi, |$x_1$|
  7578. movq %rsi, |$x_2$|
  7579. |$\vdots$|
  7580. |$\itm{instr}_1$|
  7581. |$\vdots$|
  7582. |$\itm{instr}_n$|
  7583. \end{lstlisting}
  7584. \end{minipage}
  7585. \end{center}
  7586. By changing the parameters to local variables, we are giving the
  7587. register allocator control over which registers or stack locations to
  7588. use for them. If you implemented the move-biasing challenge
  7589. (Section~\ref{sec:move-biasing}), the register allocator will try to
  7590. assign the parameter variables to the corresponding argument register,
  7591. in which case the \code{patch-instructions} pass will remove the
  7592. \code{movq} instruction. This happens in the example translation in
  7593. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7594. the \code{add} function.
  7595. %
  7596. Also, note that the register allocator will perform liveness analysis
  7597. on this sequence of move instructions and build the interference
  7598. graph. So, for example, $x_1$ will be marked as interfering with
  7599. \code{rsi} and that will prevent the assignment of $x_1$ to
  7600. \code{rsi}, which is good, because that would overwrite the argument
  7601. that needs to move into $x_2$.
  7602. Next, consider the compilation of function calls. In the mirror image
  7603. of handling the parameters of function definitions, the arguments need
  7604. to be moved to the argument passing registers. The function call
  7605. itself is performed with an indirect function call. The return value
  7606. from the function is stored in \code{rax}, so it needs to be moved
  7607. into the \itm{lhs}.
  7608. \begin{lstlisting}
  7609. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7610. |$\Rightarrow$|
  7611. movq |$\itm{arg}_1$|, %rdi
  7612. movq |$\itm{arg}_2$|, %rsi
  7613. |$\vdots$|
  7614. callq *|\itm{fun}|
  7615. movq %rax, |\itm{lhs}|
  7616. \end{lstlisting}
  7617. The \code{IndirectCallq} AST node includes an integer for the arity of
  7618. the function, i.e., the number of parameters. That information is
  7619. useful in the \code{uncover-live} pass for determining which
  7620. argument-passing registers are potentially read during the call.
  7621. For tail calls, the parameter passing is the same as non-tail calls:
  7622. generate instructions to move the arguments into to the argument
  7623. passing registers. After that we need to pop the frame from the
  7624. procedure call stack. However, we do not yet know how big the frame
  7625. is; that gets determined during register allocation. So instead of
  7626. generating those instructions here, we invent a new instruction that
  7627. means ``pop the frame and then do an indirect jump'', which we name
  7628. \code{TailJmp}. The abstract syntax for this instruction includes an
  7629. argument that specifies where to jump and an integer that represents
  7630. the arity of the function being called.
  7631. Recall that in Section~\ref{sec:explicate-control-Rvar} we recommended
  7632. using the label \code{start} for the initial block of a program, and
  7633. in Section~\ref{sec:select-Rvar} we recommended labeling the conclusion
  7634. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7635. can be compiled to an assignment to \code{rax} followed by a jump to
  7636. \code{conclusion}. With the addition of function definitions, we will
  7637. have a starting block and conclusion for each function, but their
  7638. labels need to be unique. We recommend prepending the function's name
  7639. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7640. labels. (Alternatively, one could \code{gensym} labels for the start
  7641. and conclusion and store them in the $\itm{info}$ field of the
  7642. function definition.)
  7643. \section{Register Allocation}
  7644. \label{sec:register-allocation-r4}
  7645. \subsection{Liveness Analysis}
  7646. \label{sec:liveness-analysis-r4}
  7647. \index{liveness analysis}
  7648. %% The rest of the passes need only minor modifications to handle the new
  7649. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7650. %% \code{leaq}.
  7651. The \code{IndirectCallq} instruction should be treated like
  7652. \code{Callq} regarding its written locations $W$, in that they should
  7653. include all the caller-saved registers. Recall that the reason for
  7654. that is to force call-live variables to be assigned to callee-saved
  7655. registers or to be spilled to the stack.
  7656. Regarding the set of read locations $R$ the arity field of
  7657. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  7658. argument-passing registers should be considered as read by those
  7659. instructions.
  7660. \subsection{Build Interference Graph}
  7661. \label{sec:build-interference-r4}
  7662. With the addition of function definitions, we compute an interference
  7663. graph for each function (not just one for the whole program).
  7664. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7665. spill vector-typed variables that are live during a call to the
  7666. \code{collect}. With the addition of functions to our language, we
  7667. need to revisit this issue. Many functions perform allocation and
  7668. therefore have calls to the collector inside of them. Thus, we should
  7669. not only spill a vector-typed variable when it is live during a call
  7670. to \code{collect}, but we should spill the variable if it is live
  7671. during any function call. Thus, in the \code{build-interference} pass,
  7672. we recommend adding interference edges between call-live vector-typed
  7673. variables and the callee-saved registers (in addition to the usual
  7674. addition of edges between call-live variables and the caller-saved
  7675. registers).
  7676. \subsection{Allocate Registers}
  7677. The primary change to the \code{allocate-registers} pass is adding an
  7678. auxiliary function for handling definitions (the \Def{} non-terminal
  7679. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  7680. logic is the same as described in
  7681. Chapter~\ref{ch:register-allocation-Rvar}, except now register
  7682. allocation is performed many times, once for each function definition,
  7683. instead of just once for the whole program.
  7684. \section{Patch Instructions}
  7685. In \code{patch-instructions}, you should deal with the x86
  7686. idiosyncrasy that the destination argument of \code{leaq} must be a
  7687. register. Additionally, you should ensure that the argument of
  7688. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7689. code generation more convenient, because we trample many registers
  7690. before the tail call (as explained in the next section).
  7691. \section{Print x86}
  7692. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7693. \code{IndirectCallq} are straightforward: output their concrete
  7694. syntax.
  7695. \begin{lstlisting}
  7696. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7697. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7698. \end{lstlisting}
  7699. The \code{TailJmp} node requires a bit work. A straightforward
  7700. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7701. before the jump we need to pop the current frame. This sequence of
  7702. instructions is the same as the code for the conclusion of a function,
  7703. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7704. Regarding function definitions, you will need to generate a prelude
  7705. and conclusion for each one. This code is similar to the prelude and
  7706. conclusion that you generated for the \code{main} function in
  7707. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  7708. should carry out the following steps.
  7709. \begin{enumerate}
  7710. \item Start with \code{.global} and \code{.align} directives followed
  7711. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  7712. example.)
  7713. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  7714. pointer.
  7715. \item Push to the stack all of the callee-saved registers that were
  7716. used for register allocation.
  7717. \item Move the stack pointer \code{rsp} down by the size of the stack
  7718. frame for this function, which depends on the number of regular
  7719. spills. (Aligned to 16 bytes.)
  7720. \item Move the root stack pointer \code{r15} up by the size of the
  7721. root-stack frame for this function, which depends on the number of
  7722. spilled vectors. \label{root-stack-init}
  7723. \item Initialize to zero all of the entries in the root-stack frame.
  7724. \item Jump to the start block.
  7725. \end{enumerate}
  7726. The prelude of the \code{main} function has one additional task: call
  7727. the \code{initialize} function to set up the garbage collector and
  7728. move the value of the global \code{rootstack\_begin} in
  7729. \code{r15}. This should happen before step \ref{root-stack-init}
  7730. above, which depends on \code{r15}.
  7731. The conclusion of every function should do the following.
  7732. \begin{enumerate}
  7733. \item Move the stack pointer back up by the size of the stack frame
  7734. for this function.
  7735. \item Restore the callee-saved registers by popping them from the
  7736. stack.
  7737. \item Move the root stack pointer back down by the size of the
  7738. root-stack frame for this function.
  7739. \item Restore \code{rbp} by popping it from the stack.
  7740. \item Return to the caller with the \code{retq} instruction.
  7741. \end{enumerate}
  7742. \begin{exercise}\normalfont
  7743. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  7744. Create 5 new programs that use functions, including examples that pass
  7745. functions and return functions from other functions, recursive
  7746. functions, functions that create vectors, and functions that make tail
  7747. calls. Test your compiler on these new programs and all of your
  7748. previously created test programs.
  7749. \end{exercise}
  7750. \begin{figure}[tbp]
  7751. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7752. \node (Rfun) at (0,2) {\large \LangFun{}};
  7753. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  7754. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  7755. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  7756. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  7757. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  7758. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  7759. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  7760. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  7761. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  7762. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  7763. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  7764. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  7765. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  7766. \path[->,bend left=15] (Rfun) edge [above] node
  7767. {\ttfamily\footnotesize shrink} (Rfun-1);
  7768. \path[->,bend left=15] (Rfun-1) edge [above] node
  7769. {\ttfamily\footnotesize uniquify} (Rfun-2);
  7770. \path[->,bend left=15] (Rfun-2) edge [right] node
  7771. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  7772. \path[->,bend left=15] (F1-1) edge [below] node
  7773. {\ttfamily\footnotesize limit-functions} (F1-2);
  7774. \path[->,bend right=15] (F1-2) edge [above] node
  7775. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7776. \path[->,bend right=15] (F1-3) edge [above] node
  7777. {\ttfamily\footnotesize remove-complex.} (F1-4);
  7778. \path[->,bend left=15] (F1-4) edge [right] node
  7779. {\ttfamily\footnotesize explicate-control} (C3-2);
  7780. \path[->,bend right=15] (C3-2) edge [left] node
  7781. {\ttfamily\footnotesize select-instr.} (x86-2);
  7782. \path[->,bend left=15] (x86-2) edge [left] node
  7783. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7784. \path[->,bend right=15] (x86-2-1) edge [below] node
  7785. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7786. \path[->,bend right=15] (x86-2-2) edge [left] node
  7787. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7788. \path[->,bend left=15] (x86-3) edge [above] node
  7789. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7790. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7791. \end{tikzpicture}
  7792. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  7793. \label{fig:Rfun-passes}
  7794. \end{figure}
  7795. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  7796. compiling \LangFun{} to x86.
  7797. \section{An Example Translation}
  7798. \label{sec:functions-example}
  7799. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7800. function in \LangFun{} to x86. The figure also includes the results of the
  7801. \code{explicate-control} and \code{select-instructions} passes.
  7802. \begin{figure}[htbp]
  7803. \begin{tabular}{ll}
  7804. \begin{minipage}{0.5\textwidth}
  7805. % s3_2.rkt
  7806. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7807. (define (add [x : Integer] [y : Integer])
  7808. : Integer
  7809. (+ x y))
  7810. (add 40 2)
  7811. \end{lstlisting}
  7812. $\Downarrow$
  7813. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7814. (define (add86 [x87 : Integer]
  7815. [y88 : Integer]) : Integer
  7816. add86start:
  7817. return (+ x87 y88);
  7818. )
  7819. (define (main) : Integer ()
  7820. mainstart:
  7821. tmp89 = (fun-ref add86);
  7822. (tail-call tmp89 40 2)
  7823. )
  7824. \end{lstlisting}
  7825. \end{minipage}
  7826. &
  7827. $\Rightarrow$
  7828. \begin{minipage}{0.5\textwidth}
  7829. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7830. (define (add86) : Integer
  7831. add86start:
  7832. movq %rdi, x87
  7833. movq %rsi, y88
  7834. movq x87, %rax
  7835. addq y88, %rax
  7836. jmp add11389conclusion
  7837. )
  7838. (define (main) : Integer
  7839. mainstart:
  7840. leaq (fun-ref add86), tmp89
  7841. movq $40, %rdi
  7842. movq $2, %rsi
  7843. tail-jmp tmp89
  7844. )
  7845. \end{lstlisting}
  7846. $\Downarrow$
  7847. \end{minipage}
  7848. \end{tabular}
  7849. \begin{tabular}{ll}
  7850. \begin{minipage}{0.3\textwidth}
  7851. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7852. .globl add86
  7853. .align 16
  7854. add86:
  7855. pushq %rbp
  7856. movq %rsp, %rbp
  7857. jmp add86start
  7858. add86start:
  7859. movq %rdi, %rax
  7860. addq %rsi, %rax
  7861. jmp add86conclusion
  7862. add86conclusion:
  7863. popq %rbp
  7864. retq
  7865. \end{lstlisting}
  7866. \end{minipage}
  7867. &
  7868. \begin{minipage}{0.5\textwidth}
  7869. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7870. .globl main
  7871. .align 16
  7872. main:
  7873. pushq %rbp
  7874. movq %rsp, %rbp
  7875. movq $16384, %rdi
  7876. movq $16384, %rsi
  7877. callq initialize
  7878. movq rootstack_begin(%rip), %r15
  7879. jmp mainstart
  7880. mainstart:
  7881. leaq add86(%rip), %rcx
  7882. movq $40, %rdi
  7883. movq $2, %rsi
  7884. movq %rcx, %rax
  7885. popq %rbp
  7886. jmp *%rax
  7887. mainconclusion:
  7888. popq %rbp
  7889. retq
  7890. \end{lstlisting}
  7891. \end{minipage}
  7892. \end{tabular}
  7893. \caption{Example compilation of a simple function to x86.}
  7894. \label{fig:add-fun}
  7895. \end{figure}
  7896. % Challenge idea: inlining! (simple version)
  7897. % Further Reading
  7898. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7899. \chapter{Lexically Scoped Functions}
  7900. \label{ch:Rlam}
  7901. \index{lambda}
  7902. \index{lexical scoping}
  7903. This chapter studies lexically scoped functions as they appear in
  7904. functional languages such as Racket. By lexical scoping we mean that a
  7905. function's body may refer to variables whose binding site is outside
  7906. of the function, in an enclosing scope.
  7907. %
  7908. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7909. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  7910. \key{lambda} form. The body of the \key{lambda}, refers to three
  7911. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7912. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7913. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7914. parameter of function \code{f}. The \key{lambda} is returned from the
  7915. function \code{f}. The main expression of the program includes two
  7916. calls to \code{f} with different arguments for \code{x}, first
  7917. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7918. to variables \code{g} and \code{h}. Even though these two functions
  7919. were created by the same \code{lambda}, they are really different
  7920. functions because they use different values for \code{x}. Applying
  7921. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7922. \code{15} produces \code{22}. The result of this program is \code{42}.
  7923. \begin{figure}[btp]
  7924. % s4_6.rkt
  7925. \begin{lstlisting}
  7926. (define (f [x : Integer]) : (Integer -> Integer)
  7927. (let ([y 4])
  7928. (lambda: ([z : Integer]) : Integer
  7929. (+ x (+ y z)))))
  7930. (let ([g (f 5)])
  7931. (let ([h (f 3)])
  7932. (+ (g 11) (h 15))))
  7933. \end{lstlisting}
  7934. \caption{Example of a lexically scoped function.}
  7935. \label{fig:lexical-scoping}
  7936. \end{figure}
  7937. The approach that we take for implementing lexically scoped
  7938. functions is to compile them into top-level function definitions,
  7939. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  7940. provide special treatment for variable occurrences such as \code{x}
  7941. and \code{y} in the body of the \code{lambda} of
  7942. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  7943. refer to variables defined outside of it. To identify such variable
  7944. occurrences, we review the standard notion of free variable.
  7945. \begin{definition}
  7946. A variable is \emph{free in expression} $e$ if the variable occurs
  7947. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7948. variable}
  7949. \end{definition}
  7950. For example, in the expression \code{(+ x (+ y z))} the variables
  7951. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7952. only \code{x} and \code{y} are free in the following expression
  7953. because \code{z} is bound by the \code{lambda}.
  7954. \begin{lstlisting}
  7955. (lambda: ([z : Integer]) : Integer
  7956. (+ x (+ y z)))
  7957. \end{lstlisting}
  7958. So the free variables of a \code{lambda} are the ones that will need
  7959. special treatment. We need to arrange for some way to transport, at
  7960. runtime, the values of those variables from the point where the
  7961. \code{lambda} was created to the point where the \code{lambda} is
  7962. applied. An efficient solution to the problem, due to
  7963. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7964. free variables together with the function pointer for the lambda's
  7965. code, an arrangement called a \emph{flat closure} (which we shorten to
  7966. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7967. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  7968. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  7969. pointers. The function pointer resides at index $0$ and the
  7970. values for the free variables will fill in the rest of the vector.
  7971. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7972. how closures work. It's a three-step dance. The program first calls
  7973. function \code{f}, which creates a closure for the \code{lambda}. The
  7974. closure is a vector whose first element is a pointer to the top-level
  7975. function that we will generate for the \code{lambda}, the second
  7976. element is the value of \code{x}, which is \code{5}, and the third
  7977. element is \code{4}, the value of \code{y}. The closure does not
  7978. contain an element for \code{z} because \code{z} is not a free
  7979. variable of the \code{lambda}. Creating the closure is step 1 of the
  7980. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7981. shown in Figure~\ref{fig:closures}.
  7982. %
  7983. The second call to \code{f} creates another closure, this time with
  7984. \code{3} in the second slot (for \code{x}). This closure is also
  7985. returned from \code{f} but bound to \code{h}, which is also shown in
  7986. Figure~\ref{fig:closures}.
  7987. \begin{figure}[tbp]
  7988. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7989. \caption{Example closure representation for the \key{lambda}'s
  7990. in Figure~\ref{fig:lexical-scoping}.}
  7991. \label{fig:closures}
  7992. \end{figure}
  7993. Continuing with the example, consider the application of \code{g} to
  7994. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7995. obtain the function pointer in the first element of the closure and
  7996. call it, passing in the closure itself and then the regular arguments,
  7997. in this case \code{11}. This technique for applying a closure is step
  7998. 2 of the dance.
  7999. %
  8000. But doesn't this \code{lambda} only take 1 argument, for parameter
  8001. \code{z}? The third and final step of the dance is generating a
  8002. top-level function for a \code{lambda}. We add an additional
  8003. parameter for the closure and we insert a \code{let} at the beginning
  8004. of the function for each free variable, to bind those variables to the
  8005. appropriate elements from the closure parameter.
  8006. %
  8007. This three-step dance is known as \emph{closure conversion}. We
  8008. discuss the details of closure conversion in
  8009. Section~\ref{sec:closure-conversion} and the code generated from the
  8010. example in Section~\ref{sec:example-lambda}. But first we define the
  8011. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  8012. \section{The \LangLam{} Language}
  8013. \label{sec:r5}
  8014. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  8015. functions and lexical scoping, is defined in
  8016. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  8017. the \key{lambda} form to the grammar for \LangFun{}, which already has
  8018. syntax for function application.
  8019. \begin{figure}[tp]
  8020. \centering
  8021. \fbox{
  8022. \begin{minipage}{0.96\textwidth}
  8023. \small
  8024. \[
  8025. \begin{array}{lcl}
  8026. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  8027. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  8028. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  8029. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8030. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  8031. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  8032. &\mid& \gray{\key{\#t} \mid \key{\#f}
  8033. \mid (\key{and}\;\Exp\;\Exp)
  8034. \mid (\key{or}\;\Exp\;\Exp)
  8035. \mid (\key{not}\;\Exp) } \\
  8036. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  8037. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  8038. (\key{vector-ref}\;\Exp\;\Int)} \\
  8039. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  8040. \mid (\Exp \; \Exp\ldots) } \\
  8041. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  8042. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  8043. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  8044. \LangLam{} &::=& \gray{\Def\ldots \; \Exp}
  8045. \end{array}
  8046. \]
  8047. \end{minipage}
  8048. }
  8049. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  8050. with \key{lambda}.}
  8051. \label{fig:Rlam-concrete-syntax}
  8052. \end{figure}
  8053. \begin{figure}[tp]
  8054. \centering
  8055. \fbox{
  8056. \begin{minipage}{0.96\textwidth}
  8057. \small
  8058. \[
  8059. \begin{array}{lcl}
  8060. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  8061. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  8062. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8063. &\mid& \gray{ \BOOL{\itm{bool}}
  8064. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  8065. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  8066. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  8067. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  8068. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8069. \LangLam{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8070. \end{array}
  8071. \]
  8072. \end{minipage}
  8073. }
  8074. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  8075. \label{fig:Rlam-syntax}
  8076. \end{figure}
  8077. \index{interpreter}
  8078. \label{sec:interp-Rlambda}
  8079. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  8080. \LangLam{}. The case for \key{lambda} saves the current environment
  8081. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  8082. the environment from the \key{lambda}, the \code{lam-env}, when
  8083. interpreting the body of the \key{lambda}. The \code{lam-env}
  8084. environment is extended with the mapping of parameters to argument
  8085. values.
  8086. \begin{figure}[tbp]
  8087. \begin{lstlisting}
  8088. (define interp-Rlambda-class
  8089. (class interp-Rfun-class
  8090. (super-new)
  8091. (define/override (interp-op op)
  8092. (match op
  8093. ['procedure-arity
  8094. (lambda (v)
  8095. (match v
  8096. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  8097. [else (error 'interp-op "expected a function, not ~a" v)]))]
  8098. [else (super interp-op op)]))
  8099. (define/override ((interp-exp env) e)
  8100. (define recur (interp-exp env))
  8101. (match e
  8102. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  8103. `(function ,xs ,body ,env)]
  8104. [else ((super interp-exp env) e)]))
  8105. ))
  8106. (define (interp-Rlambda p)
  8107. (send (new interp-Rlambda-class) interp-program p))
  8108. \end{lstlisting}
  8109. \caption{Interpreter for \LangLam{}.}
  8110. \label{fig:interp-Rlambda}
  8111. \end{figure}
  8112. \label{sec:type-check-r5}
  8113. \index{type checking}
  8114. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  8115. \key{lambda} form. The body of the \key{lambda} is checked in an
  8116. environment that includes the current environment (because it is
  8117. lexically scoped) and also includes the \key{lambda}'s parameters. We
  8118. require the body's type to match the declared return type.
  8119. \begin{figure}[tbp]
  8120. \begin{lstlisting}
  8121. (define (type-check-Rlambda env)
  8122. (lambda (e)
  8123. (match e
  8124. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  8125. (define-values (new-body bodyT)
  8126. ((type-check-exp (append (map cons xs Ts) env)) body))
  8127. (define ty `(,@Ts -> ,rT))
  8128. (cond
  8129. [(equal? rT bodyT)
  8130. (values (HasType (Lambda params rT new-body) ty) ty)]
  8131. [else
  8132. (error "mismatch in return type" bodyT rT)])]
  8133. ...
  8134. )))
  8135. \end{lstlisting}
  8136. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  8137. \label{fig:type-check-Rlambda}
  8138. \end{figure}
  8139. \section{Reveal Functions and the $F_2$ language}
  8140. \label{sec:reveal-functions-r5}
  8141. To support the \code{procedure-arity} operator we need to communicate
  8142. the arity of a function to the point of closure creation. We can
  8143. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  8144. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  8145. output of this pass is the language $F_2$, whose syntax is defined in
  8146. Figure~\ref{fig:f2-syntax}.
  8147. \begin{figure}[tp]
  8148. \centering
  8149. \fbox{
  8150. \begin{minipage}{0.96\textwidth}
  8151. \[
  8152. \begin{array}{lcl}
  8153. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  8154. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8155. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  8156. \end{array}
  8157. \]
  8158. \end{minipage}
  8159. }
  8160. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  8161. (Figure~\ref{fig:Rlam-syntax}).}
  8162. \label{fig:f2-syntax}
  8163. \end{figure}
  8164. \section{Closure Conversion}
  8165. \label{sec:closure-conversion}
  8166. \index{closure conversion}
  8167. The compiling of lexically-scoped functions into top-level function
  8168. definitions is accomplished in the pass \code{convert-to-closures}
  8169. that comes after \code{reveal-functions} and before
  8170. \code{limit-functions}.
  8171. As usual, we implement the pass as a recursive function over the
  8172. AST. All of the action is in the cases for \key{Lambda} and
  8173. \key{Apply}. We transform a \key{Lambda} expression into an expression
  8174. that creates a closure, that is, a vector whose first element is a
  8175. function pointer and the rest of the elements are the free variables
  8176. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  8177. using \code{vector} so that we can distinguish closures from vectors
  8178. in Section~\ref{sec:optimize-closures} and to record the arity. In
  8179. the generated code below, the \itm{name} is a unique symbol generated
  8180. to identify the function and the \itm{arity} is the number of
  8181. parameters (the length of \itm{ps}).
  8182. \begin{lstlisting}
  8183. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  8184. |$\Rightarrow$|
  8185. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  8186. \end{lstlisting}
  8187. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  8188. create a top-level function definition for each \key{Lambda}, as
  8189. shown below.\\
  8190. \begin{minipage}{0.8\textwidth}
  8191. \begin{lstlisting}
  8192. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  8193. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  8194. ...
  8195. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  8196. |\itm{body'}|)...))
  8197. \end{lstlisting}
  8198. \end{minipage}\\
  8199. The \code{clos} parameter refers to the closure. Translate the type
  8200. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  8201. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  8202. $\itm{fvts}$ are the types of the free variables in the lambda and the
  8203. underscore \code{\_} is a dummy type that we use because it is rather
  8204. difficult to give a type to the function in the closure's
  8205. type.\footnote{To give an accurate type to a closure, we would need to
  8206. add existential types to the type checker~\citep{Minamide:1996ys}.}
  8207. The dummy type is considered to be equal to any other type during type
  8208. checking. The sequence of \key{Let} forms bind the free variables to
  8209. their values obtained from the closure.
  8210. Closure conversion turns functions into vectors, so the type
  8211. annotations in the program must also be translated. We recommend
  8212. defining a auxiliary recursive function for this purpose. Function
  8213. types should be translated as follows.
  8214. \begin{lstlisting}
  8215. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  8216. |$\Rightarrow$|
  8217. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  8218. \end{lstlisting}
  8219. The above type says that the first thing in the vector is a function
  8220. pointer. The first parameter of the function pointer is a vector (a
  8221. closure) and the rest of the parameters are the ones from the original
  8222. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  8223. the closure omits the types of the free variables because 1) those
  8224. types are not available in this context and 2) we do not need them in
  8225. the code that is generated for function application.
  8226. We transform function application into code that retrieves the
  8227. function pointer from the closure and then calls the function, passing
  8228. in the closure as the first argument. We bind $e'$ to a temporary
  8229. variable to avoid code duplication.
  8230. \begin{lstlisting}
  8231. (Apply |$e$| |\itm{es}|)
  8232. |$\Rightarrow$|
  8233. (Let |\itm{tmp}| |$e'$|
  8234. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  8235. \end{lstlisting}
  8236. There is also the question of what to do with references top-level
  8237. function definitions. To maintain a uniform translation of function
  8238. application, we turn function references into closures.
  8239. \begin{tabular}{lll}
  8240. \begin{minipage}{0.3\textwidth}
  8241. \begin{lstlisting}
  8242. (FunRefArity |$f$| |$n$|)
  8243. \end{lstlisting}
  8244. \end{minipage}
  8245. &
  8246. $\Rightarrow$
  8247. &
  8248. \begin{minipage}{0.5\textwidth}
  8249. \begin{lstlisting}
  8250. (Closure |$n$| (FunRef |$f$|) '())
  8251. \end{lstlisting}
  8252. \end{minipage}
  8253. \end{tabular} \\
  8254. %
  8255. The top-level function definitions need to be updated as well to take
  8256. an extra closure parameter.
  8257. \section{An Example Translation}
  8258. \label{sec:example-lambda}
  8259. Figure~\ref{fig:lexical-functions-example} shows the result of
  8260. \code{reveal-functions} and \code{convert-to-closures} for the example
  8261. program demonstrating lexical scoping that we discussed at the
  8262. beginning of this chapter.
  8263. \begin{figure}[tbp]
  8264. \begin{minipage}{0.8\textwidth}
  8265. % tests/lambda_test_6.rkt
  8266. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8267. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  8268. (let ([y8 4])
  8269. (lambda: ([z9 : Integer]) : Integer
  8270. (+ x7 (+ y8 z9)))))
  8271. (define (main) : Integer
  8272. (let ([g0 ((fun-ref-arity f6 1) 5)])
  8273. (let ([h1 ((fun-ref-arity f6 1) 3)])
  8274. (+ (g0 11) (h1 15)))))
  8275. \end{lstlisting}
  8276. $\Rightarrow$
  8277. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8278. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  8279. (let ([y8 4])
  8280. (closure 1 (list (fun-ref lambda2) x7 y8))))
  8281. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  8282. (let ([x7 (vector-ref fvs3 1)])
  8283. (let ([y8 (vector-ref fvs3 2)])
  8284. (+ x7 (+ y8 z9)))))
  8285. (define (main) : Integer
  8286. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  8287. ((vector-ref clos5 0) clos5 5))])
  8288. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  8289. ((vector-ref clos6 0) clos6 3))])
  8290. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  8291. \end{lstlisting}
  8292. \end{minipage}
  8293. \caption{Example of closure conversion.}
  8294. \label{fig:lexical-functions-example}
  8295. \end{figure}
  8296. \begin{exercise}\normalfont
  8297. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  8298. Create 5 new programs that use \key{lambda} functions and make use of
  8299. lexical scoping. Test your compiler on these new programs and all of
  8300. your previously created test programs.
  8301. \end{exercise}
  8302. \section{Expose Allocation}
  8303. \label{sec:expose-allocation-r5}
  8304. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  8305. that allocates and initializes a vector, similar to the translation of
  8306. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  8307. The only difference is replacing the use of
  8308. \ALLOC{\itm{len}}{\itm{type}} with
  8309. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  8310. \section{Explicate Control and \LangCLam{}}
  8311. \label{sec:explicate-r5}
  8312. The output language of \code{explicate-control} is \LangCLam{} whose
  8313. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  8314. difference with respect to \LangCFun{} is the addition of the
  8315. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  8316. of \code{AllocateClosure} in the \code{explicate-control} pass is
  8317. similar to the handling of other expressions such as primitive
  8318. operators.
  8319. \begin{figure}[tp]
  8320. \fbox{
  8321. \begin{minipage}{0.96\textwidth}
  8322. \small
  8323. \[
  8324. \begin{array}{lcl}
  8325. \Exp &::= & \ldots
  8326. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  8327. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8328. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  8329. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8330. \mid \GOTO{\itm{label}} } \\
  8331. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8332. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  8333. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  8334. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  8335. \end{array}
  8336. \]
  8337. \end{minipage}
  8338. }
  8339. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  8340. \label{fig:c4-syntax}
  8341. \end{figure}
  8342. \section{Select Instructions}
  8343. \label{sec:select-instructions-Rlambda}
  8344. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  8345. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  8346. (Section~\ref{sec:select-instructions-gc}). The only difference is
  8347. that you should place the \itm{arity} in the tag that is stored at
  8348. position $0$ of the vector. Recall that in
  8349. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  8350. was not used. We store the arity in the $5$ bits starting at position
  8351. $58$.
  8352. Compile the \code{procedure-arity} operator into a sequence of
  8353. instructions that access the tag from position $0$ of the vector and
  8354. extract the $5$-bits starting at position $58$ from the tag.
  8355. \begin{figure}[p]
  8356. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8357. \node (Rfun) at (0,2) {\large \LangFun{}};
  8358. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  8359. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  8360. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8361. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8362. \node (F1-3) at (6,0) {\large $F_1$};
  8363. \node (F1-4) at (3,0) {\large $F_1$};
  8364. \node (F1-5) at (0,0) {\large $F_1$};
  8365. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8366. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8367. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8368. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8369. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8370. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8371. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8372. \path[->,bend left=15] (Rfun) edge [above] node
  8373. {\ttfamily\footnotesize shrink} (Rfun-2);
  8374. \path[->,bend left=15] (Rfun-2) edge [above] node
  8375. {\ttfamily\footnotesize uniquify} (Rfun-3);
  8376. \path[->,bend left=15] (Rfun-3) edge [right] node
  8377. {\ttfamily\footnotesize reveal-functions} (F1-1);
  8378. \path[->,bend left=15] (F1-1) edge [below] node
  8379. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  8380. \path[->,bend right=15] (F1-2) edge [above] node
  8381. {\ttfamily\footnotesize limit-fun.} (F1-3);
  8382. \path[->,bend right=15] (F1-3) edge [above] node
  8383. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  8384. \path[->,bend right=15] (F1-4) edge [above] node
  8385. {\ttfamily\footnotesize remove-complex.} (F1-5);
  8386. \path[->,bend right=15] (F1-5) edge [right] node
  8387. {\ttfamily\footnotesize explicate-control} (C3-2);
  8388. \path[->,bend left=15] (C3-2) edge [left] node
  8389. {\ttfamily\footnotesize select-instr.} (x86-2);
  8390. \path[->,bend right=15] (x86-2) edge [left] node
  8391. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8392. \path[->,bend right=15] (x86-2-1) edge [below] node
  8393. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8394. \path[->,bend right=15] (x86-2-2) edge [left] node
  8395. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8396. \path[->,bend left=15] (x86-3) edge [above] node
  8397. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8398. \path[->,bend left=15] (x86-4) edge [right] node
  8399. {\ttfamily\footnotesize print-x86} (x86-5);
  8400. \end{tikzpicture}
  8401. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  8402. functions.}
  8403. \label{fig:Rlambda-passes}
  8404. \end{figure}
  8405. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  8406. for the compilation of \LangLam{}.
  8407. \clearpage
  8408. \section{Challenge: Optimize Closures}
  8409. \label{sec:optimize-closures}
  8410. In this chapter we compiled lexically-scoped functions into a
  8411. relatively efficient representation: flat closures. However, even this
  8412. representation comes with some overhead. For example, consider the
  8413. following program with a function \code{tail-sum} that does not have
  8414. any free variables and where all the uses of \code{tail-sum} are in
  8415. applications where we know that only \code{tail-sum} is being applied
  8416. (and not any other functions).
  8417. \begin{center}
  8418. \begin{minipage}{0.95\textwidth}
  8419. \begin{lstlisting}
  8420. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  8421. (if (eq? n 0)
  8422. r
  8423. (tail-sum (- n 1) (+ n r))))
  8424. (+ (tail-sum 5 0) 27)
  8425. \end{lstlisting}
  8426. \end{minipage}
  8427. \end{center}
  8428. As described in this chapter, we uniformly apply closure conversion to
  8429. all functions, obtaining the following output for this program.
  8430. \begin{center}
  8431. \begin{minipage}{0.95\textwidth}
  8432. \begin{lstlisting}
  8433. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  8434. (if (eq? n2 0)
  8435. r3
  8436. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  8437. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  8438. (define (main) : Integer
  8439. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  8440. ((vector-ref clos6 0) clos6 5 0)) 27))
  8441. \end{lstlisting}
  8442. \end{minipage}
  8443. \end{center}
  8444. In the previous Chapter, there would be no allocation in the program
  8445. and the calls to \code{tail-sum} would be direct calls. In contrast,
  8446. the above program allocates memory for each \code{closure} and the
  8447. calls to \code{tail-sum} are indirect. These two differences incur
  8448. considerable overhead in a program such as this one, where the
  8449. allocations and indirect calls occur inside a tight loop.
  8450. One might think that this problem is trivial to solve: can't we just
  8451. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  8452. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  8453. e'_n$)} instead of treating it like a call to a closure? We would
  8454. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  8455. %
  8456. However, this problem is not so trivial because a global function may
  8457. ``escape'' and become involved in applications that also involve
  8458. closures. Consider the following example in which the application
  8459. \code{(f 41)} needs to be compiled into a closure application, because
  8460. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  8461. function might also get bound to \code{f}.
  8462. \begin{lstlisting}
  8463. (define (add1 [x : Integer]) : Integer
  8464. (+ x 1))
  8465. (let ([y (read)])
  8466. (let ([f (if (eq? (read) 0)
  8467. add1
  8468. (lambda: ([x : Integer]) : Integer (- x y)))])
  8469. (f 41)))
  8470. \end{lstlisting}
  8471. If a global function name is used in any way other than as the
  8472. operator in a direct call, then we say that the function
  8473. \emph{escapes}. If a global function does not escape, then we do not
  8474. need to perform closure conversion on the function.
  8475. \begin{exercise}\normalfont
  8476. Implement an auxiliary function for detecting which global
  8477. functions escape. Using that function, implement an improved version
  8478. of closure conversion that does not apply closure conversion to
  8479. global functions that do not escape but instead compiles them as
  8480. regular functions. Create several new test cases that check whether
  8481. you properly detect whether global functions escape or not.
  8482. \end{exercise}
  8483. So far we have reduced the overhead of calling global functions, but
  8484. it would also be nice to reduce the overhead of calling a
  8485. \code{lambda} when we can determine at compile time which
  8486. \code{lambda} will be called. We refer to such calls as \emph{known
  8487. calls}. Consider the following example in which a \code{lambda} is
  8488. bound to \code{f} and then applied.
  8489. \begin{lstlisting}
  8490. (let ([y (read)])
  8491. (let ([f (lambda: ([x : Integer]) : Integer
  8492. (+ x y))])
  8493. (f 21)))
  8494. \end{lstlisting}
  8495. Closure conversion compiles \code{(f 21)} into an indirect call:
  8496. \begin{lstlisting}
  8497. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  8498. (let ([y2 (vector-ref fvs6 1)])
  8499. (+ x3 y2)))
  8500. (define (main) : Integer
  8501. (let ([y2 (read)])
  8502. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8503. ((vector-ref f4 0) f4 21))))
  8504. \end{lstlisting}
  8505. but we can instead compile the application \code{(f 21)} into a direct call
  8506. to \code{lambda5}:
  8507. \begin{lstlisting}
  8508. (define (main) : Integer
  8509. (let ([y2 (read)])
  8510. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8511. ((fun-ref lambda5) f4 21))))
  8512. \end{lstlisting}
  8513. The problem of determining which lambda will be called from a
  8514. particular application is quite challenging in general and the topic
  8515. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  8516. following exercise we recommend that you compile an application to a
  8517. direct call when the operator is a variable and the variable is
  8518. \code{let}-bound to a closure. This can be accomplished by maintaining
  8519. an environment mapping \code{let}-bound variables to function names.
  8520. Extend the environment whenever you encounter a closure on the
  8521. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  8522. to the name of the global function for the closure. This pass should
  8523. come after closure conversion.
  8524. \begin{exercise}\normalfont
  8525. Implement a compiler pass, named \code{optimize-known-calls}, that
  8526. compiles known calls into direct calls. Verify that your compiler is
  8527. successful in this regard on several example programs.
  8528. \end{exercise}
  8529. These exercises only scratches the surface of optimizing of
  8530. closures. A good next step for the interested reader is to look at the
  8531. work of \citet{Keep:2012ab}.
  8532. \section{Further Reading}
  8533. The notion of lexically scoped anonymous functions predates modern
  8534. computers by about a decade. They were invented by
  8535. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  8536. foundation for logic. Anonymous functions were included in the
  8537. LISP~\citep{McCarthy:1960dz} programming language but were initially
  8538. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  8539. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  8540. compile Scheme programs. However, environments were represented as
  8541. linked lists, so variable lookup was linear in the size of the
  8542. environment. In this chapter we represent environments using flat
  8543. closures, which were invented by
  8544. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  8545. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  8546. closures, variable lookup is constant time but the time to create a
  8547. closure is proportional to the number of its free variables. Flat
  8548. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  8549. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  8550. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8551. \chapter{Dynamic Typing}
  8552. \label{ch:Rdyn}
  8553. \index{dynamic typing}
  8554. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  8555. typed language that is a subset of Racket. This is in contrast to the
  8556. previous chapters, which have studied the compilation of Typed
  8557. Racket. In dynamically typed languages such as \LangDyn{}, a given
  8558. expression may produce a value of a different type each time it is
  8559. executed. Consider the following example with a conditional \code{if}
  8560. expression that may return a Boolean or an integer depending on the
  8561. input to the program.
  8562. % part of dynamic_test_25.rkt
  8563. \begin{lstlisting}
  8564. (not (if (eq? (read) 1) #f 0))
  8565. \end{lstlisting}
  8566. Languages that allow expressions to produce different kinds of values
  8567. are called \emph{polymorphic}, a word composed of the Greek roots
  8568. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  8569. are several kinds of polymorphism in programming languages, such as
  8570. subtype polymorphism and parametric
  8571. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  8572. study in this chapter does not have a special name but it is the kind
  8573. that arises in dynamically typed languages.
  8574. Another characteristic of dynamically typed languages is that
  8575. primitive operations, such as \code{not}, are often defined to operate
  8576. on many different types of values. In fact, in Racket, the \code{not}
  8577. operator produces a result for any kind of value: given \code{\#f} it
  8578. returns \code{\#t} and given anything else it returns \code{\#f}.
  8579. Furthermore, even when primitive operations restrict their inputs to
  8580. values of a certain type, this restriction is enforced at runtime
  8581. instead of during compilation. For example, the following vector
  8582. reference results in a run-time contract violation because the index
  8583. must be in integer, not a Boolean such as \code{\#t}.
  8584. \begin{lstlisting}
  8585. (vector-ref (vector 42) #t)
  8586. \end{lstlisting}
  8587. \begin{figure}[tp]
  8588. \centering
  8589. \fbox{
  8590. \begin{minipage}{0.97\textwidth}
  8591. \[
  8592. \begin{array}{rcl}
  8593. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  8594. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8595. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  8596. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  8597. &\mid& \key{\#t} \mid \key{\#f}
  8598. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  8599. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  8600. \mid \CUNIOP{\key{not}}{\Exp} \\
  8601. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  8602. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  8603. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  8604. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  8605. &\mid& \LP\Exp \; \Exp\ldots\RP
  8606. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  8607. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  8608. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  8609. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  8610. \LangDyn{} &::=& \Def\ldots\; \Exp
  8611. \end{array}
  8612. \]
  8613. \end{minipage}
  8614. }
  8615. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  8616. \label{fig:r7-concrete-syntax}
  8617. \end{figure}
  8618. \begin{figure}[tp]
  8619. \centering
  8620. \fbox{
  8621. \begin{minipage}{0.96\textwidth}
  8622. \small
  8623. \[
  8624. \begin{array}{lcl}
  8625. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  8626. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  8627. &\mid& \BOOL{\itm{bool}}
  8628. \mid \IF{\Exp}{\Exp}{\Exp} \\
  8629. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  8630. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  8631. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  8632. \LangDyn{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  8633. \end{array}
  8634. \]
  8635. \end{minipage}
  8636. }
  8637. \caption{The abstract syntax of \LangDyn{}.}
  8638. \label{fig:r7-syntax}
  8639. \end{figure}
  8640. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  8641. defined in Figures~\ref{fig:r7-concrete-syntax} and
  8642. \ref{fig:r7-syntax}.
  8643. %
  8644. There is no type checker for \LangDyn{} because it is not a statically
  8645. typed language (it's dynamically typed!).
  8646. The definitional interpreter for \LangDyn{} is presented in
  8647. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  8648. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  8649. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  8650. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  8651. interpreter for \LangDyn{} creates a \emph{tagged value}\index{tagged
  8652. value} that combines an underlying value with a tag that identifies
  8653. what kind of value it is. We define the following struct
  8654. to represented tagged values.
  8655. \begin{lstlisting}
  8656. (struct Tagged (value tag) #:transparent)
  8657. \end{lstlisting}
  8658. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  8659. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  8660. but don't always capture all the information that a type does. For
  8661. example, a vector of type \code{(Vector Any Any)} is tagged with
  8662. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  8663. is tagged with \code{Procedure}.
  8664. Next consider the match case for \code{vector-ref}. The
  8665. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  8666. is used to ensure that the first argument is a vector and the second
  8667. is an integer. If they are not, a \code{trapped-error} is raised.
  8668. Recall from Section~\ref{sec:interp-Rint} that when a definition
  8669. interpreter raises a \code{trapped-error} error, the compiled code
  8670. must also signal an error by exiting with return code \code{255}. A
  8671. \code{trapped-error} is also raised if the index is not less than
  8672. length of the vector.
  8673. \begin{figure}[tbp]
  8674. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8675. (define ((interp-Rdyn-exp env) ast)
  8676. (define recur (interp-Rdyn-exp env))
  8677. (match ast
  8678. [(Var x) (lookup x env)]
  8679. [(Int n) (Tagged n 'Integer)]
  8680. [(Bool b) (Tagged b 'Boolean)]
  8681. [(Lambda xs rt body)
  8682. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  8683. [(Prim 'vector es)
  8684. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  8685. [(Prim 'vector-ref (list e1 e2))
  8686. (define vec (recur e1)) (define i (recur e2))
  8687. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8688. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8689. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8690. (vector-ref (Tagged-value vec) (Tagged-value i))]
  8691. [(Prim 'vector-set! (list e1 e2 e3))
  8692. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  8693. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8694. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8695. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8696. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  8697. (Tagged (void) 'Void)]
  8698. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  8699. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  8700. [(Prim 'or (list e1 e2))
  8701. (define v1 (recur e1))
  8702. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  8703. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  8704. [(Prim op (list e1))
  8705. #:when (set-member? type-predicates op)
  8706. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  8707. [(Prim op es)
  8708. (define args (map recur es))
  8709. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  8710. (unless (for/or ([expected-tags (op-tags op)])
  8711. (equal? expected-tags tags))
  8712. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  8713. (tag-value
  8714. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  8715. [(If q t f)
  8716. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  8717. [(Apply f es)
  8718. (define new-f (recur f)) (define args (map recur es))
  8719. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  8720. (match f-val
  8721. [`(function ,xs ,body ,lam-env)
  8722. (unless (eq? (length xs) (length args))
  8723. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  8724. (define new-env (append (map cons xs args) lam-env))
  8725. ((interp-Rdyn-exp new-env) body)]
  8726. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  8727. \end{lstlisting}
  8728. \caption{Interpreter for the \LangDyn{} language.}
  8729. \label{fig:interp-Rdyn}
  8730. \end{figure}
  8731. \begin{figure}[tbp]
  8732. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8733. (define (interp-op op)
  8734. (match op
  8735. ['+ fx+]
  8736. ['- fx-]
  8737. ['read read-fixnum]
  8738. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  8739. ['< (lambda (v1 v2)
  8740. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  8741. ['<= (lambda (v1 v2)
  8742. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  8743. ['> (lambda (v1 v2)
  8744. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  8745. ['>= (lambda (v1 v2)
  8746. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  8747. ['boolean? boolean?]
  8748. ['integer? fixnum?]
  8749. ['void? void?]
  8750. ['vector? vector?]
  8751. ['vector-length vector-length]
  8752. ['procedure? (match-lambda
  8753. [`(functions ,xs ,body ,env) #t] [else #f])]
  8754. [else (error 'interp-op "unknown operator" op)]))
  8755. (define (op-tags op)
  8756. (match op
  8757. ['+ '((Integer Integer))]
  8758. ['- '((Integer Integer) (Integer))]
  8759. ['read '(())]
  8760. ['not '((Boolean))]
  8761. ['< '((Integer Integer))]
  8762. ['<= '((Integer Integer))]
  8763. ['> '((Integer Integer))]
  8764. ['>= '((Integer Integer))]
  8765. ['vector-length '((Vector))]))
  8766. (define type-predicates
  8767. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8768. (define (tag-value v)
  8769. (cond [(boolean? v) (Tagged v 'Boolean)]
  8770. [(fixnum? v) (Tagged v 'Integer)]
  8771. [(procedure? v) (Tagged v 'Procedure)]
  8772. [(vector? v) (Tagged v 'Vector)]
  8773. [(void? v) (Tagged v 'Void)]
  8774. [else (error 'tag-value "unidentified value ~a" v)]))
  8775. (define (check-tag val expected ast)
  8776. (define tag (Tagged-tag val))
  8777. (unless (eq? tag expected)
  8778. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  8779. \end{lstlisting}
  8780. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  8781. \label{fig:interp-Rdyn-aux}
  8782. \end{figure}
  8783. \clearpage
  8784. \section{Representation of Tagged Values}
  8785. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  8786. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  8787. values at the bit level. Because almost every operation in \LangDyn{}
  8788. involves manipulating tagged values, the representation must be
  8789. efficient. Recall that all of our values are 64 bits. We shall steal
  8790. the 3 right-most bits to encode the tag. We use $001$ to identify
  8791. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  8792. and $101$ for the void value. We define the following auxiliary
  8793. function for mapping types to tag codes.
  8794. \begin{align*}
  8795. \itm{tagof}(\key{Integer}) &= 001 \\
  8796. \itm{tagof}(\key{Boolean}) &= 100 \\
  8797. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  8798. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  8799. \itm{tagof}(\key{Void}) &= 101
  8800. \end{align*}
  8801. This stealing of 3 bits comes at some price: our integers are reduced
  8802. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  8803. affect vectors and procedures because those values are addresses, and
  8804. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  8805. they are always $000$. Thus, we do not lose information by overwriting
  8806. the rightmost 3 bits with the tag and we can simply zero-out the tag
  8807. to recover the original address.
  8808. To make tagged values into first-class entities, we can give them a
  8809. type, called \code{Any}, and define operations such as \code{Inject}
  8810. and \code{Project} for creating and using them, yielding the \LangAny{}
  8811. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  8812. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  8813. in greater detail.
  8814. \section{The \LangAny{} Language}
  8815. \label{sec:Rany-lang}
  8816. \begin{figure}[tp]
  8817. \centering
  8818. \fbox{
  8819. \begin{minipage}{0.96\textwidth}
  8820. \small
  8821. \[
  8822. \begin{array}{lcl}
  8823. \Type &::= & \ldots \mid \key{Any} \\
  8824. \itm{op} &::= & \ldots \mid \code{any-vector-length}
  8825. \mid \code{any-vector-ref} \mid \code{any-vector-set!}\\
  8826. &\mid& \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  8827. \mid \code{procedure?} \mid \code{void?} \\
  8828. \Exp &::=& \ldots
  8829. \mid \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  8830. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  8831. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8832. \LangAny{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8833. \end{array}
  8834. \]
  8835. \end{minipage}
  8836. }
  8837. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  8838. \label{fig:Rany-syntax}
  8839. \end{figure}
  8840. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  8841. (The concrete syntax of \LangAny{} is in the Appendix,
  8842. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  8843. converts the value produced by expression $e$ of type $T$ into a
  8844. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  8845. produced by expression $e$ into a value of type $T$ or else halts the
  8846. program if the type tag is not equivalent to $T$.
  8847. %
  8848. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  8849. restricted to a flat type $\FType$, which simplifies the
  8850. implementation and corresponds with what is needed for compiling \LangDyn{}.
  8851. The \code{any-vector} operators adapt the vector operations so that
  8852. they can be applied to a value of type \code{Any}. They also
  8853. generalize the vector operations in that the index is not restricted
  8854. to be a literal integer in the grammar but is allowed to be any
  8855. expression.
  8856. The type predicates such as \key{boolean?} expect their argument to
  8857. produce a tagged value; they return \key{\#t} if the tag corresponds
  8858. to the predicate and they return \key{\#f} otherwise.
  8859. The type checker for \LangAny{} is shown in
  8860. Figures~\ref{fig:type-check-Rany-part-1} and
  8861. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  8862. Figure~\ref{fig:type-check-Rany-aux}.
  8863. %
  8864. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  8865. auxiliary functions \code{apply-inject} and \code{apply-project} are
  8866. in Figure~\ref{fig:apply-project}.
  8867. \begin{figure}[btp]
  8868. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8869. (define type-check-Rany-class
  8870. (class type-check-Rlambda-class
  8871. (super-new)
  8872. (inherit check-type-equal?)
  8873. (define/override (type-check-exp env)
  8874. (lambda (e)
  8875. (define recur (type-check-exp env))
  8876. (match e
  8877. [(Inject e1 ty)
  8878. (unless (flat-ty? ty)
  8879. (error 'type-check "may only inject from flat type, not ~a" ty))
  8880. (define-values (new-e1 e-ty) (recur e1))
  8881. (check-type-equal? e-ty ty e)
  8882. (values (Inject new-e1 ty) 'Any)]
  8883. [(Project e1 ty)
  8884. (unless (flat-ty? ty)
  8885. (error 'type-check "may only project to flat type, not ~a" ty))
  8886. (define-values (new-e1 e-ty) (recur e1))
  8887. (check-type-equal? e-ty 'Any e)
  8888. (values (Project new-e1 ty) ty)]
  8889. [(Prim 'any-vector-length (list e1))
  8890. (define-values (e1^ t1) (recur e1))
  8891. (check-type-equal? t1 'Any e)
  8892. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  8893. [(Prim 'any-vector-ref (list e1 e2))
  8894. (define-values (e1^ t1) (recur e1))
  8895. (define-values (e2^ t2) (recur e2))
  8896. (check-type-equal? t1 'Any e)
  8897. (check-type-equal? t2 'Integer e)
  8898. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  8899. [(Prim 'any-vector-set! (list e1 e2 e3))
  8900. (define-values (e1^ t1) (recur e1))
  8901. (define-values (e2^ t2) (recur e2))
  8902. (define-values (e3^ t3) (recur e3))
  8903. (check-type-equal? t1 'Any e)
  8904. (check-type-equal? t2 'Integer e)
  8905. (check-type-equal? t3 'Any e)
  8906. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  8907. \end{lstlisting}
  8908. \caption{Type checker for the \LangAny{} language, part 1.}
  8909. \label{fig:type-check-Rany-part-1}
  8910. \end{figure}
  8911. \begin{figure}[btp]
  8912. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8913. [(ValueOf e ty)
  8914. (define-values (new-e e-ty) (recur e))
  8915. (values (ValueOf new-e ty) ty)]
  8916. [(Prim pred (list e1))
  8917. #:when (set-member? (type-predicates) pred)
  8918. (define-values (new-e1 e-ty) (recur e1))
  8919. (check-type-equal? e-ty 'Any e)
  8920. (values (Prim pred (list new-e1)) 'Boolean)]
  8921. [(If cnd thn els)
  8922. (define-values (cnd^ Tc) (recur cnd))
  8923. (define-values (thn^ Tt) (recur thn))
  8924. (define-values (els^ Te) (recur els))
  8925. (check-type-equal? Tc 'Boolean cnd)
  8926. (check-type-equal? Tt Te e)
  8927. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  8928. [(Exit) (values (Exit) '_)]
  8929. [(Prim 'eq? (list arg1 arg2))
  8930. (define-values (e1 t1) (recur arg1))
  8931. (define-values (e2 t2) (recur arg2))
  8932. (match* (t1 t2)
  8933. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  8934. [(other wise) (check-type-equal? t1 t2 e)])
  8935. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  8936. [else ((super type-check-exp env) e)])))
  8937. ))
  8938. \end{lstlisting}
  8939. \caption{Type checker for the \LangAny{} language, part 2.}
  8940. \label{fig:type-check-Rany-part-2}
  8941. \end{figure}
  8942. \begin{figure}[tbp]
  8943. \begin{lstlisting}
  8944. (define/override (operator-types)
  8945. (append
  8946. '((integer? . ((Any) . Boolean))
  8947. (vector? . ((Any) . Boolean))
  8948. (procedure? . ((Any) . Boolean))
  8949. (void? . ((Any) . Boolean))
  8950. (tag-of-any . ((Any) . Integer))
  8951. (make-any . ((_ Integer) . Any))
  8952. )
  8953. (super operator-types)))
  8954. (define/public (type-predicates)
  8955. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8956. (define/public (combine-types t1 t2)
  8957. (match (list t1 t2)
  8958. [(list '_ t2) t2]
  8959. [(list t1 '_) t1]
  8960. [(list `(Vector ,ts1 ...)
  8961. `(Vector ,ts2 ...))
  8962. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  8963. (combine-types t1 t2)))]
  8964. [(list `(,ts1 ... -> ,rt1)
  8965. `(,ts2 ... -> ,rt2))
  8966. `(,@(for/list ([t1 ts1] [t2 ts2])
  8967. (combine-types t1 t2))
  8968. -> ,(combine-types rt1 rt2))]
  8969. [else t1]))
  8970. (define/public (flat-ty? ty)
  8971. (match ty
  8972. [(or `Integer `Boolean '_ `Void) #t]
  8973. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  8974. [`(,ts ... -> ,rt)
  8975. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  8976. [else #f]))
  8977. \end{lstlisting}
  8978. \caption{Auxiliary methods for type checking \LangAny{}.}
  8979. \label{fig:type-check-Rany-aux}
  8980. \end{figure}
  8981. \begin{figure}[btp]
  8982. \begin{lstlisting}
  8983. (define interp-Rany-class
  8984. (class interp-Rlambda-class
  8985. (super-new)
  8986. (define/override (interp-op op)
  8987. (match op
  8988. ['boolean? (match-lambda
  8989. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  8990. [else #f])]
  8991. ['integer? (match-lambda
  8992. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  8993. [else #f])]
  8994. ['vector? (match-lambda
  8995. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  8996. [else #f])]
  8997. ['procedure? (match-lambda
  8998. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  8999. [else #f])]
  9000. ['eq? (match-lambda*
  9001. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  9002. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  9003. [ls (apply (super interp-op op) ls)])]
  9004. ['any-vector-ref (lambda (v i)
  9005. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  9006. ['any-vector-set! (lambda (v i a)
  9007. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  9008. ['any-vector-length (lambda (v)
  9009. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  9010. [else (super interp-op op)]))
  9011. (define/override ((interp-exp env) e)
  9012. (define recur (interp-exp env))
  9013. (match e
  9014. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  9015. [(Project e ty2) (apply-project (recur e) ty2)]
  9016. [else ((super interp-exp env) e)]))
  9017. ))
  9018. (define (interp-Rany p)
  9019. (send (new interp-Rany-class) interp-program p))
  9020. \end{lstlisting}
  9021. \caption{Interpreter for \LangAny{}.}
  9022. \label{fig:interp-Rany}
  9023. \end{figure}
  9024. \begin{figure}[tbp]
  9025. \begin{lstlisting}
  9026. (define/public (apply-inject v tg) (Tagged v tg))
  9027. (define/public (apply-project v ty2)
  9028. (define tag2 (any-tag ty2))
  9029. (match v
  9030. [(Tagged v1 tag1)
  9031. (cond
  9032. [(eq? tag1 tag2)
  9033. (match ty2
  9034. [`(Vector ,ts ...)
  9035. (define l1 ((interp-op 'vector-length) v1))
  9036. (cond
  9037. [(eq? l1 (length ts)) v1]
  9038. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  9039. l1 (length ts))])]
  9040. [`(,ts ... -> ,rt)
  9041. (match v1
  9042. [`(function ,xs ,body ,env)
  9043. (cond [(eq? (length xs) (length ts)) v1]
  9044. [else
  9045. (error 'apply-project "arity mismatch ~a != ~a"
  9046. (length xs) (length ts))])]
  9047. [else (error 'apply-project "expected function not ~a" v1)])]
  9048. [else v1])]
  9049. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  9050. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  9051. \end{lstlisting}
  9052. \caption{Auxiliary functions for injection and projection.}
  9053. \label{fig:apply-project}
  9054. \end{figure}
  9055. \clearpage
  9056. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  9057. \label{sec:compile-r7}
  9058. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  9059. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  9060. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  9061. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  9062. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  9063. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  9064. the Boolean \code{\#t}, which must be injected to produce an
  9065. expression of type \key{Any}.
  9066. %
  9067. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  9068. addition, is representative of compilation for many primitive
  9069. operations: the arguments have type \key{Any} and must be projected to
  9070. \key{Integer} before the addition can be performed.
  9071. The compilation of \key{lambda} (third row of
  9072. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  9073. produce type annotations: we simply use \key{Any}.
  9074. %
  9075. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  9076. has to account for some differences in behavior between \LangDyn{} and
  9077. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  9078. kind of values can be used in various places. For example, the
  9079. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  9080. the arguments need not be of the same type (in that case the
  9081. result is \code{\#f}).
  9082. \begin{figure}[btp]
  9083. \centering
  9084. \begin{tabular}{|lll|} \hline
  9085. \begin{minipage}{0.27\textwidth}
  9086. \begin{lstlisting}
  9087. #t
  9088. \end{lstlisting}
  9089. \end{minipage}
  9090. &
  9091. $\Rightarrow$
  9092. &
  9093. \begin{minipage}{0.65\textwidth}
  9094. \begin{lstlisting}
  9095. (inject #t Boolean)
  9096. \end{lstlisting}
  9097. \end{minipage}
  9098. \\[2ex]\hline
  9099. \begin{minipage}{0.27\textwidth}
  9100. \begin{lstlisting}
  9101. (+ |$e_1$| |$e_2$|)
  9102. \end{lstlisting}
  9103. \end{minipage}
  9104. &
  9105. $\Rightarrow$
  9106. &
  9107. \begin{minipage}{0.65\textwidth}
  9108. \begin{lstlisting}
  9109. (inject
  9110. (+ (project |$e'_1$| Integer)
  9111. (project |$e'_2$| Integer))
  9112. Integer)
  9113. \end{lstlisting}
  9114. \end{minipage}
  9115. \\[2ex]\hline
  9116. \begin{minipage}{0.27\textwidth}
  9117. \begin{lstlisting}
  9118. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  9119. \end{lstlisting}
  9120. \end{minipage}
  9121. &
  9122. $\Rightarrow$
  9123. &
  9124. \begin{minipage}{0.65\textwidth}
  9125. \begin{lstlisting}
  9126. (inject
  9127. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  9128. (Any|$\ldots$|Any -> Any))
  9129. \end{lstlisting}
  9130. \end{minipage}
  9131. \\[2ex]\hline
  9132. \begin{minipage}{0.27\textwidth}
  9133. \begin{lstlisting}
  9134. (|$e_0$| |$e_1 \ldots e_n$|)
  9135. \end{lstlisting}
  9136. \end{minipage}
  9137. &
  9138. $\Rightarrow$
  9139. &
  9140. \begin{minipage}{0.65\textwidth}
  9141. \begin{lstlisting}
  9142. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  9143. \end{lstlisting}
  9144. \end{minipage}
  9145. \\[2ex]\hline
  9146. \begin{minipage}{0.27\textwidth}
  9147. \begin{lstlisting}
  9148. (vector-ref |$e_1$| |$e_2$|)
  9149. \end{lstlisting}
  9150. \end{minipage}
  9151. &
  9152. $\Rightarrow$
  9153. &
  9154. \begin{minipage}{0.65\textwidth}
  9155. \begin{lstlisting}
  9156. (any-vector-ref |$e_1'$| |$e_2'$|)
  9157. \end{lstlisting}
  9158. \end{minipage}
  9159. \\[2ex]\hline
  9160. \begin{minipage}{0.27\textwidth}
  9161. \begin{lstlisting}
  9162. (if |$e_1$| |$e_2$| |$e_3$|)
  9163. \end{lstlisting}
  9164. \end{minipage}
  9165. &
  9166. $\Rightarrow$
  9167. &
  9168. \begin{minipage}{0.65\textwidth}
  9169. \begin{lstlisting}
  9170. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  9171. \end{lstlisting}
  9172. \end{minipage}
  9173. \\[2ex]\hline
  9174. \begin{minipage}{0.27\textwidth}
  9175. \begin{lstlisting}
  9176. (eq? |$e_1$| |$e_2$|)
  9177. \end{lstlisting}
  9178. \end{minipage}
  9179. &
  9180. $\Rightarrow$
  9181. &
  9182. \begin{minipage}{0.65\textwidth}
  9183. \begin{lstlisting}
  9184. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  9185. \end{lstlisting}
  9186. \end{minipage}
  9187. \\[2ex]\hline
  9188. \begin{minipage}{0.27\textwidth}
  9189. \begin{lstlisting}
  9190. (not |$e_1$|)
  9191. \end{lstlisting}
  9192. \end{minipage}
  9193. &
  9194. $\Rightarrow$
  9195. &
  9196. \begin{minipage}{0.65\textwidth}
  9197. \begin{lstlisting}
  9198. (if (eq? |$e'_1$| (inject #f Boolean))
  9199. (inject #t Boolean) (inject #f Boolean))
  9200. \end{lstlisting}
  9201. \end{minipage}
  9202. \\[2ex]\hline
  9203. \end{tabular}
  9204. \caption{Cast Insertion}
  9205. \label{fig:compile-r7-Rany}
  9206. \end{figure}
  9207. \section{Reveal Casts}
  9208. \label{sec:reveal-casts-Rany}
  9209. % TODO: define R'_6
  9210. In the \code{reveal-casts} pass we recommend compiling \code{project}
  9211. into an \code{if} expression that checks whether the value's tag
  9212. matches the target type; if it does, the value is converted to a value
  9213. of the target type by removing the tag; if it does not, the program
  9214. exits. To perform these actions we need a new primitive operation,
  9215. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  9216. The \code{tag-of-any} operation retrieves the type tag from a tagged
  9217. value of type \code{Any}. The \code{ValueOf} form retrieves the
  9218. underlying value from a tagged value. The \code{ValueOf} form
  9219. includes the type for the underlying value which is used by the type
  9220. checker. Finally, the \code{Exit} form ends the execution of the
  9221. program.
  9222. If the target type of the projection is \code{Boolean} or
  9223. \code{Integer}, then \code{Project} can be translated as follows.
  9224. \begin{center}
  9225. \begin{minipage}{1.0\textwidth}
  9226. \begin{lstlisting}
  9227. (Project |$e$| |$\FType$|)
  9228. |$\Rightarrow$|
  9229. (Let |$\itm{tmp}$| |$e'$|
  9230. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  9231. (Int |$\itm{tagof}(\FType)$|)))
  9232. (ValueOf |$\itm{tmp}$| |$\FType$|)
  9233. (Exit)))
  9234. \end{lstlisting}
  9235. \end{minipage}
  9236. \end{center}
  9237. If the target type of the projection is a vector or function type,
  9238. then there is a bit more work to do. For vectors, check that the
  9239. length of the vector type matches the length of the vector (using the
  9240. \code{vector-length} primitive). For functions, check that the number
  9241. of parameters in the function type matches the function's arity (using
  9242. \code{procedure-arity}).
  9243. Regarding \code{inject}, we recommend compiling it to a slightly
  9244. lower-level primitive operation named \code{make-any}. This operation
  9245. takes a tag instead of a type.
  9246. \begin{center}
  9247. \begin{minipage}{1.0\textwidth}
  9248. \begin{lstlisting}
  9249. (Inject |$e$| |$\FType$|)
  9250. |$\Rightarrow$|
  9251. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  9252. \end{lstlisting}
  9253. \end{minipage}
  9254. \end{center}
  9255. The type predicates (\code{boolean?}, etc.) can be translated into
  9256. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  9257. translation of \code{Project}.
  9258. The \code{any-vector-ref} and \code{any-vector-set!} operations
  9259. combine the projection action with the vector operation. Also, the
  9260. read and write operations allow arbitrary expressions for the index so
  9261. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  9262. cannot guarantee that the index is within bounds. Thus, we insert code
  9263. to perform bounds checking at runtime. The translation for
  9264. \code{any-vector-ref} is as follows and the other two operations are
  9265. translated in a similar way.
  9266. \begin{lstlisting}
  9267. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  9268. |$\Rightarrow$|
  9269. (Let |$v$| |$e'_1$|
  9270. (Let |$i$| |$e'_2$|
  9271. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  9272. (If (Prim '< (list (Var |$i$|)
  9273. (Prim 'any-vector-length (list (Var |$v$|)))))
  9274. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  9275. (Exit))))
  9276. \end{lstlisting}
  9277. \section{Remove Complex Operands}
  9278. \label{sec:rco-Rany}
  9279. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  9280. The subexpression of \code{ValueOf} must be atomic.
  9281. \section{Explicate Control and \LangCAny{}}
  9282. \label{sec:explicate-Rany}
  9283. The output of \code{explicate-control} is the \LangCAny{} language whose
  9284. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  9285. form that we added to \LangAny{} remains an expression and the \code{Exit}
  9286. expression becomes a $\Tail$. Also, note that the index argument of
  9287. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  9288. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  9289. \begin{figure}[tp]
  9290. \fbox{
  9291. \begin{minipage}{0.96\textwidth}
  9292. \small
  9293. \[
  9294. \begin{array}{lcl}
  9295. \Exp &::= & \ldots
  9296. \mid \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  9297. &\mid& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  9298. &\mid& \VALUEOF{\Exp}{\FType} \\
  9299. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9300. \mid \LP\key{Collect} \,\itm{int}\RP }\\
  9301. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  9302. \mid \GOTO{\itm{label}} } \\
  9303. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9304. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  9305. \mid \LP\key{Exit}\RP \\
  9306. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  9307. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  9308. \end{array}
  9309. \]
  9310. \end{minipage}
  9311. }
  9312. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9313. \label{fig:c5-syntax}
  9314. \end{figure}
  9315. \section{Select Instructions}
  9316. \label{sec:select-Rany}
  9317. In the \code{select-instructions} pass we translate the primitive
  9318. operations on the \code{Any} type to x86 instructions that involve
  9319. manipulating the 3 tag bits of the tagged value.
  9320. \paragraph{Make-any}
  9321. We recommend compiling the \key{make-any} primitive as follows if the
  9322. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  9323. shifts the destination to the left by the number of bits specified its
  9324. source argument (in this case $3$, the length of the tag) and it
  9325. preserves the sign of the integer. We use the \key{orq} instruction to
  9326. combine the tag and the value to form the tagged value. \\
  9327. \begin{lstlisting}
  9328. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9329. |$\Rightarrow$|
  9330. movq |$e'$|, |\itm{lhs'}|
  9331. salq $3, |\itm{lhs'}|
  9332. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9333. \end{lstlisting}
  9334. The instruction selection for vectors and procedures is different
  9335. because their is no need to shift them to the left. The rightmost 3
  9336. bits are already zeros as described at the beginning of this
  9337. chapter. So we just combine the value and the tag using \key{orq}. \\
  9338. \begin{lstlisting}
  9339. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9340. |$\Rightarrow$|
  9341. movq |$e'$|, |\itm{lhs'}|
  9342. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9343. \end{lstlisting}
  9344. \paragraph{Tag-of-any}
  9345. Recall that the \code{tag-of-any} operation extracts the type tag from
  9346. a value of type \code{Any}. The type tag is the bottom three bits, so
  9347. we obtain the tag by taking the bitwise-and of the value with $111$
  9348. ($7$ in decimal).
  9349. \begin{lstlisting}
  9350. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  9351. |$\Rightarrow$|
  9352. movq |$e'$|, |\itm{lhs'}|
  9353. andq $7, |\itm{lhs'}|
  9354. \end{lstlisting}
  9355. \paragraph{ValueOf}
  9356. Like \key{make-any}, the instructions for \key{ValueOf} are different
  9357. depending on whether the type $T$ is a pointer (vector or procedure)
  9358. or not (Integer or Boolean). The following shows the instruction
  9359. selection for Integer and Boolean. We produce an untagged value by
  9360. shifting it to the right by 3 bits.
  9361. \begin{lstlisting}
  9362. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9363. |$\Rightarrow$|
  9364. movq |$e'$|, |\itm{lhs'}|
  9365. sarq $3, |\itm{lhs'}|
  9366. \end{lstlisting}
  9367. %
  9368. In the case for vectors and procedures, there is no need to
  9369. shift. Instead we just need to zero-out the rightmost 3 bits. We
  9370. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  9371. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  9372. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  9373. then apply \code{andq} with the tagged value to get the desired
  9374. result. \\
  9375. \begin{lstlisting}
  9376. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9377. |$\Rightarrow$|
  9378. movq $|$-8$|, |\itm{lhs'}|
  9379. andq |$e'$|, |\itm{lhs'}|
  9380. \end{lstlisting}
  9381. %% \paragraph{Type Predicates} We leave it to the reader to
  9382. %% devise a sequence of instructions to implement the type predicates
  9383. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  9384. \paragraph{Any-vector-length}
  9385. \begin{lstlisting}
  9386. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  9387. |$\Longrightarrow$|
  9388. movq |$\neg 111$|, %r11
  9389. andq |$a_1'$|, %r11
  9390. movq 0(%r11), %r11
  9391. andq $126, %r11
  9392. sarq $1, %r11
  9393. movq %r11, |$\itm{lhs'}$|
  9394. \end{lstlisting}
  9395. \paragraph{Any-vector-ref}
  9396. The index may be an arbitrary atom so instead of computing the offset
  9397. at compile time, instructions need to be generated to compute the
  9398. offset at runtime as follows. Note the use of the new instruction
  9399. \code{imulq}.
  9400. \begin{center}
  9401. \begin{minipage}{0.96\textwidth}
  9402. \begin{lstlisting}
  9403. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  9404. |$\Longrightarrow$|
  9405. movq |$\neg 111$|, %r11
  9406. andq |$a_1'$|, %r11
  9407. movq |$a_2'$|, %rax
  9408. addq $1, %rax
  9409. imulq $8, %rax
  9410. addq %rax, %r11
  9411. movq 0(%r11) |$\itm{lhs'}$|
  9412. \end{lstlisting}
  9413. \end{minipage}
  9414. \end{center}
  9415. \paragraph{Any-vector-set!}
  9416. The code generation for \code{any-vector-set!} is similar to the other
  9417. \code{any-vector} operations.
  9418. \section{Register Allocation for \LangAny{}}
  9419. \label{sec:register-allocation-Rany}
  9420. \index{register allocation}
  9421. There is an interesting interaction between tagged values and garbage
  9422. collection that has an impact on register allocation. A variable of
  9423. type \code{Any} might refer to a vector and therefore it might be a
  9424. root that needs to be inspected and copied during garbage
  9425. collection. Thus, we need to treat variables of type \code{Any} in a
  9426. similar way to variables of type \code{Vector} for purposes of
  9427. register allocation. In particular,
  9428. \begin{itemize}
  9429. \item If a variable of type \code{Any} is live during a function call,
  9430. then it must be spilled. This can be accomplished by changing
  9431. \code{build-interference} to mark all variables of type \code{Any}
  9432. that are live after a \code{callq} as interfering with all the
  9433. registers.
  9434. \item If a variable of type \code{Any} is spilled, it must be spilled
  9435. to the root stack instead of the normal procedure call stack.
  9436. \end{itemize}
  9437. Another concern regarding the root stack is that the garbage collector
  9438. needs to differentiate between (1) plain old pointers to tuples, (2) a
  9439. tagged value that points to a tuple, and (3) a tagged value that is
  9440. not a tuple. We enable this differentiation by choosing not to use the
  9441. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  9442. reserved for identifying plain old pointers to tuples. That way, if
  9443. one of the first three bits is set, then we have a tagged value and
  9444. inspecting the tag can differentiation between vectors ($010$) and the
  9445. other kinds of values.
  9446. \begin{exercise}\normalfont
  9447. Expand your compiler to handle \LangAny{} as discussed in the last few
  9448. sections. Create 5 new programs that use the \code{Any} type and the
  9449. new operations (\code{inject}, \code{project}, \code{boolean?},
  9450. etc.). Test your compiler on these new programs and all of your
  9451. previously created test programs.
  9452. \end{exercise}
  9453. \begin{exercise}\normalfont
  9454. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  9455. Create tests for \LangDyn{} by adapting ten of your previous test programs
  9456. by removing type annotations. Add 5 more tests programs that
  9457. specifically rely on the language being dynamically typed. That is,
  9458. they should not be legal programs in a statically typed language, but
  9459. nevertheless, they should be valid \LangDyn{} programs that run to
  9460. completion without error.
  9461. \end{exercise}
  9462. \begin{figure}[p]
  9463. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9464. \node (Rfun) at (0,4) {\large \LangDyn{}};
  9465. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  9466. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  9467. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  9468. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  9469. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  9470. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  9471. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  9472. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  9473. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  9474. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  9475. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  9476. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9477. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9478. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9479. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9480. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9481. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9482. \path[->,bend left=15] (Rfun) edge [above] node
  9483. {\ttfamily\footnotesize shrink} (Rfun-2);
  9484. \path[->,bend left=15] (Rfun-2) edge [above] node
  9485. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9486. \path[->,bend left=15] (Rfun-3) edge [above] node
  9487. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  9488. \path[->,bend right=15] (Rfun-4) edge [left] node
  9489. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  9490. \path[->,bend left=15] (Rfun-5) edge [above] node
  9491. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  9492. \path[->,bend left=15] (Rfun-6) edge [left] node
  9493. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  9494. \path[->,bend left=15] (Rfun-7) edge [below] node
  9495. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9496. \path[->,bend right=15] (F1-2) edge [above] node
  9497. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9498. \path[->,bend right=15] (F1-3) edge [above] node
  9499. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9500. \path[->,bend right=15] (F1-4) edge [above] node
  9501. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9502. \path[->,bend right=15] (F1-5) edge [right] node
  9503. {\ttfamily\footnotesize explicate-control} (C3-2);
  9504. \path[->,bend left=15] (C3-2) edge [left] node
  9505. {\ttfamily\footnotesize select-instr.} (x86-2);
  9506. \path[->,bend right=15] (x86-2) edge [left] node
  9507. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9508. \path[->,bend right=15] (x86-2-1) edge [below] node
  9509. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9510. \path[->,bend right=15] (x86-2-2) edge [left] node
  9511. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9512. \path[->,bend left=15] (x86-3) edge [above] node
  9513. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9514. \path[->,bend left=15] (x86-4) edge [right] node
  9515. {\ttfamily\footnotesize print-x86} (x86-5);
  9516. \end{tikzpicture}
  9517. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  9518. \label{fig:Rdyn-passes}
  9519. \end{figure}
  9520. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  9521. for the compilation of \LangDyn{}.
  9522. % Further Reading
  9523. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9524. \chapter{Loops and Assignment}
  9525. \label{ch:Rwhile}
  9526. % TODO: define R'_8
  9527. % TODO: multi-graph
  9528. In this chapter we study two features that are the hallmarks of
  9529. imperative programming languages: loops and assignments to local
  9530. variables. The following example demonstrates these new features by
  9531. computing the sum of the first five positive integers.
  9532. % similar to loop_test_1.rkt
  9533. \begin{lstlisting}
  9534. (let ([sum 0])
  9535. (let ([i 5])
  9536. (begin
  9537. (while (> i 0)
  9538. (begin
  9539. (set! sum (+ sum i))
  9540. (set! i (- i 1))))
  9541. sum)))
  9542. \end{lstlisting}
  9543. The \code{while} loop consists of a condition and a body.
  9544. %
  9545. The \code{set!} consists of a variable and a right-hand-side expression.
  9546. %
  9547. The primary purpose of both the \code{while} loop and \code{set!} is
  9548. to cause side effects, so it is convenient to also include in a
  9549. language feature for sequencing side effects: the \code{begin}
  9550. expression. It consists of one or more subexpressions that are
  9551. evaluated left-to-right.
  9552. \section{The \LangLoop{} Language}
  9553. \begin{figure}[tp]
  9554. \centering
  9555. \fbox{
  9556. \begin{minipage}{0.96\textwidth}
  9557. \small
  9558. \[
  9559. \begin{array}{lcl}
  9560. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  9561. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  9562. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  9563. &\mid& \gray{\key{\#t} \mid \key{\#f}
  9564. \mid (\key{and}\;\Exp\;\Exp)
  9565. \mid (\key{or}\;\Exp\;\Exp)
  9566. \mid (\key{not}\;\Exp) } \\
  9567. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  9568. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  9569. (\key{vector-ref}\;\Exp\;\Int)} \\
  9570. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  9571. \mid (\Exp \; \Exp\ldots) } \\
  9572. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  9573. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  9574. &\mid& \CSETBANG{\Var}{\Exp}
  9575. \mid \CBEGIN{\Exp\ldots}{\Exp}
  9576. \mid \CWHILE{\Exp}{\Exp} \\
  9577. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9578. \LangLoop{} &::=& \gray{\Def\ldots \; \Exp}
  9579. \end{array}
  9580. \]
  9581. \end{minipage}
  9582. }
  9583. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-concrete-syntax}).}
  9584. \label{fig:Rwhile-concrete-syntax}
  9585. \end{figure}
  9586. \begin{figure}[tp]
  9587. \centering
  9588. \fbox{
  9589. \begin{minipage}{0.96\textwidth}
  9590. \small
  9591. \[
  9592. \begin{array}{lcl}
  9593. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  9594. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  9595. &\mid& \gray{ \BOOL{\itm{bool}}
  9596. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  9597. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  9598. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  9599. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  9600. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9601. \mid \WHILE{\Exp}{\Exp} \\
  9602. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9603. \LangLoop{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9604. \end{array}
  9605. \]
  9606. \end{minipage}
  9607. }
  9608. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-syntax}).}
  9609. \label{fig:Rwhile-syntax}
  9610. \end{figure}
  9611. The concrete syntax of \LangLoop{} is defined in
  9612. Figure~\ref{fig:Rwhile-concrete-syntax} and its abstract syntax is defined
  9613. in Figure~\ref{fig:Rwhile-syntax}.
  9614. %
  9615. The definitional interpreter for \LangLoop{} is shown in
  9616. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  9617. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  9618. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  9619. support assignment to variables and to make their lifetimes indefinite
  9620. (see the second example in Section~\ref{sec:assignment-scoping}), we
  9621. box the value that is bound to each variable (in \code{Let}) and
  9622. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  9623. the value.
  9624. %
  9625. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9626. variable in the environment to obtain a boxed value and then we change
  9627. it using \code{set-box!} to the result of evaluating the right-hand
  9628. side. The result value of a \code{SetBang} is \code{void}.
  9629. %
  9630. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9631. if the result is true, 2) evaluate the body.
  9632. The result value of a \code{while} loop is also \code{void}.
  9633. %
  9634. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9635. subexpressions \itm{es} for their effects and then evaluates
  9636. and returns the result from \itm{body}.
  9637. \begin{figure}[tbp]
  9638. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9639. (define interp-Rwhile-class
  9640. (class interp-Rany-class
  9641. (super-new)
  9642. (define/override ((interp-exp env) e)
  9643. (define recur (interp-exp env))
  9644. (match e
  9645. [(SetBang x rhs)
  9646. (set-box! (lookup x env) (recur rhs))]
  9647. [(WhileLoop cnd body)
  9648. (define (loop)
  9649. (cond [(recur cnd) (recur body) (loop)]
  9650. [else (void)]))
  9651. (loop)]
  9652. [(Begin es body)
  9653. (for ([e es]) (recur e))
  9654. (recur body)]
  9655. [else ((super interp-exp env) e)]))
  9656. ))
  9657. (define (interp-Rwhile p)
  9658. (send (new interp-Rwhile-class) interp-program p))
  9659. \end{lstlisting}
  9660. \caption{Interpreter for \LangLoop{}.}
  9661. \label{fig:interp-Rwhile}
  9662. \end{figure}
  9663. The type checker for \LangLoop{} is define in
  9664. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  9665. variable and the right-hand-side must agree. The result type is
  9666. \code{Void}. For the \code{WhileLoop}, the condition must be a
  9667. \code{Boolean}. The result type is also \code{Void}. For
  9668. \code{Begin}, the result type is the type of its last subexpression.
  9669. \begin{figure}[tbp]
  9670. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9671. (define type-check-Rwhile-class
  9672. (class type-check-Rany-class
  9673. (super-new)
  9674. (inherit check-type-equal?)
  9675. (define/override (type-check-exp env)
  9676. (lambda (e)
  9677. (define recur (type-check-exp env))
  9678. (match e
  9679. [(SetBang x rhs)
  9680. (define-values (rhs^ rhsT) (recur rhs))
  9681. (define varT (dict-ref env x))
  9682. (check-type-equal? rhsT varT e)
  9683. (values (SetBang x rhs^) 'Void)]
  9684. [(WhileLoop cnd body)
  9685. (define-values (cnd^ Tc) (recur cnd))
  9686. (check-type-equal? Tc 'Boolean e)
  9687. (define-values (body^ Tbody) ((type-check-exp env) body))
  9688. (values (WhileLoop cnd^ body^) 'Void)]
  9689. [(Begin es body)
  9690. (define-values (es^ ts)
  9691. (for/lists (l1 l2) ([e es]) (recur e)))
  9692. (define-values (body^ Tbody) (recur body))
  9693. (values (Begin es^ body^) Tbody)]
  9694. [else ((super type-check-exp env) e)])))
  9695. ))
  9696. (define (type-check-Rwhile p)
  9697. (send (new type-check-Rwhile-class) type-check-program p))
  9698. \end{lstlisting}
  9699. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  9700. and \code{Begin} in \LangLoop{}.}
  9701. \label{fig:type-check-Rwhile}
  9702. \end{figure}
  9703. At first glance, the translation of these language features to x86
  9704. seems straightforward because the \LangCFun{} intermediate language already
  9705. supports all of the ingredients that we need: assignment, \code{goto},
  9706. conditional branching, and sequencing. However, there are two
  9707. complications that arise which we discuss in the next two
  9708. sections. After that we introduce one new compiler pass and the
  9709. changes necessary to the existing passes.
  9710. \section{Assignment and Lexically Scoped Functions}
  9711. \label{sec:assignment-scoping}
  9712. The addition of assignment raises a problem with our approach to
  9713. implementing lexically-scoped functions. Consider the following
  9714. example in which function \code{f} has a free variable \code{x} that
  9715. is changed after \code{f} is created but before the call to \code{f}.
  9716. % loop_test_11.rkt
  9717. \begin{lstlisting}
  9718. (let ([x 0])
  9719. (let ([y 0])
  9720. (let ([z 20])
  9721. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9722. (begin
  9723. (set! x 10)
  9724. (set! y 12)
  9725. (f y))))))
  9726. \end{lstlisting}
  9727. The correct output for this example is \code{42} because the call to
  9728. \code{f} is required to use the current value of \code{x} (which is
  9729. \code{10}). Unfortunately, the closure conversion pass
  9730. (Section~\ref{sec:closure-conversion}) generates code for the
  9731. \code{lambda} that copies the old value of \code{x} into a
  9732. closure. Thus, if we naively add support for assignment to our current
  9733. compiler, the output of this program would be \code{32}.
  9734. A first attempt at solving this problem would be to save a pointer to
  9735. \code{x} in the closure and change the occurrences of \code{x} inside
  9736. the lambda to dereference the pointer. Of course, this would require
  9737. assigning \code{x} to the stack and not to a register. However, the
  9738. problem goes a bit deeper. Consider the following example in which we
  9739. create a counter abstraction by creating a pair of functions that
  9740. share the free variable \code{x}.
  9741. % similar to loop_test_10.rkt
  9742. \begin{lstlisting}
  9743. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  9744. (vector
  9745. (lambda: () : Integer x)
  9746. (lambda: () : Void (set! x (+ 1 x)))))
  9747. (let ([counter (f 0)])
  9748. (let ([get (vector-ref counter 0)])
  9749. (let ([inc (vector-ref counter 1)])
  9750. (begin
  9751. (inc)
  9752. (get)))))
  9753. \end{lstlisting}
  9754. In this example, the lifetime of \code{x} extends beyond the lifetime
  9755. of the call to \code{f}. Thus, if we were to store \code{x} on the
  9756. stack frame for the call to \code{f}, it would be gone by the time we
  9757. call \code{inc} and \code{get}, leaving us with dangling pointers for
  9758. \code{x}. This example demonstrates that when a variable occurs free
  9759. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  9760. value of the variable needs to live on the heap. The verb ``box'' is
  9761. often used for allocating a single value on the heap, producing a
  9762. pointer, and ``unbox'' for dereferencing the pointer.
  9763. We recommend solving these problems by ``boxing'' the local variables
  9764. that are in the intersection of 1) variables that appear on the
  9765. left-hand-side of a \code{set!} and 2) variables that occur free
  9766. inside a \code{lambda}. We shall introduce a new pass named
  9767. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  9768. perform this translation. But before diving into the compiler passes,
  9769. we one more problem to discuss.
  9770. \section{Cyclic Control Flow and Dataflow Analysis}
  9771. \label{sec:dataflow-analysis}
  9772. Up until this point the control-flow graphs generated in
  9773. \code{explicate-control} were guaranteed to be acyclic. However, each
  9774. \code{while} loop introduces a cycle in the control-flow graph.
  9775. But does that matter?
  9776. %
  9777. Indeed it does. Recall that for register allocation, the compiler
  9778. performs liveness analysis to determine which variables can share the
  9779. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  9780. the control-flow graph in reverse topological order, but topological
  9781. order is only well-defined for acyclic graphs.
  9782. Let us return to the example of computing the sum of the first five
  9783. positive integers. Here is the program after instruction selection but
  9784. before register allocation.
  9785. \begin{center}
  9786. \begin{minipage}{0.45\textwidth}
  9787. \begin{lstlisting}
  9788. (define (main) : Integer
  9789. mainstart:
  9790. movq $0, sum1
  9791. movq $5, i2
  9792. jmp block5
  9793. block5:
  9794. movq i2, tmp3
  9795. cmpq tmp3, $0
  9796. jl block7
  9797. jmp block8
  9798. \end{lstlisting}
  9799. \end{minipage}
  9800. \begin{minipage}{0.45\textwidth}
  9801. \begin{lstlisting}
  9802. block7:
  9803. addq i2, sum1
  9804. movq $1, tmp4
  9805. negq tmp4
  9806. addq tmp4, i2
  9807. jmp block5
  9808. block8:
  9809. movq $27, %rax
  9810. addq sum1, %rax
  9811. jmp mainconclusion
  9812. )
  9813. \end{lstlisting}
  9814. \end{minipage}
  9815. \end{center}
  9816. Recall that liveness analysis works backwards, starting at the end
  9817. of each function. For this example we could start with \code{block8}
  9818. because we know what is live at the beginning of the conclusion,
  9819. just \code{rax} and \code{rsp}. So the live-before set
  9820. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  9821. %
  9822. Next we might try to analyze \code{block5} or \code{block7}, but
  9823. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9824. we are stuck.
  9825. The way out of this impasse comes from the realization that one can
  9826. perform liveness analysis starting with an empty live-after set to
  9827. compute an under-approximation of the live-before set. By
  9828. \emph{under-approximation}, we mean that the set only contains
  9829. variables that are really live, but it may be missing some. Next, the
  9830. under-approximations for each block can be improved by 1) updating the
  9831. live-after set for each block using the approximate live-before sets
  9832. from the other blocks and 2) perform liveness analysis again on each
  9833. block. In fact, by iterating this process, the under-approximations
  9834. eventually become the correct solutions!
  9835. %
  9836. This approach of iteratively analyzing a control-flow graph is
  9837. applicable to many static analysis problems and goes by the name
  9838. \emph{dataflow analysis}\index{dataflow analysis}. It was invented by
  9839. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9840. Washington.
  9841. Let us apply this approach to the above example. We use the empty set
  9842. for the initial live-before set for each block. Let $m_0$ be the
  9843. following mapping from label names to sets of locations (variables and
  9844. registers).
  9845. \begin{center}
  9846. \begin{lstlisting}
  9847. mainstart: {}
  9848. block5: {}
  9849. block7: {}
  9850. block8: {}
  9851. \end{lstlisting}
  9852. \end{center}
  9853. Using the above live-before approximations, we determine the
  9854. live-after for each block and then apply liveness analysis to each
  9855. block. This produces our next approximation $m_1$ of the live-before
  9856. sets.
  9857. \begin{center}
  9858. \begin{lstlisting}
  9859. mainstart: {}
  9860. block5: {i2}
  9861. block7: {i2, sum1}
  9862. block8: {rsp, sum1}
  9863. \end{lstlisting}
  9864. \end{center}
  9865. For the second round, the live-after for \code{mainstart} is the
  9866. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  9867. liveness analysis for \code{mainstart} computes the empty set. The
  9868. live-after for \code{block5} is the union of the live-before sets for
  9869. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  9870. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  9871. sum1\}}. The live-after for \code{block7} is the live-before for
  9872. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  9873. So the liveness analysis for \code{block7} remains \code{\{i2,
  9874. sum1\}}. Together these yield the following approximation $m_2$ of
  9875. the live-before sets.
  9876. \begin{center}
  9877. \begin{lstlisting}
  9878. mainstart: {}
  9879. block5: {i2, rsp, sum1}
  9880. block7: {i2, sum1}
  9881. block8: {rsp, sum1}
  9882. \end{lstlisting}
  9883. \end{center}
  9884. In the preceding iteration, only \code{block5} changed, so we can
  9885. limit our attention to \code{mainstart} and \code{block7}, the two
  9886. blocks that jump to \code{block5}. As a result, the live-before sets
  9887. for \code{mainstart} and \code{block7} are updated to include
  9888. \code{rsp}, yielding the following approximation $m_3$.
  9889. \begin{center}
  9890. \begin{lstlisting}
  9891. mainstart: {rsp}
  9892. block5: {i2, rsp, sum1}
  9893. block7: {i2, rsp, sum1}
  9894. block8: {rsp, sum1}
  9895. \end{lstlisting}
  9896. \end{center}
  9897. Because \code{block7} changed, we analyze \code{block5} once more, but
  9898. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  9899. our approximations have converged, so $m_3$ is the solution.
  9900. This iteration process is guaranteed to converge to a solution by the
  9901. Kleene Fixed-Point Theorem, a general theorem about functions on
  9902. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9903. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9904. elements, a least element $\bot$ (pronounced bottom), and a join
  9905. operator $\sqcup$.\index{lattice}\index{bottom}\index{partial
  9906. ordering}\index{join}\footnote{Technically speaking, we will be
  9907. working with join semi-lattices.} When two elements are ordered $m_i
  9908. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9909. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9910. approximation than $m_i$. The bottom element $\bot$ represents the
  9911. complete lack of information, i.e., the worst approximation. The join
  9912. operator takes two lattice elements and combines their information,
  9913. i.e., it produces the least upper bound of the two.\index{least upper
  9914. bound}
  9915. A dataflow analysis typically involves two lattices: one lattice to
  9916. represent abstract states and another lattice that aggregates the
  9917. abstract states of all the blocks in the control-flow graph. For
  9918. liveness analysis, an abstract state is a set of locations. We form
  9919. the lattice $L$ by taking its elements to be sets of locations, the
  9920. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9921. set, and the join operator to be set union.
  9922. %
  9923. We form a second lattice $M$ by taking its elements to be mappings
  9924. from the block labels to sets of locations (elements of $L$). We
  9925. order the mappings point-wise, using the ordering of $L$. So given any
  9926. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9927. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9928. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9929. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9930. We can think of one iteration of liveness analysis as being a function
  9931. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  9932. mapping.
  9933. \[
  9934. f(m_i) = m_{i+1}
  9935. \]
  9936. Next let us think for a moment about what a final solution $m_s$
  9937. should look like. If we perform liveness analysis using the solution
  9938. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9939. solution should be a \emph{fixed point} of the function $f$.\index{fixed point}
  9940. \[
  9941. f(m_s) = m_s
  9942. \]
  9943. Furthermore, the solution should only include locations that are
  9944. forced to be there by performing liveness analysis on the program, so
  9945. the solution should be the \emph{least} fixed point.\index{least fixed point}
  9946. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9947. monotone (better inputs produce better outputs), then the least fixed
  9948. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9949. chain} obtained by starting at $\bot$ and iterating $f$ as
  9950. follows.\index{Kleene Fixed-Point Theorem}
  9951. \[
  9952. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9953. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9954. \]
  9955. When a lattice contains only finitely-long ascending chains, then
  9956. every Kleene chain tops out at some fixed point after a number of
  9957. iterations of $f$. So that fixed point is also a least upper
  9958. bound of the chain.
  9959. \[
  9960. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9961. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9962. \]
  9963. The liveness analysis is indeed a monotone function and the lattice
  9964. $M$ only has finitely-long ascending chains because there are only a
  9965. finite number of variables and blocks in the program. Thus we are
  9966. guaranteed that iteratively applying liveness analysis to all blocks
  9967. in the program will eventually produce the least fixed point solution.
  9968. Next let us consider dataflow analysis in general and discuss the
  9969. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9970. %
  9971. The algorithm has four parameters: the control-flow graph \code{G}, a
  9972. function \code{transfer} that applies the analysis to one block, the
  9973. \code{bottom} and \code{join} operator for the lattice of abstract
  9974. states. The algorithm begins by creating the bottom mapping,
  9975. represented by a hash table. It then pushes all of the nodes in the
  9976. control-flow graph onto the work list (a queue). The algorithm repeats
  9977. the \code{while} loop as long as there are items in the work list. In
  9978. each iteration, a node is popped from the work list and processed. The
  9979. \code{input} for the node is computed by taking the join of the
  9980. abstract states of all the predecessor nodes. The \code{transfer}
  9981. function is then applied to obtain the \code{output} abstract
  9982. state. If the output differs from the previous state for this block,
  9983. the mapping for this block is updated and its successor nodes are
  9984. pushed onto the work list.
  9985. \begin{figure}[tb]
  9986. \begin{lstlisting}
  9987. (define (analyze-dataflow G transfer bottom join)
  9988. (define mapping (make-hash))
  9989. (for ([v (in-vertices G)])
  9990. (dict-set! mapping v bottom))
  9991. (define worklist (make-queue))
  9992. (for ([v (in-vertices G)])
  9993. (enqueue! worklist v))
  9994. (define trans-G (transpose G))
  9995. (while (not (queue-empty? worklist))
  9996. (define node (dequeue! worklist))
  9997. (define input (for/fold ([state bottom])
  9998. ([pred (in-neighbors trans-G node)])
  9999. (join state (dict-ref mapping pred))))
  10000. (define output (transfer node input))
  10001. (cond [(not (equal? output (dict-ref mapping node)))
  10002. (dict-set! mapping node output)
  10003. (for ([v (in-neighbors G node)])
  10004. (enqueue! worklist v))]))
  10005. mapping)
  10006. \end{lstlisting}
  10007. \caption{Generic work list algorithm for dataflow analysis}
  10008. \label{fig:generic-dataflow}
  10009. \end{figure}
  10010. Having discussed the two complications that arise from adding support
  10011. for assignment and loops, we turn to discussing the one new compiler
  10012. pass and the significant changes to existing passes.
  10013. \section{Convert Assignments}
  10014. \label{sec:convert-assignments}
  10015. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  10016. the combination of assignments and lexically-scoped functions requires
  10017. that we box those variables that are both assigned-to and that appear
  10018. free inside a \code{lambda}. The purpose of the
  10019. \code{convert-assignments} pass is to carry out that transformation.
  10020. We recommend placing this pass after \code{uniquify} but before
  10021. \code{reveal-functions}.
  10022. Consider again the first example from
  10023. Section~\ref{sec:assignment-scoping}:
  10024. \begin{lstlisting}
  10025. (let ([x 0])
  10026. (let ([y 0])
  10027. (let ([z 20])
  10028. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  10029. (begin
  10030. (set! x 10)
  10031. (set! y 12)
  10032. (f y))))))
  10033. \end{lstlisting}
  10034. The variables \code{x} and \code{y} are assigned-to. The variables
  10035. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  10036. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  10037. The boxing of \code{x} consists of three transformations: initialize
  10038. \code{x} with a vector, replace reads from \code{x} with
  10039. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  10040. \code{vector-set!}. The output of \code{convert-assignments} for this
  10041. example is as follows.
  10042. \begin{lstlisting}
  10043. (define (main) : Integer
  10044. (let ([x0 (vector 0)])
  10045. (let ([y1 0])
  10046. (let ([z2 20])
  10047. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  10048. (+ a3 (+ (vector-ref x0 0) z2)))])
  10049. (begin
  10050. (vector-set! x0 0 10)
  10051. (set! y1 12)
  10052. (f4 y1)))))))
  10053. \end{lstlisting}
  10054. \paragraph{Assigned \& Free}
  10055. We recommend defining an auxiliary function named
  10056. \code{assigned\&free} that takes an expression and simultaneously
  10057. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  10058. that occur free within lambda's, and 3) a new version of the
  10059. expression that records which bound variables occurred in the
  10060. intersection of $A$ and $F$. You can use the struct
  10061. \code{AssignedFree} to do this. Consider the case for
  10062. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  10063. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  10064. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  10065. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  10066. \begin{lstlisting}
  10067. (Let |$x$| |$rhs$| |$body$|)
  10068. |$\Rightarrow$|
  10069. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  10070. \end{lstlisting}
  10071. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  10072. The set of assigned variables for this \code{Let} is
  10073. $A_r \cup (A_b - \{x\})$
  10074. and the set of variables free in lambda's is
  10075. $F_r \cup (F_b - \{x\})$.
  10076. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  10077. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  10078. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  10079. and $F_r$.
  10080. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  10081. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  10082. recursively processing \itm{body}. Wrap each of parameter that occurs
  10083. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  10084. Let $P$ be the set of parameter names in \itm{params}. The result is
  10085. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  10086. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  10087. variables of an expression (see Chapter~\ref{ch:Rlam}).
  10088. \paragraph{Convert Assignments}
  10089. Next we discuss the \code{convert-assignment} pass with its auxiliary
  10090. functions for expressions and definitions. The function for
  10091. expressions, \code{cnvt-assign-exp}, should take an expression and a
  10092. set of assigned-and-free variables (obtained from the result of
  10093. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  10094. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  10095. \code{vector-ref}.
  10096. \begin{lstlisting}
  10097. (Var |$x$|)
  10098. |$\Rightarrow$|
  10099. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  10100. \end{lstlisting}
  10101. %
  10102. In the case for $\LET{\LP\code{AssignedFree}\,
  10103. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  10104. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  10105. \itm{body'} but with $x$ added to the set of assigned-and-free
  10106. variables. Translate the let-expression as follows to bind $x$ to a
  10107. boxed value.
  10108. \begin{lstlisting}
  10109. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  10110. |$\Rightarrow$|
  10111. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  10112. \end{lstlisting}
  10113. %
  10114. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  10115. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  10116. variables, translate the \code{set!} into a \code{vector-set!}
  10117. as follows.
  10118. \begin{lstlisting}
  10119. (SetBang |$x$| |$\itm{rhs}$|)
  10120. |$\Rightarrow$|
  10121. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  10122. \end{lstlisting}
  10123. %
  10124. The case for \code{Lambda} is non-trivial, but it is similar to the
  10125. case for function definitions, which we discuss next.
  10126. The auxiliary function for definitions, \code{cnvt-assign-def},
  10127. applies assignment conversion to function definitions.
  10128. We translate a function definition as follows.
  10129. \begin{lstlisting}
  10130. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  10131. |$\Rightarrow$|
  10132. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  10133. \end{lstlisting}
  10134. So it remains to explain \itm{params'} and $\itm{body}_4$.
  10135. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  10136. \code{assigned\&free} on $\itm{body_1}$.
  10137. Let $P$ be the parameter names in \itm{params}.
  10138. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  10139. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  10140. as the set of assigned-and-free variables.
  10141. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  10142. in a sequence of let-expressions that box the parameters
  10143. that are in $A_b \cap F_b$.
  10144. %
  10145. Regarding \itm{params'}, change the names of the parameters that are
  10146. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  10147. variables can retain the original names). Recall the second example in
  10148. Section~\ref{sec:assignment-scoping} involving a counter
  10149. abstraction. The following is the output of assignment version for
  10150. function \code{f}.
  10151. \begin{lstlisting}
  10152. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  10153. (vector
  10154. (lambda: () : Integer x1)
  10155. (lambda: () : Void (set! x1 (+ 1 x1)))))
  10156. |$\Rightarrow$|
  10157. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  10158. (let ([x1 (vector param_x1)])
  10159. (vector (lambda: () : Integer (vector-ref x1 0))
  10160. (lambda: () : Void
  10161. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  10162. \end{lstlisting}
  10163. \section{Remove Complex Operands}
  10164. \label{sec:rco-loop}
  10165. The three new language forms, \code{while}, \code{set!}, and
  10166. \code{begin} are all complex expressions and their subexpressions are
  10167. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  10168. output language \LangFunANF{} of this pass.
  10169. \begin{figure}[tp]
  10170. \centering
  10171. \fbox{
  10172. \begin{minipage}{0.96\textwidth}
  10173. \small
  10174. \[
  10175. \begin{array}{rcl}
  10176. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  10177. \mid \VOID{} } \\
  10178. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10179. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  10180. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10181. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  10182. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  10183. \end{array}
  10184. \]
  10185. \end{minipage}
  10186. }
  10187. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  10188. \label{fig:Rwhile-anf-syntax}
  10189. \end{figure}
  10190. As usual, when a complex expression appears in a grammar position that
  10191. needs to be atomic, such as the argument of a primitive operator, we
  10192. must introduce a temporary variable and bind it to the complex
  10193. expression. This approach applies, unchanged, to handle the new
  10194. language forms. For example, in the following code there are two
  10195. \code{begin} expressions appearing as arguments to \code{+}. The
  10196. output of \code{rco-exp} is shown below, in which the \code{begin}
  10197. expressions have been bound to temporary variables. Recall that
  10198. \code{let} expressions in \LangLoopANF{} are allowed to have
  10199. arbitrary expressions in their right-hand-side expression, so it is
  10200. fine to place \code{begin} there.
  10201. \begin{lstlisting}
  10202. (let ([x0 10])
  10203. (let ([y1 0])
  10204. (+ (+ (begin (set! y1 (read)) x0)
  10205. (begin (set! x0 (read)) y1))
  10206. x0)))
  10207. |$\Rightarrow$|
  10208. (let ([x0 10])
  10209. (let ([y1 0])
  10210. (let ([tmp2 (begin (set! y1 (read)) x0)])
  10211. (let ([tmp3 (begin (set! x0 (read)) y1)])
  10212. (let ([tmp4 (+ tmp2 tmp3)])
  10213. (+ tmp4 x0))))))
  10214. \end{lstlisting}
  10215. \section{Explicate Control and \LangCLoop{}}
  10216. \label{sec:explicate-loop}
  10217. Recall that in the \code{explicate-control} pass we define one helper
  10218. function for each kind of position in the program. For the \LangVar{}
  10219. language of integers and variables we needed kinds of positions:
  10220. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  10221. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  10222. yet another kind of position: effect position. Except for the last
  10223. subexpression, the subexpressions inside a \code{begin} are evaluated
  10224. only for their effect. Their result values are discarded. We can
  10225. generate better code by taking this fact into account.
  10226. The output language of \code{explicate-control} is \LangCLoop{}
  10227. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  10228. \LangCLam{}. The only syntactic difference is that \code{Call},
  10229. \code{vector-set!}, and \code{read} may also appear as statements.
  10230. The most significant difference between \LangCLam{} and \LangCLoop{}
  10231. is that the control-flow graphs of the later may contain cycles.
  10232. \begin{figure}[tp]
  10233. \fbox{
  10234. \begin{minipage}{0.96\textwidth}
  10235. \small
  10236. \[
  10237. \begin{array}{lcl}
  10238. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10239. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  10240. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  10241. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  10242. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  10243. \LangCLoop{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  10244. \end{array}
  10245. \]
  10246. \end{minipage}
  10247. }
  10248. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  10249. \label{fig:c7-syntax}
  10250. \end{figure}
  10251. The new auxiliary function \code{explicate-effect} takes an expression
  10252. (in an effect position) and a promise of a continuation block. The
  10253. function returns a promise for a $\Tail$ that includes the generated
  10254. code for the input expression followed by the continuation block. If
  10255. the expression is obviously pure, that is, never causes side effects,
  10256. then the expression can be removed, so the result is just the
  10257. continuation block.
  10258. %
  10259. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  10260. case. First, you will need a fresh label $\itm{loop}$ for the top of
  10261. the loop. Recursively process the \itm{body} (in effect position)
  10262. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  10263. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  10264. \itm{body'} as the then-branch and the continuation block as the
  10265. else-branch. The result should be added to the control-flow graph with
  10266. the label \itm{loop}. The result for the whole \code{while} loop is a
  10267. \code{goto} to the \itm{loop} label. Note that the loop should only be
  10268. added to the control-flow graph if the loop is indeed used, which can
  10269. be accomplished using \code{delay}.
  10270. The auxiliary functions for tail, assignment, and predicate positions
  10271. need to be updated. The three new language forms, \code{while},
  10272. \code{set!}, and \code{begin}, can appear in assignment and tail
  10273. positions. Only \code{begin} may appear in predicate positions; the
  10274. other two have result type \code{Void}.
  10275. \section{Select Instructions}
  10276. \label{sec:select-instructions-loop}
  10277. Only three small additions are needed in the
  10278. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  10279. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  10280. stand-alone statements instead of only appearing on the right-hand
  10281. side of an assignment statement. The code generation is nearly
  10282. identical; just leave off the instruction for moving the result into
  10283. the left-hand side.
  10284. \section{Register Allocation}
  10285. \label{sec:register-allocation-loop}
  10286. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  10287. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10288. which complicates the liveness analysis needed for register
  10289. allocation.
  10290. \subsection{Liveness Analysis}
  10291. \label{sec:liveness-analysis-r8}
  10292. We recommend using the generic \code{analyze-dataflow} function that
  10293. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  10294. perform liveness analysis, replacing the code in
  10295. \code{uncover-live-CFG} that processed the basic blocks in topological
  10296. order (Section~\ref{sec:liveness-analysis-Rif}).
  10297. The \code{analyze-dataflow} function has four parameters.
  10298. \begin{enumerate}
  10299. \item The first parameter \code{G} should be a directed graph from the
  10300. \code{racket/graph} package (see the sidebar in
  10301. Section~\ref{sec:build-interference}) that represents the
  10302. control-flow graph.
  10303. \item The second parameter \code{transfer} is a function that applies
  10304. liveness analysis to a basic block. It takes two parameters: the
  10305. label for the block to analyze and the live-after set for that
  10306. block. The transfer function should return the live-before set for
  10307. the block. Also, as a side-effect, it should update the block's
  10308. $\itm{info}$ with the liveness information for each instruction. To
  10309. implement the \code{transfer} function, you should be able to reuse
  10310. the code you already have for analyzing basic blocks.
  10311. \item The third and fourth parameters of \code{analyze-dataflow} are
  10312. \code{bottom} and \code{join} for the lattice of abstract states,
  10313. i.e. sets of locations. The bottom of the lattice is the empty set
  10314. \code{(set)} and the join operator is \code{set-union}.
  10315. \end{enumerate}
  10316. \begin{figure}[p]
  10317. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10318. \node (Rfun) at (0,2) {\large \LangLoop{}};
  10319. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  10320. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  10321. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10322. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10323. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10324. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10325. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  10326. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  10327. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  10328. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10329. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10330. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10331. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10332. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10333. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10334. %% \path[->,bend left=15] (Rfun) edge [above] node
  10335. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  10336. \path[->,bend left=15] (Rfun) edge [above] node
  10337. {\ttfamily\footnotesize shrink} (Rfun-2);
  10338. \path[->,bend left=15] (Rfun-2) edge [above] node
  10339. {\ttfamily\footnotesize uniquify} (Rfun-3);
  10340. \path[->,bend left=15] (Rfun-3) edge [above] node
  10341. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  10342. \path[->,bend left=15] (Rfun-4) edge [right] node
  10343. {\ttfamily\footnotesize convert-assignments} (F1-1);
  10344. \path[->,bend left=15] (F1-1) edge [below] node
  10345. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  10346. \path[->,bend right=15] (F1-2) edge [above] node
  10347. {\ttfamily\footnotesize limit-fun.} (F1-3);
  10348. \path[->,bend right=15] (F1-3) edge [above] node
  10349. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10350. \path[->,bend right=15] (F1-4) edge [above] node
  10351. {\ttfamily\footnotesize remove-complex.} (F1-5);
  10352. \path[->,bend right=15] (F1-5) edge [right] node
  10353. {\ttfamily\footnotesize explicate-control} (C3-2);
  10354. \path[->,bend left=15] (C3-2) edge [left] node
  10355. {\ttfamily\footnotesize select-instr.} (x86-2);
  10356. \path[->,bend right=15] (x86-2) edge [left] node
  10357. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10358. \path[->,bend right=15] (x86-2-1) edge [below] node
  10359. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10360. \path[->,bend right=15] (x86-2-2) edge [left] node
  10361. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10362. \path[->,bend left=15] (x86-3) edge [above] node
  10363. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10364. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  10365. \end{tikzpicture}
  10366. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  10367. \label{fig:Rwhile-passes}
  10368. \end{figure}
  10369. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  10370. for the compilation of \LangLoop{}.
  10371. \section{Challenge: Arrays}
  10372. \label{sec:arrays}
  10373. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  10374. elements whose length is determined at compile-time and where each
  10375. element of a tuple may have a different type (they are
  10376. heterogeous). This challenge is also about sequences, but this time
  10377. the length is determined at run-time and all the elements have the same
  10378. type (they are homogeneous). We use the term ``array'' for this later
  10379. kind of sequence.
  10380. The Racket language does not distinguish between tuples and arrays,
  10381. they are both represented by vectors. However, Typed Racket
  10382. distinguishes between tuples and arrays: the \code{Vector} type is for
  10383. tuples and the \code{Vectorof} type is for arrays.
  10384. %
  10385. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  10386. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  10387. and the \code{make-vector} primitive operator for creating an array,
  10388. whose arguments are the length of the array and an initial value for
  10389. all the elements in the array. The \code{vector-length},
  10390. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  10391. for tuples become overloaded for use with arrays.
  10392. %
  10393. We also include integer multiplication in \LangArray{}, as it is
  10394. useful in many examples involving arrays such as computing the
  10395. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  10396. \begin{figure}[tp]
  10397. \centering
  10398. \fbox{
  10399. \begin{minipage}{0.96\textwidth}
  10400. \small
  10401. \[
  10402. \begin{array}{lcl}
  10403. \Type &::=& \ldots \mid \LP \key{Vectorof}~\Type \RP \\
  10404. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10405. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \mid \CMUL{\Exp}{\Exp}\\
  10406. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10407. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10408. \mid \LP\key{and}\;\Exp\;\Exp\RP
  10409. \mid \LP\key{or}\;\Exp\;\Exp\RP
  10410. \mid \LP\key{not}\;\Exp\RP } \\
  10411. &\mid& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10412. &\mid& \gray{ \LP\key{vector}\;\Exp\ldots\RP \mid
  10413. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  10414. &\mid& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\mid \LP\key{void}\RP
  10415. \mid \LP\Exp \; \Exp\ldots\RP } \\
  10416. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  10417. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  10418. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10419. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10420. \mid \CWHILE{\Exp}{\Exp} } \\
  10421. &\mid& \CMAKEVEC{\Exp}{\Exp} \\
  10422. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  10423. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  10424. \end{array}
  10425. \]
  10426. \end{minipage}
  10427. }
  10428. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10429. \label{fig:Rvecof-concrete-syntax}
  10430. \end{figure}
  10431. \begin{figure}[tp]
  10432. \begin{lstlisting}
  10433. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  10434. [n : Integer]) : Integer
  10435. (let ([i 0])
  10436. (let ([prod 0])
  10437. (begin
  10438. (while (< i n)
  10439. (begin
  10440. (set! prod (+ prod (* (vector-ref A i)
  10441. (vector-ref B i))))
  10442. (set! i (+ i 1))
  10443. ))
  10444. prod))))
  10445. (let ([A (make-vector 2 2)])
  10446. (let ([B (make-vector 2 3)])
  10447. (+ (inner-product A B 2)
  10448. 30)))
  10449. \end{lstlisting}
  10450. \caption{Example program that computes the inner-product.}
  10451. \label{fig:inner-product}
  10452. \end{figure}
  10453. The type checker for \LangArray{} is define in
  10454. Figure~\ref{fig:type-check-Rvecof}. The result type of
  10455. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  10456. of the intializing expression. The length expression is required to
  10457. have type \code{Integer}. The type checking of the operators
  10458. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  10459. updated to handle the situation where the vector has type
  10460. \code{Vectorof}. In these cases we translate the operators to their
  10461. \code{vectorof} form so that later passes can easily distinguish
  10462. between operations on tuples versus arrays. We override the
  10463. \code{operator-types} method to provide the type signature for
  10464. multiplication: it takes two integers and returns an integer. To
  10465. support injection and projection of arrays to the \code{Any} type
  10466. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  10467. predicate.
  10468. \begin{figure}[tbp]
  10469. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10470. (define type-check-Rvecof-class
  10471. (class type-check-Rwhile-class
  10472. (super-new)
  10473. (inherit check-type-equal?)
  10474. (define/override (flat-ty? ty)
  10475. (match ty
  10476. ['(Vectorof Any) #t]
  10477. [else (super flat-ty? ty)]))
  10478. (define/override (operator-types)
  10479. (append '((* . ((Integer Integer) . Integer)))
  10480. (super operator-types)))
  10481. (define/override (type-check-exp env)
  10482. (lambda (e)
  10483. (define recur (type-check-exp env))
  10484. (match e
  10485. [(Prim 'make-vector (list e1 e2))
  10486. (define-values (e1^ t1) (recur e1))
  10487. (define-values (e2^ elt-type) (recur e2))
  10488. (define vec-type `(Vectorof ,elt-type))
  10489. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  10490. vec-type)]
  10491. [(Prim 'vector-ref (list e1 e2))
  10492. (define-values (e1^ t1) (recur e1))
  10493. (define-values (e2^ t2) (recur e2))
  10494. (match* (t1 t2)
  10495. [(`(Vectorof ,elt-type) 'Integer)
  10496. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  10497. [(other wise) ((super type-check-exp env) e)])]
  10498. [(Prim 'vector-set! (list e1 e2 e3) )
  10499. (define-values (e-vec t-vec) (recur e1))
  10500. (define-values (e2^ t2) (recur e2))
  10501. (define-values (e-arg^ t-arg) (recur e3))
  10502. (match t-vec
  10503. [`(Vectorof ,elt-type)
  10504. (check-type-equal? elt-type t-arg e)
  10505. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  10506. [else ((super type-check-exp env) e)])]
  10507. [(Prim 'vector-length (list e1))
  10508. (define-values (e1^ t1) (recur e1))
  10509. (match t1
  10510. [`(Vectorof ,t)
  10511. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  10512. [else ((super type-check-exp env) e)])]
  10513. [else ((super type-check-exp env) e)])))
  10514. ))
  10515. (define (type-check-Rvecof p)
  10516. (send (new type-check-Rvecof-class) type-check-program p))
  10517. \end{lstlisting}
  10518. \caption{Type checker for the \LangArray{} language.}
  10519. \label{fig:type-check-Rvecof}
  10520. \end{figure}
  10521. The interpreter for \LangArray{} is defined in
  10522. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  10523. implemented with Racket's \code{make-vector} function and
  10524. multiplication is \code{fx*}, multiplication for \code{fixnum}
  10525. integers.
  10526. \begin{figure}[tbp]
  10527. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10528. (define interp-Rvecof-class
  10529. (class interp-Rwhile-class
  10530. (super-new)
  10531. (define/override (interp-op op)
  10532. (verbose "Rvecof/interp-op" op)
  10533. (match op
  10534. ['make-vector make-vector]
  10535. ['* fx*]
  10536. [else (super interp-op op)]))
  10537. ))
  10538. (define (interp-Rvecof p)
  10539. (send (new interp-Rvecof-class) interp-program p))
  10540. \end{lstlisting}
  10541. \caption{Interpreter for \LangArray{}.}
  10542. \label{fig:interp-Rvecof}
  10543. \end{figure}
  10544. \subsection{Data Representation}
  10545. \label{sec:array-rep}
  10546. Just like tuples, we store arrays on the heap which means that the
  10547. garbage collector will need to inspect arrays. An immediate thought is
  10548. to use the same representation for arrays that we use for tuples.
  10549. However, we limit tuples to a length of $50$ so that their length and
  10550. pointer mask can fit into the 64-bit tag at the beginning of each
  10551. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  10552. millions of elements, so we need more bits to store the length.
  10553. However, because arrays are homogeneous, we only need $1$ bit for the
  10554. pointer mask instead of one bit per array elements. Finally, the
  10555. garbage collector will need to be able to distinguish between tuples
  10556. and arrays, so we need to reserve $1$ bit for that purpose. So we
  10557. arrive at the following layout for the 64-bit tag at the beginning of
  10558. an array:
  10559. \begin{itemize}
  10560. \item The right-most bit is the forwarding bit, just like in a tuple.
  10561. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  10562. it is not.
  10563. \item The next bit to the left is the pointer mask. A $0$ indicates
  10564. that none of the elements are pointers to the heap and a $1$
  10565. indicates that all of the elements are pointers.
  10566. \item The next $61$ bits store the length of the array.
  10567. \item The left-most bit distinguishes between a tuple ($0$) versus an
  10568. array ($1$).
  10569. \end{itemize}
  10570. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  10571. differentiate the kinds of values that have been injected into the
  10572. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  10573. to indicate that the value is an array.
  10574. In the following subsections we provide hints regarding how to update
  10575. the passes to handle arrays.
  10576. \subsection{Reveal Casts}
  10577. The array-access operators \code{vectorof-ref} and
  10578. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  10579. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  10580. that the type checker cannot tell whether the index will be in bounds,
  10581. so the bounds check must be performed at run time. Recall that the
  10582. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  10583. an \code{If} arround a vector reference for update to check whether
  10584. the index is less than the length. You should do the same for
  10585. \code{vectorof-ref} and \code{vectorof-set!} .
  10586. In addition, the handling of the \code{any-vector} operators in
  10587. \code{reveal-casts} needs to be updated to account for arrays that are
  10588. injected to \code{Any}. For the \code{any-vector-length} operator, the
  10589. generated code should test whether the tag is for tuples (\code{010})
  10590. or arrays (\code{110}) and then dispatch to either
  10591. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  10592. we add a case in \code{select-instructions} to generate the
  10593. appropriate instructions for accessing the array length from the
  10594. header of an array.
  10595. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  10596. the generated code needs to check that the index is less than the
  10597. vector length, so like the code for \code{any-vector-length}, check
  10598. the tag to determine whether to use \code{any-vector-length} or
  10599. \code{any-vectorof-length} for this purpose. Once the bounds checking
  10600. is complete, the generated code can use \code{any-vector-ref} and
  10601. \code{any-vector-set!} for both tuples and arrays because the
  10602. instructions used for those operators do not look at the tag at the
  10603. front of the tuple or array.
  10604. \subsection{Expose Allocation}
  10605. This pass should translate the \code{make-vector} operator into
  10606. lower-level operations. In particular, the new AST node
  10607. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  10608. length specified by the $\Exp$, but does not initialize the elements
  10609. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  10610. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  10611. element type for the array. Regarding the initialization of the array,
  10612. we recommend generated a \code{while} loop that uses
  10613. \code{vector-set!} to put the initializing value into every element of
  10614. the array.
  10615. \subsection{Remove Complex Operands}
  10616. Add cases in the \code{rco-atom} and \code{rco-exp} for
  10617. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  10618. complex and its subexpression must be atomic.
  10619. \subsection{Explicate Control}
  10620. Add cases for \code{AllocateArray} to \code{explicate-tail} and
  10621. \code{explicate-assign}.
  10622. \subsection{Select Instructions}
  10623. Generate instructions for \code{AllocateArray} similar to those for
  10624. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  10625. that the tag at the front of the array should instead use the
  10626. representation discussed in Section~\ref{sec:array-rep}.
  10627. Regarding \code{vectorof-length}, extract the length from the tag
  10628. according to the representation discussed in
  10629. Section~\ref{sec:array-rep}.
  10630. The instructions generated for \code{vectorof-ref} differ from those
  10631. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  10632. that the index is not a constant so the offset must be computed at
  10633. runtime, similar to the instructions generated for
  10634. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  10635. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  10636. appear in an assignment and as a stand-alone statement, so make sure
  10637. to handle both situations in this pass.
  10638. Finally, the instructions for \code{any-vectorof-length} should be
  10639. similar to those for \code{vectorof-length}, except that one must
  10640. first project the array by writing zeroes into the $3$-bit tag
  10641. \begin{exercise}\normalfont
  10642. Implement a compiler for the \LangArray{} language by extending your
  10643. compiler for \LangLoop{}. Test your compiler on a half dozen new
  10644. programs, including the one in Figure~\ref{fig:inner-product} and also
  10645. a program that multiplies two matrices. Note that matrices are
  10646. 2-dimensional arrays, but those can be encoded into 1-dimensional
  10647. arrays by laying out each row in the array, one after the next.
  10648. \end{exercise}
  10649. % Further Reading: dataflow analysis
  10650. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10651. \chapter{Gradual Typing}
  10652. \label{ch:Rgrad}
  10653. \index{gradual typing}
  10654. This chapter studies a language, \LangGrad{}, in which the programmer
  10655. can choose between static and dynamic type checking in different parts
  10656. of a program, thereby mixing the statically typed \LangLoop{} language
  10657. with the dynamically typed \LangDyn{}. There are several approaches to
  10658. mixing static and dynamic typing, including multi-language
  10659. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  10660. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  10661. we focus on \emph{gradual typing}\index{gradual typing}, in which the
  10662. programmer controls the amount of static versus dynamic checking by
  10663. adding or removing type annotations on parameters and
  10664. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  10665. %
  10666. The concrete syntax of \LangGrad{} is defined in
  10667. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  10668. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  10669. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  10670. non-terminals that make type annotations optional. The return types
  10671. are not optional in the abstract syntax; the parser fills in
  10672. \code{Any} when the return type is not specified in the concrete
  10673. syntax.
  10674. \begin{figure}[tp]
  10675. \centering
  10676. \fbox{
  10677. \begin{minipage}{0.96\textwidth}
  10678. \small
  10679. \[
  10680. \begin{array}{lcl}
  10681. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10682. \itm{ret} &::=& \epsilon \mid \key{:} \Type \\
  10683. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10684. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  10685. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10686. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10687. \mid (\key{and}\;\Exp\;\Exp)
  10688. \mid (\key{or}\;\Exp\;\Exp)
  10689. \mid (\key{not}\;\Exp) } \\
  10690. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10691. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  10692. (\key{vector-ref}\;\Exp\;\Int)} \\
  10693. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  10694. \mid (\Exp \; \Exp\ldots) } \\
  10695. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  10696. \mid \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  10697. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10698. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10699. \mid \CWHILE{\Exp}{\Exp} } \\
  10700. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  10701. \LangGrad{} &::=& \gray{\Def\ldots \; \Exp}
  10702. \end{array}
  10703. \]
  10704. \end{minipage}
  10705. }
  10706. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10707. \label{fig:Rgrad-concrete-syntax}
  10708. \end{figure}
  10709. \begin{figure}[tp]
  10710. \centering
  10711. \fbox{
  10712. \begin{minipage}{0.96\textwidth}
  10713. \small
  10714. \[
  10715. \begin{array}{lcl}
  10716. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10717. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  10718. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10719. &\mid& \gray{ \BOOL{\itm{bool}}
  10720. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  10721. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  10722. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  10723. &\mid& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  10724. &\mid& \gray{ \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  10725. &\mid& \gray{ \WHILE{\Exp}{\Exp} } \\
  10726. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  10727. \LangGrad{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10728. \end{array}
  10729. \]
  10730. \end{minipage}
  10731. }
  10732. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  10733. \label{fig:Rgrad-syntax}
  10734. \end{figure}
  10735. Both the type checker and the interpreter for \LangGrad{} require some
  10736. interesting changes to enable gradual typing, which we discuss in the
  10737. next two sections in the context of the \code{map-vec} example from
  10738. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  10739. revised the \code{map-vec} example, omitting the type annotations from
  10740. the \code{add1} function.
  10741. \begin{figure}[btp]
  10742. % gradual_test_9.rkt
  10743. \begin{lstlisting}
  10744. (define (map-vec [f : (Integer -> Integer)]
  10745. [v : (Vector Integer Integer)])
  10746. : (Vector Integer Integer)
  10747. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10748. (define (add1 x) (+ x 1))
  10749. (vector-ref (map-vec add1 (vector 0 41)) 1)
  10750. \end{lstlisting}
  10751. \caption{A partially-typed version of the \code{map-vec} example.}
  10752. \label{fig:gradual-map-vec}
  10753. \end{figure}
  10754. \section{Type Checking \LangGrad{}, Casts, and \LangCast{}}
  10755. \label{sec:gradual-type-check}
  10756. The type checker for \LangGrad{} uses the \code{Any} type for missing
  10757. parameter and return types. For example, the \code{x} parameter of
  10758. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  10759. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  10760. consider the \code{+} operator inside \code{add1}. It expects both
  10761. arguments to have type \code{Integer}, but its first argument \code{x}
  10762. has type \code{Any}. In a gradually typed language, such differences
  10763. are allowed so long as the types are \emph{consistent}, that is, they
  10764. are equal except in places where there is an \code{Any} type. The type
  10765. \code{Any} is consistent with every other type.
  10766. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  10767. \begin{figure}[tbp]
  10768. \begin{lstlisting}
  10769. (define/public (consistent? t1 t2)
  10770. (match* (t1 t2)
  10771. [('Integer 'Integer) #t]
  10772. [('Boolean 'Boolean) #t]
  10773. [('Void 'Void) #t]
  10774. [('Any t2) #t]
  10775. [(t1 'Any) #t]
  10776. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10777. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  10778. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10779. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  10780. (consistent? rt1 rt2))]
  10781. [(other wise) #f]))
  10782. \end{lstlisting}
  10783. \caption{The consistency predicate on types.}
  10784. \label{fig:consistent}
  10785. \end{figure}
  10786. Returning to the \code{map-vec} example of
  10787. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  10788. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  10789. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  10790. because the two types are consistent. In particular, \code{->} is
  10791. equal to \code{->} and because \code{Any} is consistent with
  10792. \code{Integer}.
  10793. Next consider a program with an error, such as applying the
  10794. \code{map-vec} to a function that sometimes returns a Boolean, as
  10795. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  10796. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  10797. consistent with the type of parameter \code{f} of \code{map-vec}, that
  10798. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  10799. Integer)}. One might say that a gradual type checker is optimistic
  10800. in that it accepts programs that might execute without a runtime type
  10801. error.
  10802. %
  10803. Unfortunately, running this program with input \code{1} triggers an
  10804. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  10805. performs checking at runtime to ensure the integrity of the static
  10806. types, such as the \code{(Integer -> Integer)} annotation on parameter
  10807. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  10808. new \code{Cast} form that is inserted by the type checker. Thus, the
  10809. output of the type checker is a program in the \LangCast{} language, which
  10810. adds \code{Cast} to \LangLoop{}, as shown in
  10811. Figure~\ref{fig:Rgrad-prime-syntax}.
  10812. \begin{figure}[tp]
  10813. \centering
  10814. \fbox{
  10815. \begin{minipage}{0.96\textwidth}
  10816. \small
  10817. \[
  10818. \begin{array}{lcl}
  10819. \Exp &::=& \ldots \mid \CAST{\Exp}{\Type}{\Type} \\
  10820. \LangCast{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10821. \end{array}
  10822. \]
  10823. \end{minipage}
  10824. }
  10825. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  10826. \label{fig:Rgrad-prime-syntax}
  10827. \end{figure}
  10828. \begin{figure}[tbp]
  10829. \begin{lstlisting}
  10830. (define (map-vec [f : (Integer -> Integer)]
  10831. [v : (Vector Integer Integer)])
  10832. : (Vector Integer Integer)
  10833. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10834. (define (add1 x) (+ x 1))
  10835. (define (true) #t)
  10836. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  10837. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  10838. \end{lstlisting}
  10839. \caption{A variant of the \code{map-vec} example with an error.}
  10840. \label{fig:map-vec-maybe-add1}
  10841. \end{figure}
  10842. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  10843. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  10844. inserted every time the type checker sees two types that are
  10845. consistent but not equal. In the \code{add1} function, \code{x} is
  10846. cast to \code{Integer} and the result of the \code{+} is cast to
  10847. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  10848. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  10849. \begin{figure}[btp]
  10850. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10851. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  10852. : (Vector Integer Integer)
  10853. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10854. (define (add1 [x : Any]) : Any
  10855. (cast (+ (cast x Any Integer) 1) Integer Any))
  10856. (define (true) : Any (cast #t Boolean Any))
  10857. (define (maybe-add1 [x : Any]) : Any
  10858. (if (eq? 0 (read)) (add1 x) (true)))
  10859. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  10860. (vector 0 41)) 0)
  10861. \end{lstlisting}
  10862. \caption{Output of type checking \code{map-vec}
  10863. and \code{maybe-add1}.}
  10864. \label{fig:map-vec-cast}
  10865. \end{figure}
  10866. The type checker for \LangGrad{} is defined in
  10867. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  10868. and \ref{fig:type-check-Rgradual-3}.
  10869. \begin{figure}[tbp]
  10870. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10871. (define type-check-gradual-class
  10872. (class type-check-Rwhile-class
  10873. (super-new)
  10874. (inherit operator-types type-predicates)
  10875. (define/override (type-check-exp env)
  10876. (lambda (e)
  10877. (define recur (type-check-exp env))
  10878. (match e
  10879. [(Prim 'vector-length (list e1))
  10880. (define-values (e1^ t) (recur e1))
  10881. (match t
  10882. [`(Vector ,ts ...)
  10883. (values (Prim 'vector-length (list e1^)) 'Integer)]
  10884. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  10885. [(Prim 'vector-ref (list e1 e2))
  10886. (define-values (e1^ t1) (recur e1))
  10887. (define-values (e2^ t2) (recur e2))
  10888. (check-consistent? t2 'Integer e)
  10889. (match t1
  10890. [`(Vector ,ts ...)
  10891. (match e2^
  10892. [(Int i)
  10893. (unless (and (0 . <= . i) (i . < . (length ts)))
  10894. (error 'type-check "invalid index ~a in ~a" i e))
  10895. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10896. [else (define e1^^ (make-cast e1^ t1 'Any))
  10897. (define e2^^ (make-cast e2^ t2 'Integer))
  10898. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  10899. ['Any
  10900. (define e2^^ (make-cast e2^ t2 'Integer))
  10901. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  10902. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10903. [(Prim 'vector-set! (list e1 e2 e3) )
  10904. (define-values (e1^ t1) (recur e1))
  10905. (define-values (e2^ t2) (recur e2))
  10906. (define-values (e3^ t3) (recur e3))
  10907. (check-consistent? t2 'Integer e)
  10908. (match t1
  10909. [`(Vector ,ts ...)
  10910. (match e2^
  10911. [(Int i)
  10912. (unless (and (0 . <= . i) (i . < . (length ts)))
  10913. (error 'type-check "invalid index ~a in ~a" i e))
  10914. (check-consistent? (list-ref ts i) t3 e)
  10915. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  10916. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  10917. [else
  10918. (define e1^^ (make-cast e1^ t1 'Any))
  10919. (define e2^^ (make-cast e2^ t2 'Integer))
  10920. (define e3^^ (make-cast e3^ t3 'Any))
  10921. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  10922. ['Any
  10923. (define e2^^ (make-cast e2^ t2 'Integer))
  10924. (define e3^^ (make-cast e3^ t3 'Any))
  10925. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  10926. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10927. \end{lstlisting}
  10928. \caption{Type checker for the \LangGrad{} language, part 1.}
  10929. \label{fig:type-check-Rgradual-1}
  10930. \end{figure}
  10931. \begin{figure}[tbp]
  10932. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10933. [(Prim 'eq? (list e1 e2))
  10934. (define-values (e1^ t1) (recur e1))
  10935. (define-values (e2^ t2) (recur e2))
  10936. (check-consistent? t1 t2 e)
  10937. (define T (meet t1 t2))
  10938. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  10939. 'Boolean)]
  10940. [(Prim 'not (list e1))
  10941. (define-values (e1^ t1) (recur e1))
  10942. (match t1
  10943. ['Any
  10944. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  10945. (Bool #t) (Bool #f)))]
  10946. [else
  10947. (define-values (t-ret new-es^)
  10948. (type-check-op 'not (list t1) (list e1^) e))
  10949. (values (Prim 'not new-es^) t-ret)])]
  10950. [(Prim 'and (list e1 e2))
  10951. (recur (If e1 e2 (Bool #f)))]
  10952. [(Prim 'or (list e1 e2))
  10953. (define tmp (gensym 'tmp))
  10954. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  10955. [(Prim op es)
  10956. #:when (not (set-member? explicit-prim-ops op))
  10957. (define-values (new-es ts)
  10958. (for/lists (exprs types) ([e es])
  10959. (recur e)))
  10960. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  10961. (values (Prim op new-es^) t-ret)]
  10962. [(If e1 e2 e3)
  10963. (define-values (e1^ T1) (recur e1))
  10964. (define-values (e2^ T2) (recur e2))
  10965. (define-values (e3^ T3) (recur e3))
  10966. (check-consistent? T2 T3 e)
  10967. (match T1
  10968. ['Boolean
  10969. (define Tif (join T2 T3))
  10970. (values (If e1^ (make-cast e2^ T2 Tif)
  10971. (make-cast e3^ T3 Tif)) Tif)]
  10972. ['Any
  10973. (define Tif (meet T2 T3))
  10974. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  10975. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  10976. Tif)]
  10977. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  10978. [(HasType e1 T)
  10979. (define-values (e1^ T1) (recur e1))
  10980. (check-consistent? T1 T)
  10981. (values (make-cast e1^ T1 T) T)]
  10982. [(SetBang x e1)
  10983. (define-values (e1^ T1) (recur e1))
  10984. (define varT (dict-ref env x))
  10985. (check-consistent? T1 varT e)
  10986. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  10987. [(WhileLoop e1 e2)
  10988. (define-values (e1^ T1) (recur e1))
  10989. (check-consistent? T1 'Boolean e)
  10990. (define-values (e2^ T2) ((type-check-exp env) e2))
  10991. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  10992. \end{lstlisting}
  10993. \caption{Type checker for the \LangGrad{} language, part 2.}
  10994. \label{fig:type-check-Rgradual-2}
  10995. \end{figure}
  10996. \begin{figure}[tbp]
  10997. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10998. [(Apply e1 e2s)
  10999. (define-values (e1^ T1) (recur e1))
  11000. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  11001. (match T1
  11002. [`(,T1ps ... -> ,T1rt)
  11003. (for ([T2 T2s] [Tp T1ps])
  11004. (check-consistent? T2 Tp e))
  11005. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  11006. (make-cast e2 src tgt)))
  11007. (values (Apply e1^ e2s^^) T1rt)]
  11008. [`Any
  11009. (define e1^^ (make-cast e1^ 'Any
  11010. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  11011. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  11012. (make-cast e2 src 'Any)))
  11013. (values (Apply e1^^ e2s^^) 'Any)]
  11014. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  11015. [(Lambda params Tr e1)
  11016. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  11017. (match p
  11018. [`[,x : ,T] (values x T)]
  11019. [(? symbol? x) (values x 'Any)])))
  11020. (define-values (e1^ T1)
  11021. ((type-check-exp (append (map cons xs Ts) env)) e1))
  11022. (check-consistent? Tr T1 e)
  11023. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  11024. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  11025. [else ((super type-check-exp env) e)]
  11026. )))
  11027. \end{lstlisting}
  11028. \caption{Type checker for the \LangGrad{} language, part 3.}
  11029. \label{fig:type-check-Rgradual-3}
  11030. \end{figure}
  11031. \begin{figure}[tbp]
  11032. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11033. (define/public (join t1 t2)
  11034. (match* (t1 t2)
  11035. [('Integer 'Integer) 'Integer]
  11036. [('Boolean 'Boolean) 'Boolean]
  11037. [('Void 'Void) 'Void]
  11038. [('Any t2) t2]
  11039. [(t1 'Any) t1]
  11040. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11041. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  11042. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11043. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  11044. -> ,(join rt1 rt2))]))
  11045. (define/public (meet t1 t2)
  11046. (match* (t1 t2)
  11047. [('Integer 'Integer) 'Integer]
  11048. [('Boolean 'Boolean) 'Boolean]
  11049. [('Void 'Void) 'Void]
  11050. [('Any t2) 'Any]
  11051. [(t1 'Any) 'Any]
  11052. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11053. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  11054. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11055. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  11056. -> ,(meet rt1 rt2))]))
  11057. (define/public (make-cast e src tgt)
  11058. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  11059. (define/public (check-consistent? t1 t2 e)
  11060. (unless (consistent? t1 t2)
  11061. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  11062. (define/override (type-check-op op arg-types args e)
  11063. (match (dict-ref (operator-types) op)
  11064. [`(,param-types . ,return-type)
  11065. (for ([at arg-types] [pt param-types])
  11066. (check-consistent? at pt e))
  11067. (values return-type
  11068. (for/list ([e args] [s arg-types] [t param-types])
  11069. (make-cast e s t)))]
  11070. [else (error 'type-check-op "unrecognized ~a" op)]))
  11071. (define explicit-prim-ops
  11072. (set-union
  11073. (type-predicates)
  11074. (set 'procedure-arity 'eq?
  11075. 'vector 'vector-length 'vector-ref 'vector-set!
  11076. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  11077. (define/override (fun-def-type d)
  11078. (match d
  11079. [(Def f params rt info body)
  11080. (define ps
  11081. (for/list ([p params])
  11082. (match p
  11083. [`[,x : ,T] T]
  11084. [(? symbol?) 'Any]
  11085. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  11086. `(,@ps -> ,rt)]
  11087. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  11088. \end{lstlisting}
  11089. \caption{Auxiliary functions for type checking \LangGrad{}.}
  11090. \label{fig:type-check-Rgradual-aux}
  11091. \end{figure}
  11092. \clearpage
  11093. \section{Interpreting \LangCast{}}
  11094. \label{sec:interp-casts}
  11095. The runtime behavior of first-order casts is straightforward, that is,
  11096. casts involving simple types such as \code{Integer} and
  11097. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  11098. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  11099. puts the integer into a tagged value
  11100. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  11101. \code{Integer} is accomplished with the \code{Project} operator, that
  11102. is, by checking the value's tag and either retrieving the underlying
  11103. integer or signaling an error if it the tag is not the one for
  11104. integers (Figure~\ref{fig:apply-project}).
  11105. %
  11106. Things get more interesting for higher-order casts, that is, casts
  11107. involving function or vector types.
  11108. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  11109. Any)} to \code{(Integer -> Integer)}. When a function flows through
  11110. this cast at runtime, we can't know in general whether the function
  11111. will always return an integer.\footnote{Predicting the return value of
  11112. a function is equivalent to the halting problem, which is
  11113. undecidable.} The \LangCast{} interpreter therefore delays the checking
  11114. of the cast until the function is applied. This is accomplished by
  11115. wrapping \code{maybe-add1} in a new function that casts its parameter
  11116. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  11117. casts the return value from \code{Any} to \code{Integer}.
  11118. Turning our attention to casts involving vector types, we consider the
  11119. example in Figure~\ref{fig:map-vec-bang} that defines a
  11120. partially-typed version of \code{map-vec} whose parameter \code{v} has
  11121. type \code{(Vector Any Any)} and that updates \code{v} in place
  11122. instead of returning a new vector. So we name this function
  11123. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  11124. the type checker inserts a cast from \code{(Vector Integer Integer)}
  11125. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  11126. cast between vector types would be a build a new vector whose elements
  11127. are the result of casting each of the original elements to the
  11128. appropriate target type. However, this approach is only valid for
  11129. immutable vectors; and our vectors are mutable. In the example of
  11130. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  11131. the updates inside of \code{map-vec!} would happen to the new vector
  11132. and not the original one.
  11133. \begin{figure}[tbp]
  11134. % gradual_test_11.rkt
  11135. \begin{lstlisting}
  11136. (define (map-vec! [f : (Any -> Any)]
  11137. [v : (Vector Any Any)]) : Void
  11138. (begin
  11139. (vector-set! v 0 (f (vector-ref v 0)))
  11140. (vector-set! v 1 (f (vector-ref v 1)))))
  11141. (define (add1 x) (+ x 1))
  11142. (let ([v (vector 0 41)])
  11143. (begin (map-vec! add1 v) (vector-ref v 1)))
  11144. \end{lstlisting}
  11145. \caption{An example involving casts on vectors.}
  11146. \label{fig:map-vec-bang}
  11147. \end{figure}
  11148. Instead the interpreter needs to create a new kind of value, a
  11149. \emph{vector proxy}, that intercepts every vector operation. On a
  11150. read, the proxy reads from the underlying vector and then applies a
  11151. cast to the resulting value. On a write, the proxy casts the argument
  11152. value and then performs the write to the underlying vector. For the
  11153. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  11154. \code{0} from \code{Integer} to \code{Any}. For the first
  11155. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  11156. to \code{Integer}.
  11157. The final category of cast that we need to consider are casts between
  11158. the \code{Any} type and either a function or a vector
  11159. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  11160. in which parameter \code{v} does not have a type annotation, so it is
  11161. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  11162. type \code{(Vector Integer Integer)} so the type checker inserts a
  11163. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  11164. thought is to use \code{Inject}, but that doesn't work because
  11165. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  11166. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  11167. to \code{Any}.
  11168. \begin{figure}[tbp]
  11169. \begin{lstlisting}
  11170. (define (map-vec! [f : (Any -> Any)] v) : Void
  11171. (begin
  11172. (vector-set! v 0 (f (vector-ref v 0)))
  11173. (vector-set! v 1 (f (vector-ref v 1)))))
  11174. (define (add1 x) (+ x 1))
  11175. (let ([v (vector 0 41)])
  11176. (begin (map-vec! add1 v) (vector-ref v 1)))
  11177. \end{lstlisting}
  11178. \caption{Casting a vector to \code{Any}.}
  11179. \label{fig:map-vec-any}
  11180. \end{figure}
  11181. The \LangCast{} interpreter uses an auxiliary function named
  11182. \code{apply-cast} to cast a value from a source type to a target type,
  11183. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  11184. of the kinds of casts that we've discussed in this section.
  11185. \begin{figure}[tbp]
  11186. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11187. (define/public (apply-cast v s t)
  11188. (match* (s t)
  11189. [(t1 t2) #:when (equal? t1 t2) v]
  11190. [('Any t2)
  11191. (match t2
  11192. [`(,ts ... -> ,rt)
  11193. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11194. (define v^ (apply-project v any->any))
  11195. (apply-cast v^ any->any `(,@ts -> ,rt))]
  11196. [`(Vector ,ts ...)
  11197. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11198. (define v^ (apply-project v vec-any))
  11199. (apply-cast v^ vec-any `(Vector ,@ts))]
  11200. [else (apply-project v t2)])]
  11201. [(t1 'Any)
  11202. (match t1
  11203. [`(,ts ... -> ,rt)
  11204. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11205. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  11206. (apply-inject v^ (any-tag any->any))]
  11207. [`(Vector ,ts ...)
  11208. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11209. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  11210. (apply-inject v^ (any-tag vec-any))]
  11211. [else (apply-inject v (any-tag t1))])]
  11212. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11213. (define x (gensym 'x))
  11214. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  11215. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  11216. (define cast-writes
  11217. (for/list ([t1 ts1] [t2 ts2])
  11218. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  11219. `(vector-proxy ,(vector v (apply vector cast-reads)
  11220. (apply vector cast-writes)))]
  11221. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11222. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  11223. `(function ,xs ,(Cast
  11224. (Apply (Value v)
  11225. (for/list ([x xs][t1 ts1][t2 ts2])
  11226. (Cast (Var x) t2 t1)))
  11227. rt1 rt2) ())]
  11228. ))
  11229. \end{lstlisting}
  11230. \caption{The \code{apply-cast} auxiliary method.}
  11231. \label{fig:apply-cast}
  11232. \end{figure}
  11233. The interpreter for \LangCast{} is defined in
  11234. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  11235. dispatching to \code{apply-cast}. To handle the addition of vector
  11236. proxies, we update the vector primitives in \code{interp-op} using the
  11237. functions in Figure~\ref{fig:guarded-vector}.
  11238. \begin{figure}[tbp]
  11239. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11240. (define interp-Rcast-class
  11241. (class interp-Rwhile-class
  11242. (super-new)
  11243. (inherit apply-fun apply-inject apply-project)
  11244. (define/override (interp-op op)
  11245. (match op
  11246. ['vector-length guarded-vector-length]
  11247. ['vector-ref guarded-vector-ref]
  11248. ['vector-set! guarded-vector-set!]
  11249. ['any-vector-ref (lambda (v i)
  11250. (match v [`(tagged ,v^ ,tg)
  11251. (guarded-vector-ref v^ i)]))]
  11252. ['any-vector-set! (lambda (v i a)
  11253. (match v [`(tagged ,v^ ,tg)
  11254. (guarded-vector-set! v^ i a)]))]
  11255. ['any-vector-length (lambda (v)
  11256. (match v [`(tagged ,v^ ,tg)
  11257. (guarded-vector-length v^)]))]
  11258. [else (super interp-op op)]
  11259. ))
  11260. (define/override ((interp-exp env) e)
  11261. (define (recur e) ((interp-exp env) e))
  11262. (match e
  11263. [(Value v) v]
  11264. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  11265. [else ((super interp-exp env) e)]))
  11266. ))
  11267. (define (interp-Rcast p)
  11268. (send (new interp-Rcast-class) interp-program p))
  11269. \end{lstlisting}
  11270. \caption{The interpreter for \LangCast{}.}
  11271. \label{fig:interp-Rcast}
  11272. \end{figure}
  11273. \begin{figure}[tbp]
  11274. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11275. (define (guarded-vector-ref vec i)
  11276. (match vec
  11277. [`(vector-proxy ,proxy)
  11278. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  11279. (define rd (vector-ref (vector-ref proxy 1) i))
  11280. (apply-fun rd (list val) 'guarded-vector-ref)]
  11281. [else (vector-ref vec i)]))
  11282. (define (guarded-vector-set! vec i arg)
  11283. (match vec
  11284. [`(vector-proxy ,proxy)
  11285. (define wr (vector-ref (vector-ref proxy 2) i))
  11286. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  11287. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  11288. [else (vector-set! vec i arg)]))
  11289. (define (guarded-vector-length vec)
  11290. (match vec
  11291. [`(vector-proxy ,proxy)
  11292. (guarded-vector-length (vector-ref proxy 0))]
  11293. [else (vector-length vec)]))
  11294. \end{lstlisting}
  11295. \caption{The guarded-vector auxiliary functions.}
  11296. \label{fig:guarded-vector}
  11297. \end{figure}
  11298. \section{Lower Casts}
  11299. \label{sec:lower-casts}
  11300. The next step in the journey towards x86 is the \code{lower-casts}
  11301. pass that translates the casts in \LangCast{} to the lower-level
  11302. \code{Inject} and \code{Project} operators and a new operator for
  11303. creating vector proxies, extending the \LangLoop{} language to create
  11304. \LangProxy{}. We recommend creating an auxiliary function named
  11305. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  11306. and a target type, and translates it to expression in \LangProxy{} that has
  11307. the same behavior as casting the expression from the source to the
  11308. target type in the interpreter.
  11309. The \code{lower-cast} function can follow a code structure similar to
  11310. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  11311. the interpreter for \LangCast{} because it must handle the same cases as
  11312. \code{apply-cast} and it needs to mimic the behavior of
  11313. \code{apply-cast}. The most interesting cases are those concerning the
  11314. casts between two vector types and between two function types.
  11315. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  11316. type to another vector type is accomplished by creating a proxy that
  11317. intercepts the operations on the underlying vector. Here we make the
  11318. creation of the proxy explicit with the \code{vector-proxy} primitive
  11319. operation. It takes three arguments, the first is an expression for
  11320. the vector, the second is a vector of functions for casting an element
  11321. that is being read from the vector, and the third is a vector of
  11322. functions for casting an element that is being written to the vector.
  11323. You can create the functions using \code{Lambda}. Also, as we shall
  11324. see in the next section, we need to differentiate these vectors from
  11325. the user-created ones, so we recommend using a new primitive operator
  11326. named \code{raw-vector} instead of \code{vector} to create these
  11327. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  11328. the output of \code{lower-casts} on the example in
  11329. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  11330. integers to a vector of \code{Any}.
  11331. \begin{figure}[tbp]
  11332. \begin{lstlisting}
  11333. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  11334. (begin
  11335. (vector-set! v 0 (f (vector-ref v 0)))
  11336. (vector-set! v 1 (f (vector-ref v 1)))))
  11337. (define (add1 [x : Any]) : Any
  11338. (inject (+ (project x Integer) 1) Integer))
  11339. (let ([v (vector 0 41)])
  11340. (begin
  11341. (map-vec! add1 (vector-proxy v
  11342. (raw-vector (lambda: ([x9 : Integer]) : Any
  11343. (inject x9 Integer))
  11344. (lambda: ([x9 : Integer]) : Any
  11345. (inject x9 Integer)))
  11346. (raw-vector (lambda: ([x9 : Any]) : Integer
  11347. (project x9 Integer))
  11348. (lambda: ([x9 : Any]) : Integer
  11349. (project x9 Integer)))))
  11350. (vector-ref v 1)))
  11351. \end{lstlisting}
  11352. \caption{Output of \code{lower-casts} on the example in
  11353. Figure~\ref{fig:map-vec-bang}.}
  11354. \label{fig:map-vec-bang-lower-cast}
  11355. \end{figure}
  11356. A cast from one function type to another function type is accomplished
  11357. by generating a \code{Lambda} whose parameter and return types match
  11358. the target function type. The body of the \code{Lambda} should cast
  11359. the parameters from the target type to the source type (yes,
  11360. backwards! functions are contravariant\index{contravariant} in the
  11361. parameters), then call the underlying function, and finally cast the
  11362. result from the source return type to the target return type.
  11363. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  11364. \code{lower-casts} pass on the \code{map-vec} example in
  11365. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  11366. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  11367. \begin{figure}[tbp]
  11368. \begin{lstlisting}
  11369. (define (map-vec [f : (Integer -> Integer)]
  11370. [v : (Vector Integer Integer)])
  11371. : (Vector Integer Integer)
  11372. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11373. (define (add1 [x : Any]) : Any
  11374. (inject (+ (project x Integer) 1) Integer))
  11375. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  11376. (project (add1 (inject x9 Integer)) Integer))
  11377. (vector 0 41)) 1)
  11378. \end{lstlisting}
  11379. \caption{Output of \code{lower-casts} on the example in
  11380. Figure~\ref{fig:gradual-map-vec}.}
  11381. \label{fig:map-vec-lower-cast}
  11382. \end{figure}
  11383. \section{Differentiate Proxies}
  11384. \label{sec:differentiate-proxies}
  11385. So far the job of differentiating vectors and vector proxies has been
  11386. the job of the interpreter. For example, the interpreter for \LangCast{}
  11387. implements \code{vector-ref} using the \code{guarded-vector-ref}
  11388. function in Figure~\ref{fig:guarded-vector}. In the
  11389. \code{differentiate-proxies} pass we shift this responsibility to the
  11390. generated code.
  11391. We begin by designing the output language $R^p_8$. In
  11392. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  11393. proxies. In $R^p_8$ we return the \code{Vector} type to
  11394. its original meaning, as the type of real vectors, and we introduce a
  11395. new type, \code{PVector}, whose values can be either real vectors or
  11396. vector proxies. This new type comes with a suite of new primitive
  11397. operations for creating and using values of type \code{PVector}. We
  11398. don't need to introduce a new type to represent vector proxies. A
  11399. proxy is represented by a vector containing three things: 1) the
  11400. underlying vector, 2) a vector of functions for casting elements that
  11401. are read from the vector, and 3) a vector of functions for casting
  11402. values to be written to the vector. So we define the following
  11403. abbreviation for the type of a vector proxy:
  11404. \[
  11405. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  11406. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  11407. \to (\key{PVector}~ T' \ldots)
  11408. \]
  11409. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  11410. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  11411. %
  11412. Next we describe each of the new primitive operations.
  11413. \begin{description}
  11414. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  11415. (\key{PVector} $T \ldots$)]\ \\
  11416. %
  11417. This operation brands a vector as a value of the \code{PVector} type.
  11418. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  11419. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  11420. %
  11421. This operation brands a vector proxy as value of the \code{PVector} type.
  11422. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  11423. \code{Boolean}] \ \\
  11424. %
  11425. returns true if the value is a vector proxy and false if it is a
  11426. real vector.
  11427. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  11428. (\key{Vector} $T \ldots$)]\ \\
  11429. %
  11430. Assuming that the input is a vector (and not a proxy), this
  11431. operation returns the vector.
  11432. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  11433. $\to$ \code{Boolean}]\ \\
  11434. %
  11435. Given a vector proxy, this operation returns the length of the
  11436. underlying vector.
  11437. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  11438. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  11439. %
  11440. Given a vector proxy, this operation returns the $i$th element of
  11441. the underlying vector.
  11442. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  11443. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  11444. proxy, this operation writes a value to the $i$th element of the
  11445. underlying vector.
  11446. \end{description}
  11447. Now to discuss the translation that differentiates vectors from
  11448. proxies. First, every type annotation in the program must be
  11449. translated (recursively) to replace \code{Vector} with \code{PVector}.
  11450. Next, we must insert uses of \code{PVector} operations in the
  11451. appropriate places. For example, we wrap every vector creation with an
  11452. \code{inject-vector}.
  11453. \begin{lstlisting}
  11454. (vector |$e_1 \ldots e_n$|)
  11455. |$\Rightarrow$|
  11456. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  11457. \end{lstlisting}
  11458. The \code{raw-vector} operator that we introduced in the previous
  11459. section does not get injected.
  11460. \begin{lstlisting}
  11461. (raw-vector |$e_1 \ldots e_n$|)
  11462. |$\Rightarrow$|
  11463. (vector |$e'_1 \ldots e'_n$|)
  11464. \end{lstlisting}
  11465. The \code{vector-proxy} primitive translates as follows.
  11466. \begin{lstlisting}
  11467. (vector-proxy |$e_1~e_2~e_3$|)
  11468. |$\Rightarrow$|
  11469. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  11470. \end{lstlisting}
  11471. We translate the vector operations into conditional expressions that
  11472. check whether the value is a proxy and then dispatch to either the
  11473. appropriate proxy vector operation or the regular vector operation.
  11474. For example, the following is the translation for \code{vector-ref}.
  11475. \begin{lstlisting}
  11476. (vector-ref |$e_1$| |$i$|)
  11477. |$\Rightarrow$|
  11478. (let ([|$v~e_1$|])
  11479. (if (proxy? |$v$|)
  11480. (proxy-vector-ref |$v$| |$i$|)
  11481. (vector-ref (project-vector |$v$|) |$i$|)
  11482. \end{lstlisting}
  11483. Note in the case of a real vector, we must apply \code{project-vector}
  11484. before the \code{vector-ref}.
  11485. \section{Reveal Casts}
  11486. \label{sec:reveal-casts-gradual}
  11487. Recall that the \code{reveal-casts} pass
  11488. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  11489. \code{Inject} and \code{Project} into lower-level operations. In
  11490. particular, \code{Project} turns into a conditional expression that
  11491. inspects the tag and retrieves the underlying value. Here we need to
  11492. augment the translation of \code{Project} to handle the situation when
  11493. the target type is \code{PVector}. Instead of using
  11494. \code{vector-length} we need to use \code{proxy-vector-length}.
  11495. \begin{lstlisting}
  11496. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  11497. |$\Rightarrow$|
  11498. (let |$\itm{tmp}$| |$e'$|
  11499. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  11500. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  11501. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  11502. (exit)))
  11503. \end{lstlisting}
  11504. \section{Closure Conversion}
  11505. \label{sec:closure-conversion-gradual}
  11506. The closure conversion pass only requires one minor adjustment. The
  11507. auxiliary function that translates type annotations needs to be
  11508. updated to handle the \code{PVector} type.
  11509. \section{Explicate Control}
  11510. \label{sec:explicate-control-gradual}
  11511. Update the \code{explicate-control} pass to handle the new primitive
  11512. operations on the \code{PVector} type.
  11513. \section{Select Instructions}
  11514. \label{sec:select-instructions-gradual}
  11515. Recall that the \code{select-instructions} pass is responsible for
  11516. lowering the primitive operations into x86 instructions. So we need
  11517. to translate the new \code{PVector} operations to x86. To do so, the
  11518. first question we need to answer is how will we differentiate the two
  11519. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  11520. We need just one bit to accomplish this, and use the bit in position
  11521. $57$ of the 64-bit tag at the front of every vector (see
  11522. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  11523. for \code{inject-vector} we leave it that way.
  11524. \begin{lstlisting}
  11525. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  11526. |$\Rightarrow$|
  11527. movq |$e'_1$|, |$\itm{lhs'}$|
  11528. \end{lstlisting}
  11529. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  11530. \begin{lstlisting}
  11531. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  11532. |$\Rightarrow$|
  11533. movq |$e'_1$|, %r11
  11534. movq |$(1 << 57)$|, %rax
  11535. orq 0(%r11), %rax
  11536. movq %rax, 0(%r11)
  11537. movq %r11, |$\itm{lhs'}$|
  11538. \end{lstlisting}
  11539. The \code{proxy?} operation consumes the information so carefully
  11540. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  11541. isolates the $57$th bit to tell whether the value is a real vector or
  11542. a proxy.
  11543. \begin{lstlisting}
  11544. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  11545. |$\Rightarrow$|
  11546. movq |$e_1'$|, %r11
  11547. movq 0(%r11), %rax
  11548. sarq $57, %rax
  11549. andq $1, %rax
  11550. movq %rax, |$\itm{lhs'}$|
  11551. \end{lstlisting}
  11552. The \code{project-vector} operation is straightforward to translate,
  11553. so we leave it up to the reader.
  11554. Regarding the \code{proxy-vector} operations, the runtime provides
  11555. procedures that implement them (they are recursive functions!) so
  11556. here we simply need to translate these vector operations into the
  11557. appropriate function call. For example, here is the translation for
  11558. \code{proxy-vector-ref}.
  11559. \begin{lstlisting}
  11560. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  11561. |$\Rightarrow$|
  11562. movq |$e_1'$|, %rdi
  11563. movq |$e_2'$|, %rsi
  11564. callq proxy_vector_ref
  11565. movq %rax, |$\itm{lhs'}$|
  11566. \end{lstlisting}
  11567. We have another batch of vector operations to deal with, those for the
  11568. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  11569. \code{any-vector-ref} when there is a \code{vector-ref} on something
  11570. of type \code{Any}, and similarly for \code{any-vector-set!} and
  11571. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  11572. Section~\ref{sec:select-Rany} we selected instructions for these
  11573. operations based on the idea that the underlying value was a real
  11574. vector. But in the current setting, the underlying value is of type
  11575. \code{PVector}. So \code{any-vector-ref} can be translates to
  11576. pseudo-x86 as follows. We begin by projecting the underlying value out
  11577. of the tagged value and then call the \code{proxy\_vector\_ref}
  11578. procedure in the runtime.
  11579. \begin{lstlisting}
  11580. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  11581. movq |$\neg 111$|, %rdi
  11582. andq |$e_1'$|, %rdi
  11583. movq |$e_2'$|, %rsi
  11584. callq proxy_vector_ref
  11585. movq %rax, |$\itm{lhs'}$|
  11586. \end{lstlisting}
  11587. The \code{any-vector-set!} and \code{any-vector-length} operators can
  11588. be translated in a similar way.
  11589. \begin{exercise}\normalfont
  11590. Implement a compiler for the gradually-typed \LangGrad{} language by
  11591. extending and adapting your compiler for \LangLoop{}. Create 10 new
  11592. partially-typed test programs. In addition to testing with these
  11593. new programs, also test your compiler on all the tests for \LangLoop{}
  11594. and tests for \LangDyn{}. Sometimes you may get a type checking error
  11595. on the \LangDyn{} programs but you can adapt them by inserting
  11596. a cast to the \code{Any} type around each subexpression
  11597. causing a type error. While \LangDyn{} doesn't have explicit casts,
  11598. you can induce one by wrapping the subexpression \code{e}
  11599. with a call to an un-annotated identity function, like this:
  11600. \code{((lambda (x) x) e)}.
  11601. \end{exercise}
  11602. \begin{figure}[p]
  11603. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11604. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  11605. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  11606. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  11607. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  11608. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  11609. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  11610. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  11611. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  11612. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  11613. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  11614. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  11615. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  11616. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  11617. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  11618. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11619. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11620. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11621. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11622. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11623. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11624. \path[->,bend right=15] (Rgradual) edge [above] node
  11625. {\ttfamily\footnotesize type-check} (Rgradualp);
  11626. \path[->,bend right=15] (Rgradualp) edge [above] node
  11627. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  11628. \path[->,bend right=15] (Rwhilepp) edge [right] node
  11629. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  11630. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  11631. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  11632. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  11633. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  11634. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  11635. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  11636. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  11637. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  11638. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  11639. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11640. \path[->,bend left=15] (F1-1) edge [below] node
  11641. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11642. \path[->,bend right=15] (F1-2) edge [above] node
  11643. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11644. \path[->,bend right=15] (F1-3) edge [above] node
  11645. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11646. \path[->,bend right=15] (F1-4) edge [above] node
  11647. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11648. \path[->,bend right=15] (F1-5) edge [right] node
  11649. {\ttfamily\footnotesize explicate-control} (C3-2);
  11650. \path[->,bend left=15] (C3-2) edge [left] node
  11651. {\ttfamily\footnotesize select-instr.} (x86-2);
  11652. \path[->,bend right=15] (x86-2) edge [left] node
  11653. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11654. \path[->,bend right=15] (x86-2-1) edge [below] node
  11655. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11656. \path[->,bend right=15] (x86-2-2) edge [left] node
  11657. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11658. \path[->,bend left=15] (x86-3) edge [above] node
  11659. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11660. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11661. \end{tikzpicture}
  11662. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  11663. \label{fig:Rgradual-passes}
  11664. \end{figure}
  11665. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  11666. for the compilation of \LangGrad{}.
  11667. \section{Further Reading}
  11668. This chapter just scratches the surface of gradual typing. The basic
  11669. approach described here is missing two key ingredients that one would
  11670. want in a implementation of gradual typing: blame
  11671. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  11672. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  11673. problem addressed by blame tracking is that when a cast on a
  11674. higher-order value fails, it often does so at a point in the program
  11675. that is far removed from the original cast. Blame tracking is a
  11676. technique for propagating extra information through casts and proxies
  11677. so that when a cast fails, the error message can point back to the
  11678. original location of the cast in the source program.
  11679. The problem addressed by space-efficient casts also relates to
  11680. higher-order casts. It turns out that in partially typed programs, a
  11681. function or vector can flow through very-many casts at runtime. With
  11682. the approach described in this chapter, each cast adds another
  11683. \code{lambda} wrapper or a vector proxy. Not only does this take up
  11684. considerable space, but it also makes the function calls and vector
  11685. operations slow. For example, a partially-typed version of quicksort
  11686. could, in the worst case, build a chain of proxies of length $O(n)$
  11687. around the vector, changing the overall time complexity of the
  11688. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  11689. solution to this problem by representing casts using the coercion
  11690. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  11691. long chains of proxies by compressing them into a concise normal
  11692. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  11693. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  11694. the Grift compiler.
  11695. \begin{center}
  11696. \url{https://github.com/Gradual-Typing/Grift}
  11697. \end{center}
  11698. There are also interesting interactions between gradual typing and
  11699. other language features, such as parametetric polymorphism,
  11700. information-flow types, and type inference, to name a few. We
  11701. recommend the reader to the online gradual typing bibliography:
  11702. \begin{center}
  11703. \url{http://samth.github.io/gradual-typing-bib/}
  11704. \end{center}
  11705. % TODO: challenge problem:
  11706. % type analysis and type specialization?
  11707. % coercions?
  11708. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11709. \chapter{Parametric Polymorphism}
  11710. \label{ch:Rpoly}
  11711. \index{parametric polymorphism}
  11712. \index{generics}
  11713. This chapter studies the compilation of parametric
  11714. polymorphism\index{parametric polymorphism}
  11715. (aka. generics\index{generics}) in the subset \LangPoly{} of Typed
  11716. Racket. Parametric polymorphism enables improved code reuse by
  11717. parameterizing functions and data structures with respect to the types
  11718. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  11719. revisits the \code{map-vec} example but this time gives it a more
  11720. fitting type. This \code{map-vec} function is parameterized with
  11721. respect to the element type of the vector. The type of \code{map-vec}
  11722. is the following polymorphic type as specified by the \code{All} and
  11723. the type parameter \code{a}.
  11724. \begin{lstlisting}
  11725. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11726. \end{lstlisting}
  11727. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  11728. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  11729. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  11730. \code{a}, but we could have just as well applied \code{map-vec} to a
  11731. vector of Booleans (and a function on Booleans).
  11732. \begin{figure}[tbp]
  11733. % poly_test_2.rkt
  11734. \begin{lstlisting}
  11735. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  11736. (define (map-vec f v)
  11737. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11738. (define (add1 [x : Integer]) : Integer (+ x 1))
  11739. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11740. \end{lstlisting}
  11741. \caption{The \code{map-vec} example using parametric polymorphism.}
  11742. \label{fig:map-vec-poly}
  11743. \end{figure}
  11744. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  11745. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  11746. syntax. We add a second form for function definitions in which a type
  11747. declaration comes before the \code{define}. In the abstract syntax,
  11748. the return type in the \code{Def} is \code{Any}, but that should be
  11749. ignored in favor of the return type in the type declaration. (The
  11750. \code{Any} comes from using the same parser as in
  11751. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  11752. enables the use of an \code{All} type for a function, thereby making
  11753. it polymorphic. The grammar for types is extended to include
  11754. polymorphic types and type variables.
  11755. \begin{figure}[tp]
  11756. \centering
  11757. \fbox{
  11758. \begin{minipage}{0.96\textwidth}
  11759. \small
  11760. \[
  11761. \begin{array}{lcl}
  11762. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11763. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  11764. &\mid& \LP\key{:}~\Var~\Type\RP \\
  11765. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  11766. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  11767. \end{array}
  11768. \]
  11769. \end{minipage}
  11770. }
  11771. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  11772. (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  11773. \label{fig:Rpoly-concrete-syntax}
  11774. \end{figure}
  11775. \begin{figure}[tp]
  11776. \centering
  11777. \fbox{
  11778. \begin{minipage}{0.96\textwidth}
  11779. \small
  11780. \[
  11781. \begin{array}{lcl}
  11782. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11783. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11784. &\mid& \DECL{\Var}{\Type} \\
  11785. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  11786. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11787. \end{array}
  11788. \]
  11789. \end{minipage}
  11790. }
  11791. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  11792. (Figure~\ref{fig:Rwhile-syntax}).}
  11793. \label{fig:Rpoly-syntax}
  11794. \end{figure}
  11795. By including polymorphic types in the $\Type$ non-terminal we choose
  11796. to make them first-class which has interesting repercussions on the
  11797. compiler. Many languages with polymorphism, such as
  11798. C++~\citep{stroustrup88:_param_types} and Standard
  11799. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  11800. it is useful to see an example of first-class polymorphism. In
  11801. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  11802. whose parameter is a polymorphic function. The occurrence of a
  11803. polymorphic type underneath a function type is enabled by the normal
  11804. recursive structure of the grammar for $\Type$ and the categorization
  11805. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  11806. applies the polymorphic function to a Boolean and to an integer.
  11807. \begin{figure}[tbp]
  11808. \begin{lstlisting}
  11809. (: apply-twice ((All (b) (b -> b)) -> Integer))
  11810. (define (apply-twice f)
  11811. (if (f #t) (f 42) (f 777)))
  11812. (: id (All (a) (a -> a)))
  11813. (define (id x) x)
  11814. (apply-twice id)
  11815. \end{lstlisting}
  11816. \caption{An example illustrating first-class polymorphism.}
  11817. \label{fig:apply-twice}
  11818. \end{figure}
  11819. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  11820. three new responsibilities (compared to \LangLoop{}). The type checking of
  11821. function application is extended to handle the case where the operator
  11822. expression is a polymorphic function. In that case the type arguments
  11823. are deduced by matching the type of the parameters with the types of
  11824. the arguments.
  11825. %
  11826. The \code{match-types} auxiliary function carries out this deduction
  11827. by recursively descending through a parameter type \code{pt} and the
  11828. corresponding argument type \code{at}, making sure that they are equal
  11829. except when there is a type parameter on the left (in the parameter
  11830. type). If it's the first time that the type parameter has been
  11831. encountered, then the algorithm deduces an association of the type
  11832. parameter to the corresponding type on the right (in the argument
  11833. type). If it's not the first time that the type parameter has been
  11834. encountered, the algorithm looks up its deduced type and makes sure
  11835. that it is equal to the type on the right.
  11836. %
  11837. Once the type arguments are deduced, the operator expression is
  11838. wrapped in an \code{Inst} AST node (for instantiate) that records the
  11839. type of the operator, but more importantly, records the deduced type
  11840. arguments. The return type of the application is the return type of
  11841. the polymorphic function, but with the type parameters replaced by the
  11842. deduced type arguments, using the \code{subst-type} function.
  11843. The second responsibility of the type checker is extending the
  11844. function \code{type-equal?} to handle the \code{All} type. This is
  11845. not quite a simple as equal on other types, such as function and
  11846. vector types, because two polymorphic types can be syntactically
  11847. different even though they are equivalent types. For example,
  11848. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  11849. Two polymorphic types should be considered equal if they differ only
  11850. in the choice of the names of the type parameters. The
  11851. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  11852. renames the type parameters of the first type to match the type
  11853. parameters of the second type.
  11854. The third responsibility of the type checker is making sure that only
  11855. defined type variables appear in type annotations. The
  11856. \code{check-well-formed} function defined in
  11857. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  11858. sure that each type variable has been defined.
  11859. The output language of the type checker is \LangInst{}, defined in
  11860. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  11861. declaration and polymorphic function into a single definition, using
  11862. the \code{Poly} form, to make polymorphic functions more convenient to
  11863. process in next pass of the compiler.
  11864. \begin{figure}[tp]
  11865. \centering
  11866. \fbox{
  11867. \begin{minipage}{0.96\textwidth}
  11868. \small
  11869. \[
  11870. \begin{array}{lcl}
  11871. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11872. \Exp &::=& \ldots \mid \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  11873. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11874. &\mid& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  11875. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11876. \end{array}
  11877. \]
  11878. \end{minipage}
  11879. }
  11880. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  11881. (Figure~\ref{fig:Rwhile-syntax}).}
  11882. \label{fig:Rpoly-prime-syntax}
  11883. \end{figure}
  11884. The output of the type checker on the polymorphic \code{map-vec}
  11885. example is listed in Figure~\ref{fig:map-vec-type-check}.
  11886. \begin{figure}[tbp]
  11887. % poly_test_2.rkt
  11888. \begin{lstlisting}
  11889. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  11890. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  11891. (define (add1 [x : Integer]) : Integer (+ x 1))
  11892. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11893. (Integer))
  11894. add1 (vector 0 41)) 1)
  11895. \end{lstlisting}
  11896. \caption{Output of the type checker on the \code{map-vec} example.}
  11897. \label{fig:map-vec-type-check}
  11898. \end{figure}
  11899. \begin{figure}[tbp]
  11900. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11901. (define type-check-poly-class
  11902. (class type-check-Rwhile-class
  11903. (super-new)
  11904. (inherit check-type-equal?)
  11905. (define/override (type-check-apply env e1 es)
  11906. (define-values (e^ ty) ((type-check-exp env) e1))
  11907. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  11908. ((type-check-exp env) e)))
  11909. (match ty
  11910. [`(,ty^* ... -> ,rt)
  11911. (for ([arg-ty ty*] [param-ty ty^*])
  11912. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  11913. (values e^ es^ rt)]
  11914. [`(All ,xs (,tys ... -> ,rt))
  11915. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11916. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  11917. (match-types env^^ param-ty arg-ty)))
  11918. (define targs
  11919. (for/list ([x xs])
  11920. (match (dict-ref env^^ x (lambda () #f))
  11921. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  11922. x (Apply e1 es))]
  11923. [ty ty])))
  11924. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  11925. [else (error 'type-check "expected a function, not ~a" ty)]))
  11926. (define/override ((type-check-exp env) e)
  11927. (match e
  11928. [(Lambda `([,xs : ,Ts] ...) rT body)
  11929. (for ([T Ts]) ((check-well-formed env) T))
  11930. ((check-well-formed env) rT)
  11931. ((super type-check-exp env) e)]
  11932. [(HasType e1 ty)
  11933. ((check-well-formed env) ty)
  11934. ((super type-check-exp env) e)]
  11935. [else ((super type-check-exp env) e)]))
  11936. (define/override ((type-check-def env) d)
  11937. (verbose 'type-check "poly/def" d)
  11938. (match d
  11939. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  11940. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  11941. (for ([p ps]) ((check-well-formed ts-env) p))
  11942. ((check-well-formed ts-env) rt)
  11943. (define new-env (append ts-env (map cons xs ps) env))
  11944. (define-values (body^ ty^) ((type-check-exp new-env) body))
  11945. (check-type-equal? ty^ rt body)
  11946. (Generic ts (Def f p:t* rt info body^))]
  11947. [else ((super type-check-def env) d)]))
  11948. (define/override (type-check-program p)
  11949. (match p
  11950. [(Program info body)
  11951. (type-check-program (ProgramDefsExp info '() body))]
  11952. [(ProgramDefsExp info ds body)
  11953. (define ds^ (combine-decls-defs ds))
  11954. (define new-env (for/list ([d ds^])
  11955. (cons (def-name d) (fun-def-type d))))
  11956. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  11957. (define-values (body^ ty) ((type-check-exp new-env) body))
  11958. (check-type-equal? ty 'Integer body)
  11959. (ProgramDefsExp info ds^^ body^)]))
  11960. ))
  11961. \end{lstlisting}
  11962. \caption{Type checker for the \LangPoly{} language.}
  11963. \label{fig:type-check-Rvar0}
  11964. \end{figure}
  11965. \begin{figure}[tbp]
  11966. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11967. (define/override (type-equal? t1 t2)
  11968. (match* (t1 t2)
  11969. [(`(All ,xs ,T1) `(All ,ys ,T2))
  11970. (define env (map cons xs ys))
  11971. (type-equal? (subst-type env T1) T2)]
  11972. [(other wise)
  11973. (super type-equal? t1 t2)]))
  11974. (define/public (match-types env pt at)
  11975. (match* (pt at)
  11976. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  11977. [('Void 'Void) env] [('Any 'Any) env]
  11978. [(`(Vector ,pts ...) `(Vector ,ats ...))
  11979. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  11980. (match-types env^ pt1 at1))]
  11981. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  11982. (define env^ (match-types env prt art))
  11983. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  11984. (match-types env^^ pt1 at1))]
  11985. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  11986. (define env^ (append (map cons pxs axs) env))
  11987. (match-types env^ pt1 at1)]
  11988. [((? symbol? x) at)
  11989. (match (dict-ref env x (lambda () #f))
  11990. [#f (error 'type-check "undefined type variable ~a" x)]
  11991. ['Type (cons (cons x at) env)]
  11992. [t^ (check-type-equal? at t^ 'matching) env])]
  11993. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  11994. (define/public (subst-type env pt)
  11995. (match pt
  11996. ['Integer 'Integer] ['Boolean 'Boolean]
  11997. ['Void 'Void] ['Any 'Any]
  11998. [`(Vector ,ts ...)
  11999. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  12000. [`(,ts ... -> ,rt)
  12001. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  12002. [`(All ,xs ,t)
  12003. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  12004. [(? symbol? x) (dict-ref env x)]
  12005. [else (error 'type-check "expected a type not ~a" pt)]))
  12006. (define/public (combine-decls-defs ds)
  12007. (match ds
  12008. ['() '()]
  12009. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  12010. (unless (equal? name f)
  12011. (error 'type-check "name mismatch, ~a != ~a" name f))
  12012. (match type
  12013. [`(All ,xs (,ps ... -> ,rt))
  12014. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  12015. (cons (Generic xs (Def name params^ rt info body))
  12016. (combine-decls-defs ds^))]
  12017. [`(,ps ... -> ,rt)
  12018. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  12019. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  12020. [else (error 'type-check "expected a function type, not ~a" type) ])]
  12021. [`(,(Def f params rt info body) . ,ds^)
  12022. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  12023. \end{lstlisting}
  12024. \caption{Auxiliary functions for type checking \LangPoly{}.}
  12025. \label{fig:type-check-Rvar0-aux}
  12026. \end{figure}
  12027. \begin{figure}[tbp]
  12028. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  12029. (define/public ((check-well-formed env) ty)
  12030. (match ty
  12031. ['Integer (void)]
  12032. ['Boolean (void)]
  12033. ['Void (void)]
  12034. [(? symbol? a)
  12035. (match (dict-ref env a (lambda () #f))
  12036. ['Type (void)]
  12037. [else (error 'type-check "undefined type variable ~a" a)])]
  12038. [`(Vector ,ts ...)
  12039. (for ([t ts]) ((check-well-formed env) t))]
  12040. [`(,ts ... -> ,t)
  12041. (for ([t ts]) ((check-well-formed env) t))
  12042. ((check-well-formed env) t)]
  12043. [`(All ,xs ,t)
  12044. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  12045. ((check-well-formed env^) t)]
  12046. [else (error 'type-check "unrecognized type ~a" ty)]))
  12047. \end{lstlisting}
  12048. \caption{Well-formed types.}
  12049. \label{fig:well-formed-types}
  12050. \end{figure}
  12051. % TODO: interpreter for R'_10
  12052. \section{Compiling Polymorphism}
  12053. \label{sec:compiling-poly}
  12054. Broadly speaking, there are four approaches to compiling parametric
  12055. polymorphism, which we describe below.
  12056. \begin{description}
  12057. \item[Monomorphization] generates a different version of a polymorphic
  12058. function for each set of type arguments that it is used with,
  12059. producing type-specialized code. This approach results in the most
  12060. efficient code but requires whole-program compilation (no separate
  12061. compilation) and increases code size. For our current purposes
  12062. monomorphization is a non-starter because, with first-class
  12063. polymorphism, it is sometimes not possible to determine which
  12064. generic functions are used with which type arguments during
  12065. compilation. (It can be done at runtime, with just-in-time
  12066. compilation.) This approach is used to compile C++
  12067. templates~\citep{stroustrup88:_param_types} and polymorphic
  12068. functions in NESL~\citep{Blelloch:1993aa} and
  12069. ML~\citep{Weeks:2006aa}.
  12070. \item[Uniform representation] generates one version of each
  12071. polymorphic function but requires all values have a common ``boxed''
  12072. format, such as the tagged values of type \code{Any} in
  12073. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  12074. similarly to code in a dynamically typed language (like \LangDyn{}),
  12075. in which primitive operators require their arguments to be projected
  12076. from \code{Any} and their results are injected into \code{Any}. (In
  12077. object-oriented languages, the projection is accomplished via
  12078. virtual method dispatch.) The uniform representation approach is
  12079. compatible with separate compilation and with first-class
  12080. polymorphism. However, it produces the least-efficient code because
  12081. it introduces overhead in the entire program, including
  12082. non-polymorphic code. This approach is used in implementations of
  12083. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  12084. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  12085. Java~\citep{Bracha:1998fk}.
  12086. \item[Mixed representation] generates one version of each polymorphic
  12087. function, using a boxed representation for type
  12088. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  12089. and conversions are performed at the boundaries between monomorphic
  12090. and polymorphic (e.g. when a polymorphic function is instantiated
  12091. and called). This approach is compatible with separate compilation
  12092. and first-class polymorphism and maintains the efficiency of
  12093. monomorphic code. The tradeoff is increased overhead at the boundary
  12094. between monomorphic and polymorphic code. This approach is used in
  12095. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  12096. Java 5 with the addition of autoboxing.
  12097. \item[Type passing] uses the unboxed representation in both
  12098. monomorphic and polymorphic code. Each polymorphic function is
  12099. compiled to a single function with extra parameters that describe
  12100. the type arguments. The type information is used by the generated
  12101. code to know how to access the unboxed values at runtime. This
  12102. approach is used in implementation of the Napier88
  12103. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  12104. passing is compatible with separate compilation and first-class
  12105. polymorphism and maintains the efficiency for monomorphic
  12106. code. There is runtime overhead in polymorphic code from dispatching
  12107. on type information.
  12108. \end{description}
  12109. In this chapter we use the mixed representation approach, partly
  12110. because of its favorable attributes, and partly because it is
  12111. straightforward to implement using the tools that we have already
  12112. built to support gradual typing. To compile polymorphic functions, we
  12113. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  12114. \LangCast{}.
  12115. \section{Erase Types}
  12116. \label{sec:erase-types}
  12117. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  12118. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  12119. shows the output of the \code{erase-types} pass on the polymorphic
  12120. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  12121. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  12122. \code{All} types are removed from the type of \code{map-vec}.
  12123. \begin{figure}[tbp]
  12124. \begin{lstlisting}
  12125. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  12126. : (Vector Any Any)
  12127. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12128. (define (add1 [x : Integer]) : Integer (+ x 1))
  12129. (vector-ref ((cast map-vec
  12130. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12131. ((Integer -> Integer) (Vector Integer Integer)
  12132. -> (Vector Integer Integer)))
  12133. add1 (vector 0 41)) 1)
  12134. \end{lstlisting}
  12135. \caption{The polymorphic \code{map-vec} example after type erasure.}
  12136. \label{fig:map-vec-erase}
  12137. \end{figure}
  12138. This process of type erasure creates a challenge at points of
  12139. instantiation. For example, consider the instantiation of
  12140. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  12141. The type of \code{map-vec} is
  12142. \begin{lstlisting}
  12143. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12144. \end{lstlisting}
  12145. and it is instantiated to
  12146. \begin{lstlisting}
  12147. ((Integer -> Integer) (Vector Integer Integer)
  12148. -> (Vector Integer Integer))
  12149. \end{lstlisting}
  12150. After erasure, the type of \code{map-vec} is
  12151. \begin{lstlisting}
  12152. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12153. \end{lstlisting}
  12154. but we need to convert it to the instantiated type. This is easy to
  12155. do in the target language \LangCast{} with a single \code{cast}. In
  12156. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  12157. has been compiled to a \code{cast} from the type of \code{map-vec} to
  12158. the instantiated type. The source and target type of a cast must be
  12159. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  12160. because both the source and target are obtained from the same
  12161. polymorphic type of \code{map-vec}, replacing the type parameters with
  12162. \code{Any} in the former and with the deduced type arguments in the
  12163. later. (Recall that the \code{Any} type is consistent with any type.)
  12164. To implement the \code{erase-types} pass, we recommend defining a
  12165. recursive auxiliary function named \code{erase-type} that applies the
  12166. following two transformations. It replaces type variables with
  12167. \code{Any}
  12168. \begin{lstlisting}
  12169. |$x$|
  12170. |$\Rightarrow$|
  12171. Any
  12172. \end{lstlisting}
  12173. and it removes the polymorphic \code{All} types.
  12174. \begin{lstlisting}
  12175. (All |$xs$| |$T_1$|)
  12176. |$\Rightarrow$|
  12177. |$T'_1$|
  12178. \end{lstlisting}
  12179. Apply the \code{erase-type} function to all of the type annotations in
  12180. the program.
  12181. Regarding the translation of expressions, the case for \code{Inst} is
  12182. the interesting one. We translate it into a \code{Cast}, as shown
  12183. below. The type of the subexpression $e$ is the polymorphic type
  12184. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  12185. $T$, the type $T'$. The target type $T''$ is the result of
  12186. substituting the arguments types $ts$ for the type parameters $xs$ in
  12187. $T$ followed by doing type erasure.
  12188. \begin{lstlisting}
  12189. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  12190. |$\Rightarrow$|
  12191. (Cast |$e'$| |$T'$| |$T''$|)
  12192. \end{lstlisting}
  12193. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  12194. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  12195. Finally, each polymorphic function is translated to a regular
  12196. functions in which type erasure has been applied to all the type
  12197. annotations and the body.
  12198. \begin{lstlisting}
  12199. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  12200. |$\Rightarrow$|
  12201. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  12202. \end{lstlisting}
  12203. \begin{exercise}\normalfont
  12204. Implement a compiler for the polymorphic language \LangPoly{} by
  12205. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  12206. programs that use polymorphic functions. Some of them should make
  12207. use of first-class polymorphism.
  12208. \end{exercise}
  12209. \begin{figure}[p]
  12210. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12211. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  12212. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  12213. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  12214. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  12215. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  12216. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  12217. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  12218. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  12219. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  12220. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  12221. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  12222. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  12223. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  12224. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  12225. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  12226. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12227. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12228. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12229. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12230. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12231. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12232. \path[->,bend right=15] (Rpoly) edge [above] node
  12233. {\ttfamily\footnotesize type-check} (Rpolyp);
  12234. \path[->,bend right=15] (Rpolyp) edge [above] node
  12235. {\ttfamily\footnotesize erase-types} (Rgradualp);
  12236. \path[->,bend right=15] (Rgradualp) edge [above] node
  12237. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  12238. \path[->,bend right=15] (Rwhilepp) edge [right] node
  12239. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  12240. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  12241. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  12242. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  12243. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  12244. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  12245. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  12246. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  12247. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  12248. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  12249. {\ttfamily\footnotesize convert-assignments} (F1-1);
  12250. \path[->,bend left=15] (F1-1) edge [below] node
  12251. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12252. \path[->,bend right=15] (F1-2) edge [above] node
  12253. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12254. \path[->,bend right=15] (F1-3) edge [above] node
  12255. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12256. \path[->,bend right=15] (F1-4) edge [above] node
  12257. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12258. \path[->,bend right=15] (F1-5) edge [right] node
  12259. {\ttfamily\footnotesize explicate-control} (C3-2);
  12260. \path[->,bend left=15] (C3-2) edge [left] node
  12261. {\ttfamily\footnotesize select-instr.} (x86-2);
  12262. \path[->,bend right=15] (x86-2) edge [left] node
  12263. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12264. \path[->,bend right=15] (x86-2-1) edge [below] node
  12265. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12266. \path[->,bend right=15] (x86-2-2) edge [left] node
  12267. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12268. \path[->,bend left=15] (x86-3) edge [above] node
  12269. {\ttfamily\footnotesize patch-instr.} (x86-4);
  12270. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  12271. \end{tikzpicture}
  12272. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  12273. \label{fig:Rpoly-passes}
  12274. \end{figure}
  12275. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  12276. for the compilation of \LangPoly{}.
  12277. % TODO: challenge problem: specialization of instantiations
  12278. % Further Reading
  12279. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12280. \chapter{Appendix}
  12281. \section{Interpreters}
  12282. \label{appendix:interp}
  12283. \index{interpreter}
  12284. We provide interpreters for each of the source languages \LangInt{},
  12285. \LangVar{}, $\ldots$ in the files \code{interp-Rint.rkt},
  12286. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  12287. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  12288. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  12289. and x86 are in the \key{interp.rkt} file.
  12290. \section{Utility Functions}
  12291. \label{appendix:utilities}
  12292. The utility functions described in this section are in the
  12293. \key{utilities.rkt} file of the support code.
  12294. \paragraph{\code{interp-tests}}
  12295. The \key{interp-tests} function runs the compiler passes and the
  12296. interpreters on each of the specified tests to check whether each pass
  12297. is correct. The \key{interp-tests} function has the following
  12298. parameters:
  12299. \begin{description}
  12300. \item[name (a string)] a name to identify the compiler,
  12301. \item[typechecker] a function of exactly one argument that either
  12302. raises an error using the \code{error} function when it encounters a
  12303. type error, or returns \code{\#f} when it encounters a type
  12304. error. If there is no type error, the type checker returns the
  12305. program.
  12306. \item[passes] a list with one entry per pass. An entry is a list with
  12307. four things:
  12308. \begin{enumerate}
  12309. \item a string giving the name of the pass,
  12310. \item the function that implements the pass (a translator from AST
  12311. to AST),
  12312. \item a function that implements the interpreter (a function from
  12313. AST to result value) for the output language,
  12314. \item and a type checker for the output language. Type checkers for
  12315. the $R$ and $C$ languages are provided in the support code. For
  12316. example, the type checkers for \LangVar{} and \LangCVar{} are in
  12317. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  12318. type checker entry is optional. The support code does not provide
  12319. type checkers for the x86 languages.
  12320. \end{enumerate}
  12321. \item[source-interp] an interpreter for the source language. The
  12322. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  12323. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  12324. \item[tests] a list of test numbers that specifies which tests to
  12325. run. (see below)
  12326. \end{description}
  12327. %
  12328. The \key{interp-tests} function assumes that the subdirectory
  12329. \key{tests} has a collection of Racket programs whose names all start
  12330. with the family name, followed by an underscore and then the test
  12331. number, ending with the file extension \key{.rkt}. Also, for each test
  12332. program that calls \code{read} one or more times, there is a file with
  12333. the same name except that the file extension is \key{.in} that
  12334. provides the input for the Racket program. If the test program is
  12335. expected to fail type checking, then there should be an empty file of
  12336. the same name but with extension \key{.tyerr}.
  12337. \paragraph{\code{compiler-tests}}
  12338. runs the compiler passes to generate x86 (a \key{.s} file) and then
  12339. runs the GNU C compiler (gcc) to generate machine code. It runs the
  12340. machine code and checks that the output is $42$. The parameters to the
  12341. \code{compiler-tests} function are similar to those of the
  12342. \code{interp-tests} function, and consist of
  12343. \begin{itemize}
  12344. \item a compiler name (a string),
  12345. \item a type checker,
  12346. \item description of the passes,
  12347. \item name of a test-family, and
  12348. \item a list of test numbers.
  12349. \end{itemize}
  12350. \paragraph{\code{compile-file}}
  12351. takes a description of the compiler passes (see the comment for
  12352. \key{interp-tests}) and returns a function that, given a program file
  12353. name (a string ending in \key{.rkt}), applies all of the passes and
  12354. writes the output to a file whose name is the same as the program file
  12355. name but with \key{.rkt} replaced with \key{.s}.
  12356. \paragraph{\code{read-program}}
  12357. takes a file path and parses that file (it must be a Racket program)
  12358. into an abstract syntax tree.
  12359. \paragraph{\code{parse-program}}
  12360. takes an S-expression representation of an abstract syntax tree and converts it into
  12361. the struct-based representation.
  12362. \paragraph{\code{assert}}
  12363. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  12364. and displays the message \key{msg} if the Boolean \key{bool} is false.
  12365. \paragraph{\code{lookup}}
  12366. % remove discussion of lookup? -Jeremy
  12367. takes a key and an alist, and returns the first value that is
  12368. associated with the given key, if there is one. If not, an error is
  12369. triggered. The alist may contain both immutable pairs (built with
  12370. \key{cons}) and mutable pairs (built with \key{mcons}).
  12371. %The \key{map2} function ...
  12372. \section{x86 Instruction Set Quick-Reference}
  12373. \label{sec:x86-quick-reference}
  12374. \index{x86}
  12375. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  12376. do. We write $A \to B$ to mean that the value of $A$ is written into
  12377. location $B$. Address offsets are given in bytes. The instruction
  12378. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  12379. registers (such as \code{\%rax}), or memory references (such as
  12380. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  12381. reference per instruction. Other operands must be immediates or
  12382. registers.
  12383. \begin{table}[tbp]
  12384. \centering
  12385. \begin{tabular}{l|l}
  12386. \textbf{Instruction} & \textbf{Operation} \\ \hline
  12387. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  12388. \texttt{negq} $A$ & $- A \to A$ \\
  12389. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  12390. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  12391. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  12392. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  12393. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  12394. \texttt{retq} & Pops the return address and jumps to it \\
  12395. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  12396. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  12397. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  12398. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  12399. be an immediate) \\
  12400. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  12401. matches the condition code of the instruction, otherwise go to the
  12402. next instructions. The condition codes are \key{e} for ``equal'',
  12403. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  12404. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  12405. \texttt{jl} $L$ & \\
  12406. \texttt{jle} $L$ & \\
  12407. \texttt{jg} $L$ & \\
  12408. \texttt{jge} $L$ & \\
  12409. \texttt{jmp} $L$ & Jump to label $L$ \\
  12410. \texttt{movq} $A$, $B$ & $A \to B$ \\
  12411. \texttt{movzbq} $A$, $B$ &
  12412. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  12413. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  12414. and the extra bytes of $B$ are set to zero.} \\
  12415. & \\
  12416. & \\
  12417. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  12418. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  12419. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  12420. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  12421. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  12422. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  12423. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  12424. description of the condition codes. $A$ must be a single byte register
  12425. (e.g., \texttt{al} or \texttt{cl}).} \\
  12426. \texttt{setl} $A$ & \\
  12427. \texttt{setle} $A$ & \\
  12428. \texttt{setg} $A$ & \\
  12429. \texttt{setge} $A$ &
  12430. \end{tabular}
  12431. \vspace{5pt}
  12432. \caption{Quick-reference for the x86 instructions used in this book.}
  12433. \label{tab:x86-instr}
  12434. \end{table}
  12435. \cleardoublepage
  12436. \section{Concrete Syntax for Intermediate Languages}
  12437. The concrete syntax of \LangAny{} is defined in
  12438. Figure~\ref{fig:Rany-concrete-syntax}.
  12439. \begin{figure}[tp]
  12440. \centering
  12441. \fbox{
  12442. \begin{minipage}{0.97\textwidth}\small
  12443. \[
  12444. \begin{array}{lcl}
  12445. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  12446. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}} \\
  12447. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  12448. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void}
  12449. \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  12450. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  12451. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType}\\
  12452. &\mid& \LP\key{any-vector-length}\;\Exp\RP
  12453. \mid \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  12454. &\mid& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  12455. &\mid& \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP
  12456. \mid \LP\key{void?}\;\Exp\RP \\
  12457. &\mid& \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \\
  12458. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  12459. \LangAny{} &::=& \gray{\Def\ldots \; \Exp}
  12460. \end{array}
  12461. \]
  12462. \end{minipage}
  12463. }
  12464. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  12465. (Figure~\ref{fig:Rlam-syntax}).}
  12466. \label{fig:Rany-concrete-syntax}
  12467. \end{figure}
  12468. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  12469. defined in Figures~\ref{fig:c0-concrete-syntax},
  12470. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  12471. and \ref{fig:c3-concrete-syntax}, respectively.
  12472. \begin{figure}[tbp]
  12473. \fbox{
  12474. \begin{minipage}{0.96\textwidth}
  12475. \[
  12476. \begin{array}{lcl}
  12477. \Atm &::=& \Int \mid \Var \\
  12478. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  12479. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  12480. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  12481. \LangCVar{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  12482. \end{array}
  12483. \]
  12484. \end{minipage}
  12485. }
  12486. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  12487. \label{fig:c0-concrete-syntax}
  12488. \end{figure}
  12489. \begin{figure}[tbp]
  12490. \fbox{
  12491. \begin{minipage}{0.96\textwidth}
  12492. \small
  12493. \[
  12494. \begin{array}{lcl}
  12495. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  12496. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  12497. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12498. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  12499. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  12500. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12501. \mid \key{goto}~\itm{label}\key{;}\\
  12502. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  12503. \LangCIf{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12504. \end{array}
  12505. \]
  12506. \end{minipage}
  12507. }
  12508. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  12509. \label{fig:c1-concrete-syntax}
  12510. \end{figure}
  12511. \begin{figure}[tbp]
  12512. \fbox{
  12513. \begin{minipage}{0.96\textwidth}
  12514. \small
  12515. \[
  12516. \begin{array}{lcl}
  12517. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  12518. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12519. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12520. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  12521. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  12522. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  12523. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  12524. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  12525. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12526. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  12527. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  12528. \LangCVec{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12529. \end{array}
  12530. \]
  12531. \end{minipage}
  12532. }
  12533. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  12534. \label{fig:c2-concrete-syntax}
  12535. \end{figure}
  12536. \begin{figure}[tp]
  12537. \fbox{
  12538. \begin{minipage}{0.96\textwidth}
  12539. \small
  12540. \[
  12541. \begin{array}{lcl}
  12542. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  12543. \\
  12544. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12545. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  12546. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  12547. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  12548. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  12549. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  12550. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  12551. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  12552. \mid \LP\key{collect} \,\itm{int}\RP }\\
  12553. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  12554. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  12555. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  12556. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  12557. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  12558. \LangCFun{} & ::= & \Def\ldots
  12559. \end{array}
  12560. \]
  12561. \end{minipage}
  12562. }
  12563. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  12564. \label{fig:c3-concrete-syntax}
  12565. \end{figure}
  12566. \cleardoublepage
  12567. \addcontentsline{toc}{chapter}{Index}
  12568. \printindex
  12569. \cleardoublepage
  12570. \bibliographystyle{plainnat}
  12571. \bibliography{all}
  12572. \addcontentsline{toc}{chapter}{Bibliography}
  12573. \end{document}
  12574. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  12575. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  12576. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  12577. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  12578. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator jane
  12579. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  12580. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  12581. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  12582. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs Tt
  12583. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  12584. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  12585. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  12586. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  12587. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  12588. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  12589. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  12590. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  12591. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  12592. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  12593. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  12594. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  12595. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  12596. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  12597. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  12598. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  12599. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  12600. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  12601. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  12602. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  12603. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  12604. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  12605. % LocalWords: struct Friedman's MacOS Nystrom alist sam kate
  12606. % LocalWords: alists arity github unordered pqueue exprs ret param
  12607. % LocalWords: tyerr bytereg dh dl JmpIf HasType Osterlund Jacek TODO
  12608. % LocalWords: Gamari GlobalValue ProgramDefsExp prm ProgramDefs vn
  12609. % LocalWords: FunRef TailCall tailjmp IndirectCallq TailJmp Gilray
  12610. % LocalWords: dereference unbox Dataflow versa dataflow Kildall rhs
  12611. % LocalWords: Kleene enqueue dequeue AssignedFree FV cnvt SetBang tg
  12612. % LocalWords: ValueOf typechecker