book.tex 651 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. % move binary subtraction from Lif to Lint
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \usepackage{upquote}
  17. \definecolor{lightgray}{gray}{1}
  18. \newcommand{\black}[1]{{\color{black} #1}}
  19. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  20. \newcommand{\gray}[1]{{\color{gray} #1}}
  21. \def\racketEd{0}
  22. \def\pythonEd{1}
  23. \def\edition{1}
  24. % material that is specific to the Racket edition of the book
  25. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  26. % would like a command for: \if\edition\racketEd\color{olive}
  27. % and : \fi\color{black}
  28. % material that is specific to the Python edition of the book
  29. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  30. %% For multiple indices:
  31. \usepackage{multind}
  32. \makeindex{subject}
  33. \makeindex{authors}
  34. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  35. \if\edition\racketEd
  36. \lstset{%
  37. language=Lisp,
  38. basicstyle=\ttfamily\small,
  39. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  40. deletekeywords={read,mapping,vector},
  41. escapechar=|,
  42. columns=flexible,
  43. moredelim=[is][\color{red}]{~}{~},
  44. showstringspaces=false
  45. }
  46. \fi
  47. \if\edition\pythonEd
  48. \lstset{%
  49. language=Python,
  50. basicstyle=\ttfamily\small,
  51. morekeywords={match,case,bool,int},
  52. deletekeywords={},
  53. escapechar=|,
  54. columns=flexible,
  55. moredelim=[is][\color{red}]{~}{~},
  56. showstringspaces=false
  57. }
  58. \fi
  59. %%% Any shortcut own defined macros place here
  60. %% sample of author macro:
  61. \input{defs}
  62. \newtheorem{exercise}[theorem]{Exercise}
  63. % Adjusted settings
  64. \setlength{\columnsep}{4pt}
  65. %% \begingroup
  66. %% \setlength{\intextsep}{0pt}%
  67. %% \setlength{\columnsep}{0pt}%
  68. %% \begin{wrapfigure}{r}{0.5\textwidth}
  69. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  70. %% \caption{Basic layout}
  71. %% \end{wrapfigure}
  72. %% \lipsum[1]
  73. %% \endgroup
  74. \newbox\oiintbox
  75. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  76. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  77. \def\oiint{\copy\oiintbox}
  78. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  79. %\usepackage{showframe}
  80. \def\ShowFrameLinethickness{0.125pt}
  81. \addbibresource{book.bib}
  82. \begin{document}
  83. \frontmatter
  84. \HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  85. \halftitlepage
  86. \Title{Essentials of Compilation}
  87. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  88. %\edition{First Edition}
  89. \BookAuthor{Jeremy G. Siek}
  90. \imprint{The MIT Press\\
  91. Cambridge, Massachusetts\\
  92. London, England}
  93. \begin{copyrightpage}
  94. \textcopyright\ 2021 Jeremy G. Siek. Available for free viewing
  95. or personal downloading under the
  96. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  97. license.
  98. Copyright in this monograph has been licensed exclusively to The MIT
  99. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  100. version to the public in 2022. All inquiries regarding rights should
  101. be addressed to The MIT Press, Rights and Permissions Department.
  102. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  103. %% All rights reserved. No part of this book may be reproduced in any
  104. %% form by any electronic or mechanical means (including photocopying,
  105. %% recording, or information storage and retrieval) without permission in
  106. %% writing from the publisher.
  107. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  108. %% United States of America.
  109. %% Library of Congress Cataloging-in-Publication Data is available.
  110. %% ISBN:
  111. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  112. \end{copyrightpage}
  113. \dedication{This book is dedicated to the programming language wonks
  114. at Indiana University.}
  115. %% \begin{epigraphpage}
  116. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  117. %% \textit{Book Name if any}}
  118. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  119. %% \end{epigraphpage}
  120. \tableofcontents
  121. %\listoffigures
  122. %\listoftables
  123. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  124. \chapter*{Preface}
  125. \addcontentsline{toc}{fmbm}{Preface}
  126. There is a magical moment when a programmer presses the ``run'' button
  127. and the software begins to execute. Somehow a program written in a
  128. high-level language is running on a computer that is only capable of
  129. shuffling bits. Here we reveal the wizardry that makes that moment
  130. possible. Beginning with the ground breaking work of Backus and
  131. colleagues in the 1950s, computer scientists discovered techniques for
  132. constructing programs, called \emph{compilers}, that automatically
  133. translate high-level programs into machine code.
  134. We take you on a journey by constructing your own compiler for a small
  135. but powerful language. Along the way we explain the essential
  136. concepts, algorithms, and data structures that underlie compilers. We
  137. develop your understanding of how programs are mapped onto computer
  138. hardware, which is helpful when reasoning about properties at the
  139. junction between hardware and software such as execution time,
  140. software errors, and security vulnerabilities. For those interested
  141. in pursuing compiler construction, our goal is to provide a
  142. stepping-stone to advanced topics such as just-in-time compilation,
  143. program analysis, and program optimization. For those interested in
  144. designing and implementing programming languages, we connect
  145. language design choices to their impact on the compiler and the generated
  146. code.
  147. A compiler is typically organized as a sequence of stages that
  148. progressively translate a program to code that runs on hardware. We
  149. take this approach to the extreme by partitioning our compiler into a
  150. large number of \emph{nanopasses}, each of which performs a single
  151. task. This allows us to test the output of each pass in isolation, and
  152. furthermore, allows us to focus our attention which makes the compiler
  153. far easier to understand.
  154. The most familiar approach to describing compilers is with one pass
  155. per chapter. The problem with that approach is it obfuscates how
  156. language features motivate design choices in a compiler. We take an
  157. \emph{incremental} approach in which we build a complete compiler in
  158. each chapter, starting with a small input language that includes only
  159. arithmetic and variables and we add new language features in
  160. subsequent chapters.
  161. Our choice of language features is designed to elicit the fundamental
  162. concepts and algorithms used in compilers.
  163. \begin{itemize}
  164. \item We begin with integer arithmetic and local variables in
  165. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  166. the fundamental tools of compiler construction: \emph{abstract
  167. syntax trees} and \emph{recursive functions}.
  168. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  169. \emph{graph coloring} to assign variables to machine registers.
  170. \item Chapter~\ref{ch:Lif} adds \code{if} expressions, which motivates
  171. an elegant recursive algorithm for translating them into conditional
  172. \code{goto}'s.
  173. \item Chapter~\ref{ch:Lwhile} fleshes out support for imperative
  174. programming languages with the addition of loops\racket{ and mutable
  175. variables}. This elicits the need for \emph{dataflow
  176. analysis} in the register allocator.
  177. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  178. \emph{garbage collection}.
  179. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  180. but lack lexical scoping, similar to the C programming
  181. language~\citep{Kernighan:1988nx} except that we generate efficient
  182. tail calls. The reader learns about the procedure call stack,
  183. \emph{calling conventions}, and their interaction with register
  184. allocation and garbage collection.
  185. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  186. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  187. \emph{closure conversion}, in which lambdas are translated into a
  188. combination of functions and tuples.
  189. % Chapter about classes and objects?
  190. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  191. point the input languages are statically typed. The reader extends
  192. the statically typed language with an \code{Any} type which serves
  193. as a target for compiling the dynamically typed language.
  194. {\if\edition\pythonEd
  195. \item Chapter~\ref{ch:Robject} adds support for \emph{objects} and
  196. \emph{classes}.
  197. \fi}
  198. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  199. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  200. in which different regions of a program may be static or dynamically
  201. typed. The reader implements runtime support for \emph{proxies} that
  202. allow values to safely move between regions.
  203. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  204. leveraging the \code{Any} type and type casts developed in Chapters
  205. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  206. \end{itemize}
  207. There are many language features that we do not include. Our choices
  208. balance the incidental complexity of a feature versus the fundamental
  209. concepts that it exposes. For example, we include tuples and not
  210. records because they both elicit the study of heap allocation and
  211. garbage collection but records come with more incidental complexity.
  212. Since 2009 drafts of this book have served as the textbook for 16-week
  213. compiler courses for upper-level undergraduates and first-year
  214. graduate students at the University of Colorado and Indiana
  215. University.
  216. %
  217. Students come into the course having learned the basics of
  218. programming, data structures and algorithms, and discrete
  219. mathematics.
  220. %
  221. At the beginning of the course, students form groups of 2-4 people.
  222. The groups complete one chapter every two weeks, starting with
  223. Chapter~\ref{ch:Lvar}. Many chapters include a challenge problem that
  224. we assign to the graduate students. The last two weeks of the course
  225. involve a final project in which students design and implement a
  226. compiler extension of their choosing. Chapters~\ref{ch:Rgrad} and
  227. \ref{ch:Rpoly} can be used in support of these projects or they can
  228. replace some of the other chapters. For example, a course with an
  229. emphasis on statically-typed imperative languages could include
  230. Chapter~\ref{ch:Rpoly} but skip Chapter~\ref{ch:Rdyn}. For compiler
  231. courses at universities on the quarter system, with 10 weeks, we
  232. recommend completing up through Chapter~\ref{ch:Rfun}. (If pressed
  233. for time, one can skip Chapter~\ref{ch:Lvec} but still include
  234. Chapter~\ref{ch:Rfun} by limiting the number of parameters allowed in
  235. functions.) Figure~\ref{fig:chapter-dependences} depicts the
  236. dependencies between chapters.
  237. This book has also been used in compiler courses at California
  238. Polytechnic State University, Portland State University, Rose–Hulman
  239. Institute of Technology, University of Massachusetts Lowell, and the
  240. University of Vermont.
  241. \begin{figure}[tp]
  242. {\if\edition\racketEd
  243. \begin{tikzpicture}[baseline=(current bounding box.center)]
  244. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  245. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  246. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  247. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  248. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  249. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  250. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  251. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  252. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  253. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual Typing};
  254. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  255. \path[->] (C1) edge [above] node {} (C2);
  256. \path[->] (C2) edge [above] node {} (C3);
  257. \path[->] (C3) edge [above] node {} (C4);
  258. \path[->] (C4) edge [above] node {} (C5);
  259. \path[->] (C5) edge [above] node {} (C6);
  260. \path[->] (C6) edge [above] node {} (C7);
  261. \path[->] (C4) edge [above] node {} (C8);
  262. \path[->] (C4) edge [above] node {} (C9);
  263. \path[->] (C8) edge [above] node {} (C10);
  264. \path[->] (C10) edge [above] node {} (C11);
  265. \end{tikzpicture}
  266. \fi}
  267. {\if\edition\pythonEd
  268. \begin{tikzpicture}[baseline=(current bounding box.center)]
  269. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  270. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  271. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  272. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  273. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  274. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  275. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  276. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  277. \node (CO) at (0,-3) {\small Ch.~\ref{ch:Robject} Objects};
  278. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  279. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual Typing};
  280. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  281. \path[->] (C1) edge [above] node {} (C2);
  282. \path[->] (C2) edge [above] node {} (C3);
  283. \path[->] (C3) edge [above] node {} (C4);
  284. \path[->] (C4) edge [above] node {} (C5);
  285. \path[->] (C5) edge [above] node {} (C6);
  286. \path[->] (C6) edge [above] node {} (C7);
  287. \path[->] (C4) edge [above] node {} (C8);
  288. \path[->] (C4) edge [above] node {} (C9);
  289. \path[->] (C8) edge [above] node {} (C10);
  290. \path[->] (C8) edge [above] node {} (CO);
  291. \path[->] (C10) edge [above] node {} (C11);
  292. \end{tikzpicture}
  293. \fi}
  294. \caption{Diagram of chapter dependencies.}
  295. \label{fig:chapter-dependences}
  296. \end{figure}
  297. \racket{
  298. We use the \href{https://racket-lang.org/}{Racket} language both for
  299. the implementation of the compiler and for the input language, so the
  300. reader should be proficient with Racket or Scheme. There are many
  301. excellent resources for learning Scheme and
  302. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  303. }
  304. \python{
  305. This edition of the book uses \href{https://www.python.org/}{Python}
  306. both for the implementation of the compiler and for the input language, so the
  307. reader should be proficient with Python. There are many
  308. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  309. }
  310. The support code for this book is in the github repository at
  311. the following URL:
  312. \if\edition\racketEd
  313. \begin{center}\small
  314. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  315. \end{center}
  316. \fi
  317. \if\edition\pythonEd
  318. \begin{center}\small
  319. \url{https://github.com/IUCompilerCourse/}
  320. \end{center}
  321. \fi
  322. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  323. is helpful but not necessary for the reader to have taken a computer
  324. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  325. of x86-64 assembly language that are needed.
  326. %
  327. We follow the System V calling
  328. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  329. that we generate works with the runtime system (written in C) when it
  330. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  331. operating systems on Intel hardware.
  332. %
  333. On the Windows operating system, \code{gcc} uses the Microsoft x64
  334. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  335. assembly code that we generate does \emph{not} work with the runtime
  336. system on Windows. One workaround is to use a virtual machine with
  337. Linux as the guest operating system.
  338. \section*{Acknowledgments}
  339. The tradition of compiler construction at Indiana University goes back
  340. to research and courses on programming languages by Daniel Friedman in
  341. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  342. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  343. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  344. the compiler course and continued the development of Chez Scheme.
  345. %
  346. The compiler course evolved to incorporate novel pedagogical ideas
  347. while also including elements of real-world compilers. One of
  348. Friedman's ideas was to split the compiler into many small
  349. passes. Another idea, called ``the game'', was to test the code
  350. generated by each pass using interpreters.
  351. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  352. developed infrastructure to support this approach and evolved the
  353. course to use even smaller
  354. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  355. design decisions in this book are inspired by the assignment
  356. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  357. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  358. organization of the course made it difficult for students to
  359. understand the rationale for the compiler design. Ghuloum proposed the
  360. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  361. on.
  362. We thank the many students who served as teaching assistants for the
  363. compiler course at IU and made suggestions for improving the book
  364. including Carl Factora, Ryan Scott, and Cameron Swords. We especially
  365. thank Andre Kuhlenschmidt for his work on the garbage collector,
  366. Michael Vollmer for his work on efficient tail calls, and Michael
  367. Vitousek for his help running the first offering of the incremental
  368. compiler course at IU.
  369. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  370. Near, Ryan Newton, Nate Nystrom, Andrew Tolmach, and Michael Wollowski
  371. for teaching courses based on drafts of this book and for their
  372. invaluable feedback.
  373. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  374. course in the early 2000's and especially for finding the bug that
  375. sent our garbage collector on a wild goose chase!
  376. \mbox{}\\
  377. \noindent Jeremy G. Siek \\
  378. Bloomington, Indiana
  379. \mainmatter
  380. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  381. \chapter{Preliminaries}
  382. \label{ch:trees-recur}
  383. In this chapter we review the basic tools that are needed to implement
  384. a compiler. Programs are typically input by a programmer as text,
  385. i.e., a sequence of characters. The program-as-text representation is
  386. called \emph{concrete syntax}. We use concrete syntax to concisely
  387. write down and talk about programs. Inside the compiler, we use
  388. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  389. that efficiently supports the operations that the compiler needs to
  390. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  391. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  392. from concrete syntax to abstract syntax is a process called
  393. \emph{parsing}~\citep{Aho:2006wb}. We do not cover the theory and
  394. implementation of parsing in this book.
  395. %
  396. \racket{A parser is provided in the support code for translating from
  397. concrete to abstract syntax.}
  398. %
  399. \python{We use Python's \code{ast} module to translate from concrete
  400. to abstract syntax.}
  401. ASTs can be represented in many different ways inside the compiler,
  402. depending on the programming language used to write the compiler.
  403. %
  404. \racket{We use Racket's
  405. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  406. feature to represent ASTs (Section~\ref{sec:ast}).}
  407. %
  408. \python{We use Python classes and objects to represent ASTs, especially the
  409. classes defined in the standard \code{ast} module for the Python
  410. source language.}
  411. %
  412. We use grammars to define the abstract syntax of programming languages
  413. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  414. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  415. recursive functions to construct and deconstruct ASTs
  416. (Section~\ref{sec:recursion}). This chapter provides an brief
  417. introduction to these ideas.
  418. \racket{\index{subject}{struct}}
  419. \python{\index{subject}{class}\index{subject}{object}}
  420. \section{Abstract Syntax Trees}
  421. \label{sec:ast}
  422. Compilers use abstract syntax trees to represent programs because they
  423. often need to ask questions like: for a given part of a program, what
  424. kind of language feature is it? What are its sub-parts? Consider the
  425. program on the left and its AST on the right. This program is an
  426. addition operation and it has two sub-parts, a
  427. \racket{read}\python{input} operation and a negation. The negation has
  428. another sub-part, the integer constant \code{8}. By using a tree to
  429. represent the program, we can easily follow the links to go from one
  430. part of a program to its sub-parts.
  431. \begin{center}
  432. \begin{minipage}{0.4\textwidth}
  433. \if\edition\racketEd
  434. \begin{lstlisting}
  435. (+ (read) (- 8))
  436. \end{lstlisting}
  437. \fi
  438. \if\edition\pythonEd
  439. \begin{lstlisting}
  440. input_int() + -8
  441. \end{lstlisting}
  442. \fi
  443. \end{minipage}
  444. \begin{minipage}{0.4\textwidth}
  445. \begin{equation}
  446. \begin{tikzpicture}
  447. \node[draw] (plus) at (0 , 0) {\key{+}};
  448. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  449. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  450. \node[draw] (8) at (1 , -3) {\key{8}};
  451. \draw[->] (plus) to (read);
  452. \draw[->] (plus) to (minus);
  453. \draw[->] (minus) to (8);
  454. \end{tikzpicture}
  455. \label{eq:arith-prog}
  456. \end{equation}
  457. \end{minipage}
  458. \end{center}
  459. We use the standard terminology for trees to describe ASTs: each
  460. rectangle above is called a \emph{node}. The arrows connect a node to its
  461. \emph{children} (which are also nodes). The top-most node is the
  462. \emph{root}. Every node except for the root has a \emph{parent} (the
  463. node it is the child of). If a node has no children, it is a
  464. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  465. \index{subject}{node}
  466. \index{subject}{children}
  467. \index{subject}{root}
  468. \index{subject}{parent}
  469. \index{subject}{leaf}
  470. \index{subject}{internal node}
  471. %% Recall that an \emph{symbolic expression} (S-expression) is either
  472. %% \begin{enumerate}
  473. %% \item an atom, or
  474. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  475. %% where $e_1$ and $e_2$ are each an S-expression.
  476. %% \end{enumerate}
  477. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  478. %% null value \code{'()}, etc. We can create an S-expression in Racket
  479. %% simply by writing a backquote (called a quasi-quote in Racket)
  480. %% followed by the textual representation of the S-expression. It is
  481. %% quite common to use S-expressions to represent a list, such as $a, b
  482. %% ,c$ in the following way:
  483. %% \begin{lstlisting}
  484. %% `(a . (b . (c . ())))
  485. %% \end{lstlisting}
  486. %% Each element of the list is in the first slot of a pair, and the
  487. %% second slot is either the rest of the list or the null value, to mark
  488. %% the end of the list. Such lists are so common that Racket provides
  489. %% special notation for them that removes the need for the periods
  490. %% and so many parenthesis:
  491. %% \begin{lstlisting}
  492. %% `(a b c)
  493. %% \end{lstlisting}
  494. %% The following expression creates an S-expression that represents AST
  495. %% \eqref{eq:arith-prog}.
  496. %% \begin{lstlisting}
  497. %% `(+ (read) (- 8))
  498. %% \end{lstlisting}
  499. %% When using S-expressions to represent ASTs, the convention is to
  500. %% represent each AST node as a list and to put the operation symbol at
  501. %% the front of the list. The rest of the list contains the children. So
  502. %% in the above case, the root AST node has operation \code{`+} and its
  503. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  504. %% diagram \eqref{eq:arith-prog}.
  505. %% To build larger S-expressions one often needs to splice together
  506. %% several smaller S-expressions. Racket provides the comma operator to
  507. %% splice an S-expression into a larger one. For example, instead of
  508. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  509. %% we could have first created an S-expression for AST
  510. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  511. %% S-expression.
  512. %% \begin{lstlisting}
  513. %% (define ast1.4 `(- 8))
  514. %% (define ast1_1 `(+ (read) ,ast1.4))
  515. %% \end{lstlisting}
  516. %% In general, the Racket expression that follows the comma (splice)
  517. %% can be any expression that produces an S-expression.
  518. {\if\edition\racketEd
  519. We define a Racket \code{struct} for each kind of node. For this
  520. chapter we require just two kinds of nodes: one for integer constants
  521. and one for primitive operations. The following is the \code{struct}
  522. definition for integer constants.
  523. \begin{lstlisting}
  524. (struct Int (value))
  525. \end{lstlisting}
  526. An integer node includes just one thing: the integer value.
  527. To create an AST node for the integer $8$, we write \INT{8}.
  528. \begin{lstlisting}
  529. (define eight (Int 8))
  530. \end{lstlisting}
  531. We say that the value created by \INT{8} is an
  532. \emph{instance} of the
  533. \code{Int} structure.
  534. The following is the \code{struct} definition for primitive operations.
  535. \begin{lstlisting}
  536. (struct Prim (op args))
  537. \end{lstlisting}
  538. A primitive operation node includes an operator symbol \code{op} and a
  539. list of child \code{args}. For example, to create an AST that negates
  540. the number $8$, we write \code{(Prim '- (list eight))}.
  541. \begin{lstlisting}
  542. (define neg-eight (Prim '- (list eight)))
  543. \end{lstlisting}
  544. Primitive operations may have zero or more children. The \code{read}
  545. operator has zero children:
  546. \begin{lstlisting}
  547. (define rd (Prim 'read '()))
  548. \end{lstlisting}
  549. whereas the addition operator has two children:
  550. \begin{lstlisting}
  551. (define ast1_1 (Prim '+ (list rd neg-eight)))
  552. \end{lstlisting}
  553. We have made a design choice regarding the \code{Prim} structure.
  554. Instead of using one structure for many different operations
  555. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  556. structure for each operation, as follows.
  557. \begin{lstlisting}
  558. (struct Read ())
  559. (struct Add (left right))
  560. (struct Neg (value))
  561. \end{lstlisting}
  562. The reason we choose to use just one structure is that in many parts
  563. of the compiler the code for the different primitive operators is the
  564. same, so we might as well just write that code once, which is enabled
  565. by using a single structure.
  566. \fi}
  567. {\if\edition\pythonEd
  568. We use a Python \code{class} for each kind of node.
  569. The following is the class definition for constants.
  570. \begin{lstlisting}
  571. class Constant:
  572. def __init__(self, value):
  573. self.value = value
  574. \end{lstlisting}
  575. An integer constant node includes just one thing: the integer value.
  576. To create an AST node for the integer $8$, we write \INT{8}.
  577. \begin{lstlisting}
  578. eight = Constant(8)
  579. \end{lstlisting}
  580. We say that the value created by \INT{8} is an
  581. \emph{instance} of the \code{Constant} class.
  582. The following is the class definition for unary operators.
  583. \begin{lstlisting}
  584. class UnaryOp:
  585. def __init__(self, op, operand):
  586. self.op = op
  587. self.operand = operand
  588. \end{lstlisting}
  589. The specific operation is specified by the \code{op} parameter. For
  590. example, the class \code{USub} is for unary subtraction. (More unary
  591. operators are introduced in later chapters.) To create an AST that
  592. negates the number $8$, we write the following.
  593. \begin{lstlisting}
  594. neg_eight = UnaryOp(USub(), eight)
  595. \end{lstlisting}
  596. The call to the \code{input\_int} function is represented by the
  597. \code{Call} and \code{Name} classes.
  598. \begin{lstlisting}
  599. class Call:
  600. def __init__(self, func, args):
  601. self.func = func
  602. self.args = args
  603. class Name:
  604. def __init__(self, id):
  605. self.id = id
  606. \end{lstlisting}
  607. To create an AST node that calls \code{input\_int}, we write
  608. \begin{lstlisting}
  609. read = Call(Name('input_int'), [])
  610. \end{lstlisting}
  611. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  612. the \code{BinOp} class for binary operators.
  613. \begin{lstlisting}
  614. class BinOp:
  615. def __init__(self, left, op, right):
  616. self.op = op
  617. self.left = left
  618. self.right = right
  619. \end{lstlisting}
  620. Similar to \code{UnaryOp}, the specific operation is specified by the
  621. \code{op} parameter, which for now is just an instance of the
  622. \code{Add} class. So to create the AST node that adds negative eight
  623. to some user input, we write the following.
  624. \begin{lstlisting}
  625. ast1_1 = BinOp(read, Add(), neg_eight)
  626. \end{lstlisting}
  627. \fi}
  628. When compiling a program such as \eqref{eq:arith-prog}, we need to
  629. know that the operation associated with the root node is addition and
  630. we need to be able to access its two children. \racket{Racket}\python{Python}
  631. provides pattern matching to support these kinds of queries, as we see in
  632. Section~\ref{sec:pattern-matching}.
  633. In this book, we often write down the concrete syntax of a program
  634. even when we really have in mind the AST because the concrete syntax
  635. is more concise. We recommend that, in your mind, you always think of
  636. programs as abstract syntax trees.
  637. \section{Grammars}
  638. \label{sec:grammar}
  639. \index{subject}{integer}
  640. \index{subject}{literal}
  641. \index{subject}{constant}
  642. A programming language can be thought of as a \emph{set} of programs.
  643. The set is typically infinite (one can always create larger and larger
  644. programs), so one cannot simply describe a language by listing all of
  645. the programs in the language. Instead we write down a set of rules, a
  646. \emph{grammar}, for building programs. Grammars are often used to
  647. define the concrete syntax of a language, but they can also be used to
  648. describe the abstract syntax. We write our rules in a variant of
  649. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  650. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  651. As an example, we describe a small language, named \LangInt{}, that consists of
  652. integers and arithmetic operations.
  653. \index{subject}{grammar}
  654. The first grammar rule for the abstract syntax of \LangInt{} says that an
  655. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  656. \begin{equation}
  657. \Exp ::= \INT{\Int} \label{eq:arith-int}
  658. \end{equation}
  659. %
  660. Each rule has a left-hand-side and a right-hand-side.
  661. If you have an AST node that matches the
  662. right-hand-side, then you can categorize it according to the
  663. left-hand-side.
  664. %
  665. Symbols in typewriter font are \emph{terminal} symbols and must
  666. literally appear in the program for the rule to be applicable.
  667. \index{subject}{terminal}
  668. %
  669. Our grammars do not mention \emph{white-space}, that is, separating characters
  670. like spaces, tabulators, and newlines. White-space may be inserted
  671. between symbols for disambiguation and to improve readability.
  672. \index{subject}{white-space}
  673. %
  674. A name such as $\Exp$ that is defined by the grammar rules is a
  675. \emph{non-terminal}. \index{subject}{non-terminal}
  676. %
  677. The name $\Int$ is also a non-terminal, but instead of defining it
  678. with a grammar rule, we define it with the following explanation. An
  679. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  680. $-$ (for negative integers), such that the sequence of decimals
  681. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  682. the representation of integers using 63 bits, which simplifies several
  683. aspects of compilation. \racket{Thus, these integers corresponds to
  684. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  685. \python{In contrast, integers in Python have unlimited precision, but
  686. the techniques needed to handle unlimited precision fall outside the
  687. scope of this book.}
  688. The second grammar rule is the \READOP{} operation that receives an
  689. input integer from the user of the program.
  690. \begin{equation}
  691. \Exp ::= \READ{} \label{eq:arith-read}
  692. \end{equation}
  693. The third rule says that, given an $\Exp$ node, the negation of that
  694. node is also an $\Exp$.
  695. \begin{equation}
  696. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  697. \end{equation}
  698. We can apply these rules to categorize the ASTs that are in the
  699. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  700. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  701. following AST is an $\Exp$.
  702. \begin{center}
  703. \begin{minipage}{0.5\textwidth}
  704. \NEG{\INT{\code{8}}}
  705. \end{minipage}
  706. \begin{minipage}{0.25\textwidth}
  707. \begin{equation}
  708. \begin{tikzpicture}
  709. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  710. \node[draw, circle] (8) at (0, -1.2) {$8$};
  711. \draw[->] (minus) to (8);
  712. \end{tikzpicture}
  713. \label{eq:arith-neg8}
  714. \end{equation}
  715. \end{minipage}
  716. \end{center}
  717. The next grammar rules are for addition and subtraction expressions:
  718. \begin{align}
  719. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  720. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  721. \end{align}
  722. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  723. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  724. \eqref{eq:arith-read} and we have already categorized
  725. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  726. to show that
  727. \[
  728. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  729. \]
  730. is an $\Exp$ in the \LangInt{} language.
  731. If you have an AST for which the above rules do not apply, then the
  732. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  733. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  734. because there are no rules for the \key{*} operator. Whenever we
  735. define a language with a grammar, the language only includes those
  736. programs that are justified by the grammar rules.
  737. {\if\edition\pythonEd
  738. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  739. There is a statement for printing the value of an expression
  740. \[
  741. \Stmt{} ::= \PRINT{\Exp}
  742. \]
  743. and a statement that evaluates an expression but ignores the result.
  744. \[
  745. \Stmt{} ::= \EXPR{\Exp}
  746. \]
  747. \fi}
  748. {\if\edition\racketEd
  749. The last grammar rule for \LangInt{} states that there is a
  750. \code{Program} node to mark the top of the whole program:
  751. \[
  752. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  753. \]
  754. The \code{Program} structure is defined as follows
  755. \begin{lstlisting}
  756. (struct Program (info body))
  757. \end{lstlisting}
  758. where \code{body} is an expression. In later chapters, the \code{info}
  759. part will be used to store auxiliary information but for now it is
  760. just the empty list.
  761. \fi}
  762. {\if\edition\pythonEd
  763. The last grammar rule for \LangInt{} states that there is a
  764. \code{Module} node to mark the top of the whole program:
  765. \[
  766. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  767. \]
  768. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  769. this case, a list of statements.
  770. %
  771. The \code{Module} class is defined as follows
  772. \begin{lstlisting}
  773. class Module:
  774. def __init__(self, body):
  775. self.body = body
  776. \end{lstlisting}
  777. where \code{body} is a list of statements.
  778. \fi}
  779. It is common to have many grammar rules with the same left-hand side
  780. but different right-hand sides, such as the rules for $\Exp$ in the
  781. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  782. combine several right-hand-sides into a single rule.
  783. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  784. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  785. defined in Figure~\ref{fig:r0-concrete-syntax}.
  786. \racket{The \code{read-program} function provided in
  787. \code{utilities.rkt} of the support code reads a program in from a
  788. file (the sequence of characters in the concrete syntax of Racket)
  789. and parses it into an abstract syntax tree. See the description of
  790. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  791. details.}
  792. \python{The \code{parse} function in Python's \code{ast} module
  793. converts the concrete syntax (represented as a string) into an
  794. abstract syntax tree.}
  795. \newcommand{\LintGrammarRacket}{
  796. \begin{array}{rcl}
  797. \Type &::=& \key{Integer} \\
  798. \Exp{} &::=& \Int{} \MID \LP\key{read}\RP \MID \LP\key{-}\;\Exp\RP \MID \LP\key{+} \; \Exp{}\;\Exp{}\RP
  799. \end{array}
  800. }
  801. \newcommand{\LintASTRacket}{
  802. \begin{array}{rcl}
  803. \Type &::=& \key{Integer} \\
  804. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  805. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp}
  806. \end{array}
  807. }
  808. \newcommand{\LintGrammarPython}{
  809. \begin{array}{rcl}
  810. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  811. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  812. \end{array}
  813. }
  814. \newcommand{\LintASTPython}{
  815. \begin{array}{rcl}
  816. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  817. \itm{unaryop} &::= & \code{USub()} \\
  818. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  819. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  820. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  821. \end{array}
  822. }
  823. \begin{figure}[tp]
  824. \fbox{
  825. \begin{minipage}{0.96\textwidth}
  826. {\if\edition\racketEd
  827. \[
  828. \begin{array}{l}
  829. \LintGrammarRacket \\
  830. \begin{array}{rcl}
  831. \LangInt{} &::=& \Exp
  832. \end{array}
  833. \end{array}
  834. \]
  835. \fi}
  836. {\if\edition\pythonEd
  837. \[
  838. \begin{array}{l}
  839. \LintGrammarPython \\
  840. \begin{array}{rcl}
  841. \LangInt{} &::=& \Stmt^{*}
  842. \end{array}
  843. \end{array}
  844. \]
  845. \fi}
  846. \end{minipage}
  847. }
  848. \caption{The concrete syntax of \LangInt{}.}
  849. \label{fig:r0-concrete-syntax}
  850. \end{figure}
  851. \begin{figure}[tp]
  852. \fbox{
  853. \begin{minipage}{0.96\textwidth}
  854. {\if\edition\racketEd
  855. \[
  856. \begin{array}{l}
  857. \LintASTRacket{} \\
  858. \begin{array}{rcl}
  859. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  860. \end{array}
  861. \end{array}
  862. \]
  863. \fi}
  864. {\if\edition\pythonEd
  865. \[
  866. \begin{array}{l}
  867. \LintASTPython\\
  868. \begin{array}{rcl}
  869. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  870. \end{array}
  871. \end{array}
  872. \]
  873. \fi}
  874. \end{minipage}
  875. }
  876. \caption{The abstract syntax of \LangInt{}.}
  877. \label{fig:r0-syntax}
  878. \end{figure}
  879. \section{Pattern Matching}
  880. \label{sec:pattern-matching}
  881. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  882. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python} provides the
  883. \texttt{match} feature to access the parts of a value.
  884. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  885. \begin{center}
  886. \begin{minipage}{0.5\textwidth}
  887. {\if\edition\racketEd
  888. \begin{lstlisting}
  889. (match ast1_1
  890. [(Prim op (list child1 child2))
  891. (print op)])
  892. \end{lstlisting}
  893. \fi}
  894. {\if\edition\pythonEd
  895. \begin{lstlisting}
  896. match ast1_1:
  897. case BinOp(child1, op, child2):
  898. print(op)
  899. \end{lstlisting}
  900. \fi}
  901. \end{minipage}
  902. \end{center}
  903. {\if\edition\racketEd
  904. %
  905. In the above example, the \texttt{match} form checks whether the AST
  906. \eqref{eq:arith-prog} is a binary operator, binds its parts to the
  907. three pattern variables \texttt{op}, \texttt{child1}, and
  908. \texttt{child2}, and then prints out the operator. In general, a match
  909. clause consists of a \emph{pattern} and a
  910. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  911. to be either a pattern variable, a structure name followed by a
  912. pattern for each of the structure's arguments, or an S-expression
  913. (symbols, lists, etc.). (See Chapter 12 of The Racket
  914. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  915. and Chapter 9 of The Racket
  916. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  917. for a complete description of \code{match}.)
  918. %
  919. The body of a match clause may contain arbitrary Racket code. The
  920. pattern variables can be used in the scope of the body, such as
  921. \code{op} in \code{(print op)}.
  922. %
  923. \fi}
  924. %
  925. %
  926. {\if\edition\pythonEd
  927. %
  928. In the above example, the \texttt{match} form checks whether the AST
  929. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  930. three pattern variables \texttt{child1}, \texttt{op}, and
  931. \texttt{child2}, and then prints out the operator. In general, each
  932. \code{case} consists of a \emph{pattern} and a
  933. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  934. to be either a pattern variable, a class name followed by a pattern
  935. for each of its constructor's arguments, or other literals such as
  936. strings, lists, etc.
  937. %
  938. The body of each \code{case} may contain arbitrary Python code. The
  939. pattern variables can be used in the body, such as \code{op} in
  940. \code{print(op)}.
  941. %
  942. \fi}
  943. A \code{match} form may contain several clauses, as in the following
  944. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  945. the AST. The \code{match} proceeds through the clauses in order,
  946. checking whether the pattern can match the input AST. The body of the
  947. first clause that matches is executed. The output of \code{leaf} for
  948. several ASTs is shown on the right.
  949. \begin{center}
  950. \begin{minipage}{0.6\textwidth}
  951. {\if\edition\racketEd
  952. \begin{lstlisting}
  953. (define (leaf arith)
  954. (match arith
  955. [(Int n) #t]
  956. [(Prim 'read '()) #t]
  957. [(Prim '- (list e1)) #f]
  958. [(Prim '+ (list e1 e2)) #f]))
  959. (leaf (Prim 'read '()))
  960. (leaf (Prim '- (list (Int 8))))
  961. (leaf (Int 8))
  962. \end{lstlisting}
  963. \fi}
  964. {\if\edition\pythonEd
  965. \begin{lstlisting}
  966. def leaf(arith):
  967. match arith:
  968. case Constant(n):
  969. return True
  970. case Call(Name('input_int'), []):
  971. return True
  972. case UnaryOp(USub(), e1):
  973. return False
  974. case BinOp(e1, Add(), e2):
  975. return False
  976. print(leaf(Call(Name('input_int'), [])))
  977. print(leaf(UnaryOp(USub(), eight)))
  978. print(leaf(Constant(8)))
  979. \end{lstlisting}
  980. \fi}
  981. \end{minipage}
  982. \vrule
  983. \begin{minipage}{0.25\textwidth}
  984. {\if\edition\racketEd
  985. \begin{lstlisting}
  986. #t
  987. #f
  988. #t
  989. \end{lstlisting}
  990. \fi}
  991. {\if\edition\pythonEd
  992. \begin{lstlisting}
  993. True
  994. False
  995. True
  996. \end{lstlisting}
  997. \fi}
  998. \end{minipage}
  999. \end{center}
  1000. When writing a \code{match}, we refer to the grammar definition to
  1001. identify which non-terminal we are expecting to match against, then we
  1002. make sure that 1) we have one \racket{clause}\python{case} for each alternative of that
  1003. non-terminal and 2) that the pattern in each \racket{clause}\python{case} corresponds to the
  1004. corresponding right-hand side of a grammar rule. For the \code{match}
  1005. in the \code{leaf} function, we refer to the grammar for \LangInt{} in
  1006. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  1007. alternatives, so the \code{match} has 4 \racket{clauses}\python{cases}.
  1008. The pattern in each \racket{clause}\python{case} corresponds to the right-hand side
  1009. of a grammar rule. For example, the pattern \ADD{\code{e1}}{\code{e2}} corresponds to the
  1010. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  1011. patterns, replace non-terminals such as $\Exp$ with pattern variables
  1012. of your choice (e.g. \code{e1} and \code{e2}).
  1013. \section{Recursive Functions}
  1014. \label{sec:recursion}
  1015. \index{subject}{recursive function}
  1016. Programs are inherently recursive. For example, an expression is often
  1017. made of smaller expressions. Thus, the natural way to process an
  1018. entire program is with a recursive function. As a first example of
  1019. such a recursive function, we define the function \code{exp} in
  1020. Figure~\ref{fig:exp-predicate}, which takes an arbitrary value and
  1021. determines whether or not it is an expression in \LangInt{}.
  1022. %
  1023. We say that a function is defined by \emph{structural recursion} when
  1024. it is defined using a sequence of match \racket{clauses}\python{cases}
  1025. that correspond to a grammar, and the body of each
  1026. \racket{clause}\python{case} makes a recursive call on each child
  1027. node.\footnote{This principle of structuring code according to the
  1028. data definition is advocated in the book \emph{How to Design
  1029. Programs} \url{https://htdp.org/2020-8-1/Book/index.html}.}
  1030. \python{We define a second function, named \code{stmt}, that
  1031. recognizes whether a value is a \LangInt{} statement.}
  1032. \python{Finally, } Figure~\ref{fig:exp-predicate} \racket{also}
  1033. defines \code{Lint}, which determines whether an AST is a program in
  1034. \LangInt{}. In general we can expect to write one recursive function
  1035. to handle each non-terminal in a grammar.\index{subject}{structural
  1036. recursion} Of the two examples at the bottom of the figure, the
  1037. first is in \code{Lint} and the second is not.
  1038. \begin{figure}[tp]
  1039. {\if\edition\racketEd
  1040. \begin{lstlisting}
  1041. (define (exp ast)
  1042. (match ast
  1043. [(Int n) #t]
  1044. [(Prim 'read '()) #t]
  1045. [(Prim '- (list e)) (exp e)]
  1046. [(Prim '+ (list e1 e2))
  1047. (and (exp e1) (exp e2))]
  1048. [else #f]))
  1049. (define (Lint ast)
  1050. (match ast
  1051. [(Program '() e) (exp e)]
  1052. [else #f]))
  1053. (Lint (Program '() ast1_1)
  1054. (Lint (Program '()
  1055. (Prim '- (list (Prim 'read '())
  1056. (Prim '+ (list (Num 8)))))))
  1057. \end{lstlisting}
  1058. \fi}
  1059. {\if\edition\pythonEd
  1060. \begin{lstlisting}
  1061. def exp(e):
  1062. match e:
  1063. case Constant(n):
  1064. return True
  1065. case Call(Name('input_int'), []):
  1066. return True
  1067. case UnaryOp(USub(), e1):
  1068. return exp(e1)
  1069. case BinOp(e1, Add(), e2):
  1070. return exp(e1) and exp(e2)
  1071. case BinOp(e1, Sub(), e2):
  1072. return exp(e1) and exp(e2)
  1073. case _:
  1074. return False
  1075. def stmt(s):
  1076. match s:
  1077. case Expr(Call(Name('print'), [e])):
  1078. return exp(e)
  1079. case Expr(e):
  1080. return exp(e)
  1081. case _:
  1082. return False
  1083. def Lint(p):
  1084. match p:
  1085. case Module(body):
  1086. return all([stmt(s) for s in body])
  1087. case _:
  1088. return False
  1089. print(Lint(Module([Expr(ast1_1)])))
  1090. print(Lint(Module([Expr(BinOp(read, Sub(),
  1091. UnaryOp(Add(), Constant(8))))])))
  1092. \end{lstlisting}
  1093. \fi}
  1094. \caption{Example of recursive functions for \LangInt{}. These functions
  1095. recognize whether an AST is in \LangInt{}.}
  1096. \label{fig:exp-predicate}
  1097. \end{figure}
  1098. %% You may be tempted to merge the two functions into one, like this:
  1099. %% \begin{center}
  1100. %% \begin{minipage}{0.5\textwidth}
  1101. %% \begin{lstlisting}
  1102. %% (define (Lint ast)
  1103. %% (match ast
  1104. %% [(Int n) #t]
  1105. %% [(Prim 'read '()) #t]
  1106. %% [(Prim '- (list e)) (Lint e)]
  1107. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1108. %% [(Program '() e) (Lint e)]
  1109. %% [else #f]))
  1110. %% \end{lstlisting}
  1111. %% \end{minipage}
  1112. %% \end{center}
  1113. %% %
  1114. %% Sometimes such a trick will save a few lines of code, especially when
  1115. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1116. %% \emph{not} recommended because it can get you into trouble.
  1117. %% %
  1118. %% For example, the above function is subtly wrong:
  1119. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1120. %% returns true when it should return false.
  1121. \section{Interpreters}
  1122. \label{sec:interp_Lint}
  1123. \index{subject}{interpreter}
  1124. The behavior of a program is defined by the specification of the
  1125. programming language.
  1126. %
  1127. \racket{For example, the Scheme language is defined in the report by
  1128. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1129. reference manual~\citep{plt-tr}.}
  1130. %
  1131. \python{For example, the Python language is defined in the Python
  1132. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1133. %
  1134. In this book we use interpreters
  1135. to specify each language that we consider. An interpreter that is
  1136. designated as the definition of a language is called a
  1137. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  1138. \index{subject}{definitional interpreter} We warm up by creating a
  1139. definitional interpreter for the \LangInt{} language, which serves as
  1140. a second example of structural recursion. The \code{interp\_Lint}
  1141. function is defined in Figure~\ref{fig:interp_Lint}.
  1142. %
  1143. \racket{The body of the function is a match on the input program
  1144. followed by a call to the \lstinline{interp_exp} helper function,
  1145. which in turn has one match clause per grammar rule for \LangInt{}
  1146. expressions.}
  1147. %
  1148. \python{The body of the function matches on the \code{Module} AST node
  1149. and then invokes \code{interp\_stmt} on each statement in the
  1150. module. The \code{interp\_stmt} function includes a case for each
  1151. grammar rule of the \Stmt{} non-terminal and it calls
  1152. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1153. function includes a case for each grammar rule of the \Exp{}
  1154. non-terminal.}
  1155. \begin{figure}[tp]
  1156. {\if\edition\racketEd
  1157. \begin{lstlisting}
  1158. (define (interp_exp e)
  1159. (match e
  1160. [(Int n) n]
  1161. [(Prim 'read '())
  1162. (define r (read))
  1163. (cond [(fixnum? r) r]
  1164. [else (error 'interp_exp "read expected an integer" r)])]
  1165. [(Prim '- (list e))
  1166. (define v (interp_exp e))
  1167. (fx- 0 v)]
  1168. [(Prim '+ (list e1 e2))
  1169. (define v1 (interp_exp e1))
  1170. (define v2 (interp_exp e2))
  1171. (fx+ v1 v2)]))
  1172. (define (interp_Lint p)
  1173. (match p
  1174. [(Program '() e) (interp_exp e)]))
  1175. \end{lstlisting}
  1176. \fi}
  1177. {\if\edition\pythonEd
  1178. \begin{lstlisting}
  1179. def interp_exp(e):
  1180. match e:
  1181. case BinOp(left, Add(), right):
  1182. l = interp_exp(left); r = interp_exp(right)
  1183. return l + r
  1184. case BinOp(left, Sub(), right):
  1185. l = interp_exp(left); r = interp_exp(right)
  1186. return l - r
  1187. case UnaryOp(USub(), v):
  1188. return - interp_exp(v)
  1189. case Constant(value):
  1190. return value
  1191. case Call(Name('input_int'), []):
  1192. return int(input())
  1193. def interp_stmt(s):
  1194. match s:
  1195. case Expr(Call(Name('print'), [arg])):
  1196. print(interp_exp(arg))
  1197. case Expr(value):
  1198. interp_exp(value)
  1199. def interp_Lint(p):
  1200. match p:
  1201. case Module(body):
  1202. for s in body:
  1203. interp_stmt(s)
  1204. \end{lstlisting}
  1205. \fi}
  1206. \caption{Interpreter for the \LangInt{} language.}
  1207. \label{fig:interp_Lint}
  1208. \end{figure}
  1209. Let us consider the result of interpreting a few \LangInt{} programs. The
  1210. following program adds two integers.
  1211. {\if\edition\racketEd
  1212. \begin{lstlisting}
  1213. (+ 10 32)
  1214. \end{lstlisting}
  1215. \fi}
  1216. {\if\edition\pythonEd
  1217. \begin{lstlisting}
  1218. print(10 + 32)
  1219. \end{lstlisting}
  1220. \fi}
  1221. The result is \key{42}, the answer to life, the universe, and
  1222. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  1223. Galaxy} by Douglas Adams.}
  1224. %
  1225. We wrote the above program in concrete syntax whereas the parsed
  1226. abstract syntax is:
  1227. {\if\edition\racketEd
  1228. \begin{lstlisting}
  1229. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1230. \end{lstlisting}
  1231. \fi}
  1232. {\if\edition\pythonEd
  1233. \begin{lstlisting}
  1234. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1235. \end{lstlisting}
  1236. \fi}
  1237. The next example demonstrates that expressions may be nested within
  1238. each other, in this case nesting several additions and negations.
  1239. {\if\edition\racketEd
  1240. \begin{lstlisting}
  1241. (+ 10 (- (+ 12 20)))
  1242. \end{lstlisting}
  1243. \fi}
  1244. {\if\edition\pythonEd
  1245. \begin{lstlisting}
  1246. print(10 + -(12 + 20))
  1247. \end{lstlisting}
  1248. \fi}
  1249. %
  1250. \noindent What is the result of the above program?
  1251. {\if\edition\racketEd
  1252. As mentioned previously, the \LangInt{} language does not support
  1253. arbitrarily-large integers, but only $63$-bit integers, so we
  1254. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1255. in Racket.
  1256. Suppose
  1257. \[
  1258. n = 999999999999999999
  1259. \]
  1260. which indeed fits in $63$-bits. What happens when we run the
  1261. following program in our interpreter?
  1262. \begin{lstlisting}
  1263. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1264. \end{lstlisting}
  1265. It produces an error:
  1266. \begin{lstlisting}
  1267. fx+: result is not a fixnum
  1268. \end{lstlisting}
  1269. We establish the convention that if running the definitional
  1270. interpreter on a program produces an error then the meaning of that
  1271. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1272. error is a \code{trapped-error}. A compiler for the language is under
  1273. no obligations regarding programs with unspecified behavior; it does
  1274. not have to produce an executable, and if it does, that executable can
  1275. do anything. On the other hand, if the error is a
  1276. \code{trapped-error}, then the compiler must produce an executable and
  1277. it is required to report that an error occurred. To signal an error,
  1278. exit with a return code of \code{255}. The interpreters in chapters
  1279. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  1280. \code{trapped-error}.
  1281. \fi}
  1282. % TODO: how to deal with too-large integers in the Python interpreter?
  1283. %% This convention applies to the languages defined in this
  1284. %% book, as a way to simplify the student's task of implementing them,
  1285. %% but this convention is not applicable to all programming languages.
  1286. %%
  1287. Moving on to the last feature of the \LangInt{} language, the
  1288. \READOP{} operation prompts the user of the program for an integer.
  1289. Recall that program \eqref{eq:arith-prog} requests an integer input
  1290. and then subtracts \code{8}. So if we run
  1291. {\if\edition\racketEd
  1292. \begin{lstlisting}
  1293. (interp_Lint (Program '() ast1_1))
  1294. \end{lstlisting}
  1295. \fi}
  1296. {\if\edition\pythonEd
  1297. \begin{lstlisting}
  1298. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1299. \end{lstlisting}
  1300. \fi}
  1301. \noindent and if the input is \code{50}, the result is \code{42}.
  1302. We include the \READOP{} operation in \LangInt{} so a clever student
  1303. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1304. during compilation to obtain the output and then generates the trivial
  1305. code to produce the output.\footnote{Yes, a clever student did this in the
  1306. first instance of this course!}
  1307. The job of a compiler is to translate a program in one language into a
  1308. program in another language so that the output program behaves the
  1309. same way as the input program. This idea is depicted in the
  1310. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1311. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1312. Given a compiler that translates from language $\mathcal{L}_1$ to
  1313. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1314. compiler must translate it into some program $P_2$ such that
  1315. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1316. same input $i$ yields the same output $o$.
  1317. \begin{equation} \label{eq:compile-correct}
  1318. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1319. \node (p1) at (0, 0) {$P_1$};
  1320. \node (p2) at (3, 0) {$P_2$};
  1321. \node (o) at (3, -2.5) {$o$};
  1322. \path[->] (p1) edge [above] node {compile} (p2);
  1323. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1324. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1325. \end{tikzpicture}
  1326. \end{equation}
  1327. In the next section we see our first example of a compiler.
  1328. \section{Example Compiler: a Partial Evaluator}
  1329. \label{sec:partial-evaluation}
  1330. In this section we consider a compiler that translates \LangInt{}
  1331. programs into \LangInt{} programs that may be more efficient. The
  1332. compiler eagerly computes the parts of the program that do not depend
  1333. on any inputs, a process known as \emph{partial
  1334. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1335. For example, given the following program
  1336. {\if\edition\racketEd
  1337. \begin{lstlisting}
  1338. (+ (read) (- (+ 5 3)))
  1339. \end{lstlisting}
  1340. \fi}
  1341. {\if\edition\pythonEd
  1342. \begin{lstlisting}
  1343. print(input_int() + -(5 + 3) )
  1344. \end{lstlisting}
  1345. \fi}
  1346. \noindent our compiler translates it into the program
  1347. {\if\edition\racketEd
  1348. \begin{lstlisting}
  1349. (+ (read) -8)
  1350. \end{lstlisting}
  1351. \fi}
  1352. {\if\edition\pythonEd
  1353. \begin{lstlisting}
  1354. print(input_int() + -8)
  1355. \end{lstlisting}
  1356. \fi}
  1357. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1358. evaluator for the \LangInt{} language. The output of the partial evaluator
  1359. is a program in \LangInt{}. In Figure~\ref{fig:pe-arith}, the structural
  1360. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1361. whereas the code for partially evaluating the negation and addition
  1362. operations is factored into two auxiliary functions:
  1363. \code{pe\_neg} and \code{pe\_add}. The input to these
  1364. functions is the output of partially evaluating the children.
  1365. The \code{pe\_neg} and \code{pe\_add} functions check whether their
  1366. arguments are integers and if they are, perform the appropriate
  1367. arithmetic. Otherwise, they create an AST node for the arithmetic
  1368. operation.
  1369. \begin{figure}[tp]
  1370. {\if\edition\racketEd
  1371. \begin{lstlisting}
  1372. (define (pe_neg r)
  1373. (match r
  1374. [(Int n) (Int (fx- 0 n))]
  1375. [else (Prim '- (list r))]))
  1376. (define (pe_add r1 r2)
  1377. (match* (r1 r2)
  1378. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1379. [(_ _) (Prim '+ (list r1 r2))]))
  1380. (define (pe_exp e)
  1381. (match e
  1382. [(Int n) (Int n)]
  1383. [(Prim 'read '()) (Prim 'read '())]
  1384. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1385. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]))
  1386. (define (pe_Lint p)
  1387. (match p
  1388. [(Program '() e) (Program '() (pe_exp e))]))
  1389. \end{lstlisting}
  1390. \fi}
  1391. {\if\edition\pythonEd
  1392. \begin{lstlisting}
  1393. def pe_neg(r):
  1394. match r:
  1395. case Constant(n):
  1396. return Constant(-n)
  1397. case _:
  1398. return UnaryOp(USub(), r)
  1399. def pe_add(r1, r2):
  1400. match (r1, r2):
  1401. case (Constant(n1), Constant(n2)):
  1402. return Constant(n1 + n2)
  1403. case _:
  1404. return BinOp(r1, Add(), r2)
  1405. def pe_sub(r1, r2):
  1406. match (r1, r2):
  1407. case (Constant(n1), Constant(n2)):
  1408. return Constant(n1 - n2)
  1409. case _:
  1410. return BinOp(r1, Sub(), r2)
  1411. def pe_exp(e):
  1412. match e:
  1413. case BinOp(left, Add(), right):
  1414. return pe_add(pe_exp(left), pe_exp(right))
  1415. case BinOp(left, Sub(), right):
  1416. return pe_sub(pe_exp(left), pe_exp(right))
  1417. case UnaryOp(USub(), v):
  1418. return pe_neg(pe_exp(v))
  1419. case Constant(value):
  1420. return e
  1421. case Call(Name('input_int'), []):
  1422. return e
  1423. def pe_stmt(s):
  1424. match s:
  1425. case Expr(Call(Name('print'), [arg])):
  1426. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1427. case Expr(value):
  1428. return Expr(pe_exp(value))
  1429. def pe_P_int(p):
  1430. match p:
  1431. case Module(body):
  1432. new_body = [pe_stmt(s) for s in body]
  1433. return Module(new_body)
  1434. \end{lstlisting}
  1435. \fi}
  1436. \caption{A partial evaluator for \LangInt{}.}
  1437. \label{fig:pe-arith}
  1438. \end{figure}
  1439. To gain some confidence that the partial evaluator is correct, we can
  1440. test whether it produces programs that get the same result as the
  1441. input programs. That is, we can test whether it satisfies Diagram
  1442. \ref{eq:compile-correct}.
  1443. %
  1444. {\if\edition\racketEd
  1445. The following code runs the partial evaluator on several examples and
  1446. tests the output program. The \texttt{parse-program} and
  1447. \texttt{assert} functions are defined in
  1448. Appendix~\ref{appendix:utilities}.\\
  1449. \begin{minipage}{1.0\textwidth}
  1450. \begin{lstlisting}
  1451. (define (test_pe p)
  1452. (assert "testing pe_Lint"
  1453. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1454. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1455. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1456. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1457. \end{lstlisting}
  1458. \end{minipage}
  1459. \fi}
  1460. % TODO: python version of testing the PE
  1461. \begin{exercise}\normalfont
  1462. Create three programs in the \LangInt{} language and test whether
  1463. partially evaluating them with \code{pe\_Lint} and then
  1464. interpreting them with \code{interp\_Lint} gives the same result
  1465. as directly interpreting them with \code{interp\_Lint}.
  1466. \end{exercise}
  1467. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1468. \chapter{Integers and Variables}
  1469. \label{ch:Lvar}
  1470. This chapter is about compiling a subset of
  1471. \racket{Racket}\python{Python} to x86-64 assembly
  1472. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1473. integer arithmetic and local variables. We often refer to x86-64
  1474. simply as x86. The chapter begins with a description of the
  1475. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1476. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language is
  1477. large so we discuss only the instructions needed for compiling
  1478. \LangVar{}. We introduce more x86 instructions in later chapters.
  1479. After introducing \LangVar{} and x86, we reflect on their differences
  1480. and come up with a plan to break down the translation from \LangVar{}
  1481. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1482. rest of the sections in this chapter give detailed hints regarding
  1483. each step. We hope to give enough hints that the well-prepared
  1484. reader, together with a few friends, can implement a compiler from
  1485. \LangVar{} to x86 in a short time. To give the reader a feeling for
  1486. the scale of this first compiler, the instructor solution for the
  1487. \LangVar{} compiler is approximately \racket{500}\python{300} lines of
  1488. code.
  1489. \section{The \LangVar{} Language}
  1490. \label{sec:s0}
  1491. \index{subject}{variable}
  1492. The \LangVar{} language extends the \LangInt{} language with
  1493. variables. The concrete syntax of the \LangVar{} language is defined
  1494. by the grammar in Figure~\ref{fig:Lvar-concrete-syntax} and the
  1495. abstract syntax is defined in Figure~\ref{fig:Lvar-syntax}. The
  1496. non-terminal \Var{} may be any \racket{Racket}\python{Python} identifier.
  1497. As in \LangInt{}, \READOP{} is a nullary operator, \key{-} is a unary operator, and
  1498. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1499. syntax of \LangVar{} includes the \racket{\key{Program}
  1500. struct}\python{\key{Module} instance} to mark the top of the
  1501. program.
  1502. %% The $\itm{info}$
  1503. %% field of the \key{Program} structure contains an \emph{association
  1504. %% list} (a list of key-value pairs) that is used to communicate
  1505. %% auxiliary data from one compiler pass the next.
  1506. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1507. exhibit several compilation techniques.
  1508. \newcommand{\LvarGrammarRacket}{
  1509. \begin{array}{rcl}
  1510. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1511. \end{array}
  1512. }
  1513. \newcommand{\LvarAST}{
  1514. \begin{array}{rcl}
  1515. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1516. \end{array}
  1517. }
  1518. \newcommand{\LvarGrammarPython}{
  1519. \begin{array}{rcl}
  1520. \Exp &::=& \Var{} \\
  1521. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1522. \end{array}
  1523. }
  1524. \newcommand{\LvarASTPython}{
  1525. \begin{array}{rcl}
  1526. \Exp{} &::=& \VAR{\Var{}} \\
  1527. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1528. \end{array}
  1529. }
  1530. \begin{figure}[tp]
  1531. \centering
  1532. \fbox{
  1533. \begin{minipage}{0.96\textwidth}
  1534. {\if\edition\racketEd
  1535. \[
  1536. \begin{array}{l}
  1537. \gray{\LintGrammarRacket{}} \\ \hline
  1538. \LvarGrammarRacket{} \\
  1539. \begin{array}{rcl}
  1540. \LangVarM{} &::=& \Exp
  1541. \end{array}
  1542. \end{array}
  1543. \]
  1544. \fi}
  1545. {\if\edition\pythonEd
  1546. \[
  1547. \begin{array}{l}
  1548. \gray{\LintGrammarPython} \\ \hline
  1549. \LvarGrammarPython \\
  1550. \begin{array}{rcl}
  1551. \LangVarM{} &::=& \Stmt^{*}
  1552. \end{array}
  1553. \end{array}
  1554. \]
  1555. \fi}
  1556. \end{minipage}
  1557. }
  1558. \caption{The concrete syntax of \LangVar{}.}
  1559. \label{fig:Lvar-concrete-syntax}
  1560. \end{figure}
  1561. \begin{figure}[tp]
  1562. \centering
  1563. \fbox{
  1564. \begin{minipage}{0.96\textwidth}
  1565. {\if\edition\racketEd
  1566. \[
  1567. \begin{array}{l}
  1568. \gray{\LintASTRacket{}} \\ \hline
  1569. \LvarAST \\
  1570. \begin{array}{rcl}
  1571. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1572. \end{array}
  1573. \end{array}
  1574. \]
  1575. \fi}
  1576. {\if\edition\pythonEd
  1577. \[
  1578. \begin{array}{l}
  1579. \gray{\LintASTPython}\\ \hline
  1580. \LvarASTPython \\
  1581. \begin{array}{rcl}
  1582. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1583. \end{array}
  1584. \end{array}
  1585. \]
  1586. \fi}
  1587. \end{minipage}
  1588. }
  1589. \caption{The abstract syntax of \LangVar{}.}
  1590. \label{fig:Lvar-syntax}
  1591. \end{figure}
  1592. {\if\edition\racketEd
  1593. Let us dive further into the syntax and semantics of the \LangVar{}
  1594. language. The \key{let} feature defines a variable for use within its
  1595. body and initializes the variable with the value of an expression.
  1596. The abstract syntax for \key{let} is defined in
  1597. Figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1598. \begin{lstlisting}
  1599. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1600. \end{lstlisting}
  1601. For example, the following program initializes \code{x} to $32$ and then
  1602. evaluates the body \code{(+ 10 x)}, producing $42$.
  1603. \begin{lstlisting}
  1604. (let ([x (+ 12 20)]) (+ 10 x))
  1605. \end{lstlisting}
  1606. \fi}
  1607. %
  1608. {\if\edition\pythonEd
  1609. %
  1610. The \LangVar{} language includes assignment statements, which define a
  1611. variable for use in later statements and initializes the variable with
  1612. the value of an expression. The abstract syntax for assignment is
  1613. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1614. assignment is
  1615. \begin{lstlisting}
  1616. |$\itm{var}$| = |$\itm{exp}$|
  1617. \end{lstlisting}
  1618. For example, the following program initializes the variable \code{x}
  1619. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1620. \begin{lstlisting}
  1621. x = 12 + 20
  1622. print(10 + x)
  1623. \end{lstlisting}
  1624. \fi}
  1625. {\if\edition\racketEd
  1626. %
  1627. When there are multiple \key{let}'s for the same variable, the closest
  1628. enclosing \key{let} is used. That is, variable definitions overshadow
  1629. prior definitions. Consider the following program with two \key{let}'s
  1630. that define variables named \code{x}. Can you figure out the result?
  1631. \begin{lstlisting}
  1632. (let ([x 32]) (+ (let ([x 10]) x) x))
  1633. \end{lstlisting}
  1634. For the purposes of depicting which variable uses correspond to which
  1635. definitions, the following shows the \code{x}'s annotated with
  1636. subscripts to distinguish them. Double check that your answer for the
  1637. above is the same as your answer for this annotated version of the
  1638. program.
  1639. \begin{lstlisting}
  1640. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1641. \end{lstlisting}
  1642. The initializing expression is always evaluated before the body of the
  1643. \key{let}, so in the following, the \key{read} for \code{x} is
  1644. performed before the \key{read} for \code{y}. Given the input
  1645. $52$ then $10$, the following produces $42$ (not $-42$).
  1646. \begin{lstlisting}
  1647. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1648. \end{lstlisting}
  1649. \fi}
  1650. \subsection{Extensible Interpreters via Method Overriding}
  1651. \label{sec:extensible-interp}
  1652. To prepare for discussing the interpreter of \LangVar{}, we explain
  1653. why we implement it in an object-oriented style. Throughout this book
  1654. we define many interpreters, one for each of language that we
  1655. study. Because each language builds on the prior one, there is a lot
  1656. of commonality between these interpreters. We want to write down the
  1657. common parts just once instead of many times. A naive approach would
  1658. be for the interpreter of \LangVar{} to handle the
  1659. \racket{cases for variables and \code{let}}
  1660. \python{case for variables}
  1661. but dispatch to \LangInt{}
  1662. for the rest of the cases. The following code sketches this idea. (We
  1663. explain the \code{env} parameter soon, in
  1664. Section~\ref{sec:interp-Lvar}.)
  1665. \begin{center}
  1666. {\if\edition\racketEd
  1667. \begin{minipage}{0.45\textwidth}
  1668. \begin{lstlisting}
  1669. (define ((interp_Lint env) e)
  1670. (match e
  1671. [(Prim '- (list e1))
  1672. (fx- 0 ((interp_Lint env) e1))]
  1673. ...))
  1674. \end{lstlisting}
  1675. \end{minipage}
  1676. \begin{minipage}{0.45\textwidth}
  1677. \begin{lstlisting}
  1678. (define ((interp_Lvar env) e)
  1679. (match e
  1680. [(Var x)
  1681. (dict-ref env x)]
  1682. [(Let x e body)
  1683. (define v ((interp_exp env) e))
  1684. (define env^ (dict-set env x v))
  1685. ((interp_exp env^) body)]
  1686. [else ((interp_Lint env) e)]))
  1687. \end{lstlisting}
  1688. \end{minipage}
  1689. \fi}
  1690. {\if\edition\pythonEd
  1691. \begin{minipage}{0.45\textwidth}
  1692. \begin{lstlisting}
  1693. def interp_Lint(e, env):
  1694. match e:
  1695. case UnaryOp(USub(), e1):
  1696. return - interp_Lint(e1, env)
  1697. ...
  1698. \end{lstlisting}
  1699. \end{minipage}
  1700. \begin{minipage}{0.45\textwidth}
  1701. \begin{lstlisting}
  1702. def interp_Lvar(e, env):
  1703. match e:
  1704. case Name(id):
  1705. return env[id]
  1706. case _:
  1707. return interp_Lint(e, env)
  1708. \end{lstlisting}
  1709. \end{minipage}
  1710. \fi}
  1711. \end{center}
  1712. The problem with this approach is that it does not handle situations
  1713. in which an \LangVar{} feature, such as a variable, is nested inside
  1714. an \LangInt{} feature, like the \code{-} operator, as in the following
  1715. program.
  1716. %
  1717. {\if\edition\racketEd
  1718. \begin{lstlisting}
  1719. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1720. \end{lstlisting}
  1721. \fi}
  1722. {\if\edition\pythonEd
  1723. \begin{lstlisting}
  1724. y = 10
  1725. print(-y)
  1726. \end{lstlisting}
  1727. \fi}
  1728. %
  1729. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1730. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1731. then it recursively calls \code{interp\_Lint} again on its argument.
  1732. But there is no case for \code{Var} in \code{interp\_Lint} so we get
  1733. an error!
  1734. To make our interpreters extensible we need something called
  1735. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1736. recursive knot is delayed to when the functions are
  1737. composed. Object-oriented languages provide open recursion via
  1738. method overriding\index{subject}{method overriding}. The
  1739. following code uses method overriding to interpret \LangInt{} and
  1740. \LangVar{} using
  1741. %
  1742. \racket{the
  1743. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1744. \index{subject}{class} feature of Racket}
  1745. %
  1746. \python{a Python \code{class} definition}.
  1747. %
  1748. We define one class for each language and define a method for
  1749. interpreting expressions inside each class. The class for \LangVar{}
  1750. inherits from the class for \LangInt{} and the method
  1751. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1752. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1753. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1754. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1755. \code{interp\_exp} in \LangInt{}.
  1756. \begin{center}
  1757. \hspace{-20pt}
  1758. {\if\edition\racketEd
  1759. \begin{minipage}{0.45\textwidth}
  1760. \begin{lstlisting}
  1761. (define interp_Lint_class
  1762. (class object%
  1763. (define/public ((interp_exp env) e)
  1764. (match e
  1765. [(Prim '- (list e))
  1766. (fx- 0 ((interp_exp env) e))]
  1767. ...))
  1768. ...))
  1769. \end{lstlisting}
  1770. \end{minipage}
  1771. \begin{minipage}{0.45\textwidth}
  1772. \begin{lstlisting}
  1773. (define interp_Lvar_class
  1774. (class interp_Lint_class
  1775. (define/override ((interp_exp env) e)
  1776. (match e
  1777. [(Var x)
  1778. (dict-ref env x)]
  1779. [(Let x e body)
  1780. (define v ((interp_exp env) e))
  1781. (define env^ (dict-set env x v))
  1782. ((interp_exp env^) body)]
  1783. [else
  1784. (super (interp_exp env) e)]))
  1785. ...
  1786. ))
  1787. \end{lstlisting}
  1788. \end{minipage}
  1789. \fi}
  1790. {\if\edition\pythonEd
  1791. \begin{minipage}{0.45\textwidth}
  1792. \begin{lstlisting}
  1793. class InterpLint:
  1794. def interp_exp(e):
  1795. match e:
  1796. case UnaryOp(USub(), e1):
  1797. return -self.interp_exp(e1)
  1798. ...
  1799. ...
  1800. \end{lstlisting}
  1801. \end{minipage}
  1802. \begin{minipage}{0.45\textwidth}
  1803. \begin{lstlisting}
  1804. def InterpLvar(InterpLint):
  1805. def interp_exp(e):
  1806. match e:
  1807. case Name(id):
  1808. return env[id]
  1809. case _:
  1810. return super().interp_exp(e)
  1811. ...
  1812. \end{lstlisting}
  1813. \end{minipage}
  1814. \fi}
  1815. \end{center}
  1816. Getting back to the troublesome example, repeated here:
  1817. {\if\edition\racketEd
  1818. \begin{lstlisting}
  1819. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1820. \end{lstlisting}
  1821. \fi}
  1822. {\if\edition\pythonEd
  1823. \begin{lstlisting}
  1824. y = 10
  1825. print(-y)
  1826. \end{lstlisting}
  1827. \fi}
  1828. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1829. \racket{on this expression,}
  1830. \python{on the \code{-y} expression,}
  1831. %
  1832. call it \code{e0}, by creating an object of the \LangVar{} class
  1833. and calling the \code{interp\_exp} method.
  1834. {\if\edition\racketEd
  1835. \begin{lstlisting}
  1836. (send (new interp_Lvar_class) interp_exp e0)
  1837. \end{lstlisting}
  1838. \fi}
  1839. {\if\edition\pythonEd
  1840. \begin{lstlisting}
  1841. InterpLvar().interp_exp(e0)
  1842. \end{lstlisting}
  1843. \fi}
  1844. \noindent To process the \code{-} operator, the default case of
  1845. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1846. method in \LangInt{}. But then for the recursive method call, it
  1847. dispatches back to \code{interp\_exp} in \LangVar{}, where the
  1848. \code{Var} node is handled correctly. Thus, method overriding gives us
  1849. the open recursion that we need to implement our interpreters in an
  1850. extensible way.
  1851. \subsection{Definitional Interpreter for \LangVar{}}
  1852. \label{sec:interp-Lvar}
  1853. {\if\edition\racketEd
  1854. \begin{figure}[tp]
  1855. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1856. \small
  1857. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1858. An \emph{association list} (alist) is a list of key-value pairs.
  1859. For example, we can map people to their ages with an alist.
  1860. \index{subject}{alist}\index{subject}{association list}
  1861. \begin{lstlisting}[basicstyle=\ttfamily]
  1862. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1863. \end{lstlisting}
  1864. The \emph{dictionary} interface is for mapping keys to values.
  1865. Every alist implements this interface. \index{subject}{dictionary} The package
  1866. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1867. provides many functions for working with dictionaries. Here
  1868. are a few of them:
  1869. \begin{description}
  1870. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1871. returns the value associated with the given $\itm{key}$.
  1872. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1873. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1874. but otherwise is the same as $\itm{dict}$.
  1875. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1876. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1877. of keys and values in $\itm{dict}$. For example, the following
  1878. creates a new alist in which the ages are incremented.
  1879. \end{description}
  1880. \vspace{-10pt}
  1881. \begin{lstlisting}[basicstyle=\ttfamily]
  1882. (for/list ([(k v) (in-dict ages)])
  1883. (cons k (add1 v)))
  1884. \end{lstlisting}
  1885. \end{tcolorbox}
  1886. %\end{wrapfigure}
  1887. \caption{Association lists implement the dictionary interface.}
  1888. \label{fig:alist}
  1889. \end{figure}
  1890. \fi}
  1891. Having justified the use of classes and methods to implement
  1892. interpreters, we revisit the definitional interpreter for \LangInt{}
  1893. in Figure~\ref{fig:interp-Lint-class} and then extend it to create an
  1894. interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}. The
  1895. interpreter for \LangVar{} adds two new \key{match} cases for
  1896. variables and \racket{\key{let}}\python{assignment}. For
  1897. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1898. value bound to a variable to all the uses of the variable. To
  1899. accomplish this, we maintain a mapping from variables to values
  1900. called an \emph{environment}\index{subject}{environment}.
  1901. %
  1902. We use%
  1903. %
  1904. \racket{an association list (alist)}
  1905. %
  1906. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary}}
  1907. %
  1908. to represent the environment.
  1909. %
  1910. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1911. and the \code{racket/dict} package.}
  1912. %
  1913. The \code{interp\_exp} function takes the current environment,
  1914. \code{env}, as an extra parameter. When the interpreter encounters a
  1915. variable, it looks up the corresponding value in the dictionary.
  1916. %
  1917. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1918. initializing expression, extends the environment with the result
  1919. value bound to the variable, using \code{dict-set}, then evaluates
  1920. the body of the \key{Let}.}
  1921. %
  1922. \python{When the interpreter encounters an assignment, it evaluates
  1923. the initializing expression and then associates the resulting value
  1924. with the variable in the environment.}
  1925. \begin{figure}[tp]
  1926. {\if\edition\racketEd
  1927. \begin{lstlisting}
  1928. (define interp_Lint_class
  1929. (class object%
  1930. (super-new)
  1931. (define/public ((interp_exp env) e)
  1932. (match e
  1933. [(Int n) n]
  1934. [(Prim 'read '())
  1935. (define r (read))
  1936. (cond [(fixnum? r) r]
  1937. [else (error 'interp_exp "expected an integer" r)])]
  1938. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1939. [(Prim '+ (list e1 e2))
  1940. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]))
  1941. (define/public (interp_program p)
  1942. (match p
  1943. [(Program '() e) ((interp_exp '()) e)]))
  1944. ))
  1945. \end{lstlisting}
  1946. \fi}
  1947. {\if\edition\pythonEd
  1948. \begin{lstlisting}
  1949. class InterpLint:
  1950. def interp_exp(self, e, env):
  1951. match e:
  1952. case BinOp(left, Add(), right):
  1953. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1954. case UnaryOp(USub(), v):
  1955. return - self.interp_exp(v, env)
  1956. case Constant(value):
  1957. return value
  1958. case Call(Name('input_int'), []):
  1959. return int(input())
  1960. def interp_stmts(self, ss, env):
  1961. if len(ss) == 0:
  1962. return
  1963. match ss[0]:
  1964. case Expr(Call(Name('print'), [arg])):
  1965. print(self.interp_exp(arg, env), end='')
  1966. return self.interp_stmts(ss[1:], env)
  1967. case Expr(value):
  1968. self.interp_exp(value, env)
  1969. return self.interp_stmts(ss[1:], env)
  1970. def interp(self, p):
  1971. match p:
  1972. case Module(body):
  1973. self.interp_stmts(body, {})
  1974. def interp_Lint(p):
  1975. return InterpLint().interp(p)
  1976. \end{lstlisting}
  1977. \fi}
  1978. \caption{Interpreter for \LangInt{} as a class.}
  1979. \label{fig:interp-Lint-class}
  1980. \end{figure}
  1981. \begin{figure}[tp]
  1982. {\if\edition\racketEd
  1983. \begin{lstlisting}
  1984. (define interp_Lvar_class
  1985. (class interp_Lint_class
  1986. (super-new)
  1987. (define/override ((interp_exp env) e)
  1988. (match e
  1989. [(Var x) (dict-ref env x)]
  1990. [(Let x e body)
  1991. (define new-env (dict-set env x ((interp_exp env) e)))
  1992. ((interp_exp new-env) body)]
  1993. [else ((super interp-exp env) e)]))
  1994. ))
  1995. (define (interp_Lvar p)
  1996. (send (new interp_Lvar_class) interp_program p))
  1997. \end{lstlisting}
  1998. \fi}
  1999. {\if\edition\pythonEd
  2000. \begin{lstlisting}
  2001. class InterpLvar(InterpLint):
  2002. def interp_exp(self, e, env):
  2003. match e:
  2004. case Name(id):
  2005. return env[id]
  2006. case _:
  2007. return super().interp_exp(e, env)
  2008. def interp_stmts(self, ss, env):
  2009. if len(ss) == 0:
  2010. return
  2011. match ss[0]:
  2012. case Assign([lhs], value):
  2013. env[lhs.id] = self.interp_exp(value, env)
  2014. return self.interp_stmts(ss[1:], env)
  2015. case _:
  2016. return super().interp_stmts(ss, env)
  2017. def interp_Lvar(p):
  2018. return InterpLvar().interp(p)
  2019. \end{lstlisting}
  2020. \fi}
  2021. \caption{Interpreter for the \LangVar{} language.}
  2022. \label{fig:interp-Lvar}
  2023. \end{figure}
  2024. The goal for this chapter is to implement a compiler that translates
  2025. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2026. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2027. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2028. That is, they output the same integer $n$. We depict this correctness
  2029. criteria in the following diagram.
  2030. \[
  2031. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2032. \node (p1) at (0, 0) {$P_1$};
  2033. \node (p2) at (4, 0) {$P_2$};
  2034. \node (o) at (4, -2) {$n$};
  2035. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2036. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2037. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2038. \end{tikzpicture}
  2039. \]
  2040. In the next section we introduce the \LangXInt{} subset of x86 that
  2041. suffices for compiling \LangVar{}.
  2042. \section{The \LangXInt{} Assembly Language}
  2043. \label{sec:x86}
  2044. \index{subject}{x86}
  2045. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2046. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2047. assembler.
  2048. %
  2049. A program begins with a \code{main} label followed by a sequence of
  2050. instructions. The \key{globl} directive says that the \key{main}
  2051. procedure is externally visible, which is necessary so that the
  2052. operating system can call it.
  2053. %
  2054. An x86 program is stored in the computer's memory. For our purposes,
  2055. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2056. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  2057. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  2058. the address of the next instruction to be executed. For most
  2059. instructions, the program counter is incremented after the instruction
  2060. is executed, so it points to the next instruction in memory. Most x86
  2061. instructions take two operands, where each operand is either an
  2062. integer constant (called an \emph{immediate value}\index{subject}{immediate
  2063. value}), a \emph{register}\index{subject}{register}, or a memory location.
  2064. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2065. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2066. && \key{r8} \MID \key{r9} \MID \key{r10}
  2067. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2068. \MID \key{r14} \MID \key{r15}}
  2069. \begin{figure}[tp]
  2070. \fbox{
  2071. \begin{minipage}{0.96\textwidth}
  2072. {\if\edition\racketEd
  2073. \[
  2074. \begin{array}{lcl}
  2075. \Reg &::=& \allregisters{} \\
  2076. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2077. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2078. \key{subq} \; \Arg\key{,} \Arg \MID
  2079. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2080. && \key{callq} \; \mathit{label} \MID
  2081. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \key{jmp}\,\itm{label} \\
  2082. && \itm{label}\key{:}\; \Instr \\
  2083. \LangXIntM{} &::= & \key{.globl main}\\
  2084. & & \key{main:} \; \Instr\ldots
  2085. \end{array}
  2086. \]
  2087. \fi}
  2088. {\if\edition\pythonEd
  2089. \[
  2090. \begin{array}{lcl}
  2091. \Reg &::=& \allregisters{} \\
  2092. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2093. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2094. \key{subq} \; \Arg\key{,} \Arg \MID
  2095. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2096. && \key{callq} \; \mathit{label} \MID
  2097. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2098. \LangXIntM{} &::= & \key{.globl main}\\
  2099. & & \key{main:} \; \Instr^{*}
  2100. \end{array}
  2101. \]
  2102. \fi}
  2103. \end{minipage}
  2104. }
  2105. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2106. \label{fig:x86-int-concrete}
  2107. \end{figure}
  2108. A register is a special kind of variable that holds a 64-bit
  2109. value. There are 16 general-purpose registers in the computer and
  2110. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  2111. is written with a \key{\%} followed by the register name, such as
  2112. \key{\%rax}.
  2113. An immediate value is written using the notation \key{\$}$n$ where $n$
  2114. is an integer.
  2115. %
  2116. %
  2117. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2118. which obtains the address stored in register $r$ and then adds $n$
  2119. bytes to the address. The resulting address is used to load or store
  2120. to memory depending on whether it occurs as a source or destination
  2121. argument of an instruction.
  2122. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  2123. source $s$ and destination $d$, applies the arithmetic operation, then
  2124. writes the result back to the destination $d$. \index{subject}{instruction}
  2125. %
  2126. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2127. stores the result in $d$.
  2128. %
  2129. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2130. specified by the label and $\key{retq}$ returns from a procedure to
  2131. its caller.
  2132. %
  2133. We discuss procedure calls in more detail later in this chapter and in
  2134. Chapter~\ref{ch:Rfun}.
  2135. %
  2136. The last letter \key{q} indicates that these instructions operate on
  2137. quadwords, i.e., 64-bit values.
  2138. %
  2139. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2140. counter to the address of the instruction after the specified
  2141. label.}
  2142. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  2143. all of the x86 instructions used in this book.
  2144. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2145. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2146. \lstinline{movq $10, %rax}
  2147. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  2148. adds $32$ to the $10$ in \key{rax} and
  2149. puts the result, $42$, back into \key{rax}.
  2150. %
  2151. The last instruction, \key{retq}, finishes the \key{main} function by
  2152. returning the integer in \key{rax} to the operating system. The
  2153. operating system interprets this integer as the program's exit
  2154. code. By convention, an exit code of 0 indicates that a program
  2155. completed successfully, and all other exit codes indicate various
  2156. errors.
  2157. %
  2158. \racket{Nevertheless, in this book we return the result of the program
  2159. as the exit code.}
  2160. \begin{figure}[tbp]
  2161. \begin{lstlisting}
  2162. .globl main
  2163. main:
  2164. movq $10, %rax
  2165. addq $32, %rax
  2166. retq
  2167. \end{lstlisting}
  2168. \caption{An x86 program that computes
  2169. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2170. \label{fig:p0-x86}
  2171. \end{figure}
  2172. We exhibit the use of memory for storing intermediate results in the
  2173. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2174. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2175. uses a region of memory called the \emph{procedure call stack} (or
  2176. \emph{stack} for
  2177. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2178. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2179. for each procedure call. The memory layout for an individual frame is
  2180. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2181. \emph{stack pointer}\index{subject}{stack pointer} and points to the
  2182. item at the top of the stack. The stack grows downward in memory, so
  2183. we increase the size of the stack by subtracting from the stack
  2184. pointer. In the context of a procedure call, the \emph{return
  2185. address}\index{subject}{return address} is the instruction after the
  2186. call instruction on the caller side. The function call instruction,
  2187. \code{callq}, pushes the return address onto the stack prior to
  2188. jumping to the procedure. The register \key{rbp} is the \emph{base
  2189. pointer}\index{subject}{base pointer} and is used to access variables
  2190. that are stored in the frame of the current procedure call. The base
  2191. pointer of the caller is store after the return address. In
  2192. Figure~\ref{fig:frame} we number the variables from $1$ to
  2193. $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$
  2194. at $-16\key{(\%rbp)}$, etc.
  2195. \begin{figure}[tbp]
  2196. {\if\edition\racketEd
  2197. \begin{lstlisting}
  2198. start:
  2199. movq $10, -8(%rbp)
  2200. negq -8(%rbp)
  2201. movq -8(%rbp), %rax
  2202. addq $52, %rax
  2203. jmp conclusion
  2204. .globl main
  2205. main:
  2206. pushq %rbp
  2207. movq %rsp, %rbp
  2208. subq $16, %rsp
  2209. jmp start
  2210. conclusion:
  2211. addq $16, %rsp
  2212. popq %rbp
  2213. retq
  2214. \end{lstlisting}
  2215. \fi}
  2216. {\if\edition\pythonEd
  2217. \begin{lstlisting}
  2218. .globl main
  2219. main:
  2220. pushq %rbp
  2221. movq %rsp, %rbp
  2222. subq $16, %rsp
  2223. movq $10, -8(%rbp)
  2224. negq -8(%rbp)
  2225. movq -8(%rbp), %rax
  2226. addq $52, %rax
  2227. addq $16, %rsp
  2228. popq %rbp
  2229. retq
  2230. \end{lstlisting}
  2231. \fi}
  2232. \caption{An x86 program that computes
  2233. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2234. \label{fig:p1-x86}
  2235. \end{figure}
  2236. \begin{figure}[tbp]
  2237. \centering
  2238. \begin{tabular}{|r|l|} \hline
  2239. Position & Contents \\ \hline
  2240. 8(\key{\%rbp}) & return address \\
  2241. 0(\key{\%rbp}) & old \key{rbp} \\
  2242. -8(\key{\%rbp}) & variable $1$ \\
  2243. -16(\key{\%rbp}) & variable $2$ \\
  2244. \ldots & \ldots \\
  2245. 0(\key{\%rsp}) & variable $n$\\ \hline
  2246. \end{tabular}
  2247. \caption{Memory layout of a frame.}
  2248. \label{fig:frame}
  2249. \end{figure}
  2250. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2251. control is transferred from the operating system to the \code{main}
  2252. function. The operating system issues a \code{callq main} instruction
  2253. which pushes its return address on the stack and then jumps to
  2254. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2255. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2256. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2257. alignment (because the \code{callq} pushed the return address). The
  2258. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  2259. for a procedure. The instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2260. pointer and then saves the base pointer of the caller at address
  2261. \code{rsp} on the stack. The next instruction \code{movq \%rsp, \%rbp} sets the
  2262. base pointer to the current stack pointer, which is pointing at the location
  2263. of the old base pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  2264. pointer down to make enough room for storing variables. This program
  2265. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  2266. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  2267. functions.
  2268. \racket{The last instruction of the prelude is \code{jmp start},
  2269. which transfers control to the instructions that were generated from
  2270. the expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2271. \racket{The first instruction under the \code{start} label is}
  2272. %
  2273. \python{The first instruction after the prelude is}
  2274. %
  2275. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2276. %
  2277. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  2278. %
  2279. The next instruction moves the $-10$ from variable $1$ into the
  2280. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2281. the value in \code{rax}, updating its contents to $42$.
  2282. \racket{The three instructions under the label \code{conclusion} are the
  2283. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2284. %
  2285. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2286. \code{main} function consists of the last three instructions.}
  2287. %
  2288. The first two restore the \code{rsp} and \code{rbp} registers to the
  2289. state they were in at the beginning of the procedure. In particular,
  2290. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  2291. old base pointer. Then \key{popq \%rbp} returns the old base pointer
  2292. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2293. \key{retq}, jumps back to the procedure that called this one and adds
  2294. $8$ to the stack pointer.
  2295. Our compiler needs a convenient representation for manipulating x86
  2296. programs, so we define an abstract syntax for x86 in
  2297. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2298. \LangXInt{}.
  2299. %
  2300. {\if\edition\pythonEd%
  2301. The main difference compared to the concrete syntax of \LangXInt{}
  2302. (Figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2303. names, and register names are explicitly represented by strings.
  2304. \fi} %
  2305. {\if\edition\racketEd
  2306. The main difference compared to the concrete syntax of \LangXInt{}
  2307. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2308. front of every instruction. Instead instructions are grouped into
  2309. \emph{blocks}\index{subject}{block} with a
  2310. label associated with every block, which is why the \key{X86Program}
  2311. struct includes an alist mapping labels to blocks. The reason for this
  2312. organization becomes apparent in Chapter~\ref{ch:Lif} when we
  2313. introduce conditional branching. The \code{Block} structure includes
  2314. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2315. useful in Chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2316. $\itm{info}$ field should contain an empty list.
  2317. \fi}
  2318. %
  2319. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2320. node includes an integer for representing the arity of the function,
  2321. i.e., the number of arguments, which is helpful to know during
  2322. register allocation (Chapter~\ref{ch:register-allocation-Lvar}).
  2323. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2324. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2325. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2326. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2327. \MID \skey{r14} \MID \skey{r15}}
  2328. \begin{figure}[tp]
  2329. \fbox{
  2330. \begin{minipage}{0.98\textwidth}
  2331. \small
  2332. {\if\edition\racketEd
  2333. \[
  2334. \begin{array}{lcl}
  2335. \Reg &::=& \allregisters{} \\
  2336. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2337. \MID \DEREF{\Reg}{\Int} \\
  2338. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2339. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2340. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2341. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2342. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2343. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2344. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2345. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2346. \end{array}
  2347. \]
  2348. \fi}
  2349. {\if\edition\pythonEd
  2350. \[
  2351. \begin{array}{lcl}
  2352. \Reg &::=& \allastregisters{} \\
  2353. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2354. \MID \DEREF{\Reg}{\Int} \\
  2355. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2356. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2357. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2358. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2359. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2360. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2361. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2362. \end{array}
  2363. \]
  2364. \fi}
  2365. \end{minipage}
  2366. }
  2367. \caption{The abstract syntax of \LangXInt{} assembly.}
  2368. \label{fig:x86-int-ast}
  2369. \end{figure}
  2370. \section{Planning the trip to x86}
  2371. \label{sec:plan-s0-x86}
  2372. To compile one language to another it helps to focus on the
  2373. differences between the two languages because the compiler will need
  2374. to bridge those differences. What are the differences between \LangVar{}
  2375. and x86 assembly? Here are some of the most important ones:
  2376. \begin{enumerate}
  2377. \item x86 arithmetic instructions typically have two arguments and
  2378. update the second argument in place. In contrast, \LangVar{}
  2379. arithmetic operations take two arguments and produce a new value.
  2380. An x86 instruction may have at most one memory-accessing argument.
  2381. Furthermore, some x86 instructions place special restrictions on
  2382. their arguments.
  2383. \item An argument of an \LangVar{} operator can be a deeply-nested
  2384. expression, whereas x86 instructions restrict their arguments to be
  2385. integer constants, registers, and memory locations.
  2386. {\if\edition\racketEd
  2387. \item The order of execution in x86 is explicit in the syntax: a
  2388. sequence of instructions and jumps to labeled positions, whereas in
  2389. \LangVar{} the order of evaluation is a left-to-right depth-first
  2390. traversal of the abstract syntax tree.
  2391. \fi}
  2392. \item A program in \LangVar{} can have any number of variables
  2393. whereas x86 has 16 registers and the procedure call stack.
  2394. {\if\edition\racketEd
  2395. \item Variables in \LangVar{} can shadow other variables with the
  2396. same name. In x86, registers have unique names and memory locations
  2397. have unique addresses.
  2398. \fi}
  2399. \end{enumerate}
  2400. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2401. down the problem into several steps, dealing with the above
  2402. differences one at a time. Each of these steps is called a \emph{pass}
  2403. of the compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2404. %
  2405. This terminology comes from the way each step passes over, that is,
  2406. traverses the AST of the program.
  2407. %
  2408. Furthermore, we follow the nanopass approach, which means we strive
  2409. for each pass to accomplish one clear objective (not two or three at
  2410. the same time).
  2411. %
  2412. We begin by sketching how we might implement each pass, and give them
  2413. names. We then figure out an ordering of the passes and the
  2414. input/output language for each pass. The very first pass has
  2415. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2416. its output language. In between we can choose whichever language is
  2417. most convenient for expressing the output of each pass, whether that
  2418. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2419. our own design. Finally, to implement each pass we write one
  2420. recursive function per non-terminal in the grammar of the input
  2421. language of the pass. \index{subject}{intermediate language}
  2422. Our compiler for \LangVar{} consists of the following passes.
  2423. %
  2424. \begin{description}
  2425. {\if\edition\racketEd
  2426. \item[\key{uniquify}] deals with the shadowing of variables by
  2427. renaming every variable to a unique name.
  2428. \fi}
  2429. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2430. of a primitive operation or function call is a variable or integer,
  2431. that is, an \emph{atomic} expression. We refer to non-atomic
  2432. expressions as \emph{complex}. This pass introduces temporary
  2433. variables to hold the results of complex
  2434. subexpressions.\index{subject}{atomic
  2435. expression}\index{subject}{complex expression}%
  2436. {\if\edition\racketEd
  2437. \item[\key{explicate\_control}] makes the execution order of the
  2438. program explicit. It converts the abstract syntax tree representation
  2439. into a control-flow graph in which each node contains a sequence of
  2440. statements and the edges between nodes say which nodes contain jumps
  2441. to other nodes.
  2442. \fi}
  2443. \item[\key{select\_instructions}] handles the difference between
  2444. \LangVar{} operations and x86 instructions. This pass converts each
  2445. \LangVar{} operation to a short sequence of instructions that
  2446. accomplishes the same task.
  2447. \item[\key{assign\_homes}] replaces variables with registers or stack
  2448. locations.
  2449. \end{description}
  2450. %
  2451. {\if\edition\racketEd
  2452. %
  2453. Our treatment of \code{remove\_complex\_operands} and
  2454. \code{explicate\_control} as separate passes is an example of the
  2455. nanopass approach\footnote{For analogous decompositions of the
  2456. translation into continuation passing style, see the work of
  2457. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2458. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2459. %
  2460. \fi}
  2461. The next question is: in what order should we apply these passes? This
  2462. question can be challenging because it is difficult to know ahead of
  2463. time which orderings will be better (easier to implement, produce more
  2464. efficient code, etc.) so oftentimes trial-and-error is
  2465. involved. Nevertheless, we can try to plan ahead and make educated
  2466. choices regarding the ordering.
  2467. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2468. \key{uniquify}? The \key{uniquify} pass should come first because
  2469. \key{explicate\_control} changes all the \key{let}-bound variables to
  2470. become local variables whose scope is the entire program, which would
  2471. confuse variables with the same name.}
  2472. %
  2473. \racket{We place \key{remove\_complex\_opera*} before \key{explicate\_control}
  2474. because the later removes the \key{let} form, but it is convenient to
  2475. use \key{let} in the output of \key{remove\_complex\_opera*}.}
  2476. %
  2477. \racket{The ordering of \key{uniquify} with respect to
  2478. \key{remove\_complex\_opera*} does not matter so we arbitrarily choose
  2479. \key{uniquify} to come first.}
  2480. The \key{select\_instructions} and \key{assign\_homes} passes are
  2481. intertwined.
  2482. %
  2483. In Chapter~\ref{ch:Rfun} we learn that, in x86, registers are used for
  2484. passing arguments to functions and it is preferable to assign
  2485. parameters to their corresponding registers. This suggests that it
  2486. would be better to start with the \key{select\_instructions} pass,
  2487. which generates the instructions for argument passing, before
  2488. performing register allocation.
  2489. %
  2490. On the other hand, by selecting instructions first we may run into a
  2491. dead end in \key{assign\_homes}. Recall that only one argument of an
  2492. x86 instruction may be a memory access but \key{assign\_homes} might
  2493. be forced to assign both arguments to memory locations.
  2494. %
  2495. A sophisticated approach is to iteratively repeat the two passes until
  2496. a solution is found. However, to reduce implementation complexity we
  2497. recommend placing \key{select\_instructions} first, followed by the
  2498. \key{assign\_homes}, then a third pass named \key{patch\_instructions}
  2499. that uses a reserved register to fix outstanding problems.
  2500. \begin{figure}[tbp]
  2501. {\if\edition\racketEd
  2502. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2503. \node (Lvar) at (0,2) {\large \LangVar{}};
  2504. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2505. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  2506. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2507. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2508. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2509. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2510. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2511. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2512. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2513. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  2514. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2515. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2516. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2517. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2518. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  2519. \end{tikzpicture}
  2520. \fi}
  2521. {\if\edition\pythonEd
  2522. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2523. \node (Lvar) at (0,2) {\large \LangVar{}};
  2524. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2525. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2526. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2527. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2528. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2529. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2530. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2531. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2532. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2533. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2534. \end{tikzpicture}
  2535. \fi}
  2536. \caption{Diagram of the passes for compiling \LangVar{}. }
  2537. \label{fig:Lvar-passes}
  2538. \end{figure}
  2539. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2540. passes and identifies the input and output language of each pass.
  2541. %
  2542. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2543. language, which extends \LangXInt{} with an unbounded number of
  2544. program-scope variables and removes the restrictions regarding
  2545. instruction arguments.
  2546. %
  2547. The last pass, \key{prelude\_and\_conclusion}, places the program
  2548. instructions inside a \code{main} function with instructions for the
  2549. prelude and conclusion.
  2550. %
  2551. \racket{In the following section we discuss the \LangCVar{}
  2552. intermediate language.}
  2553. %
  2554. The remainder of this chapter provides guidance on the implementation
  2555. of each of the compiler passes in Figure~\ref{fig:Lvar-passes}.
  2556. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2557. %% are programs that are still in the \LangVar{} language, though the
  2558. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2559. %% (Section~\ref{sec:remove-complex-opera-Lvar}).
  2560. %% %
  2561. %% The output of \code{explicate\_control} is in an intermediate language
  2562. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2563. %% syntax, which we introduce in the next section. The
  2564. %% \key{select-instruction} pass translates from \LangCVar{} to
  2565. %% \LangXVar{}. The \key{assign-homes} and
  2566. %% \key{patch-instructions}
  2567. %% passes input and output variants of x86 assembly.
  2568. {\if\edition\racketEd
  2569. \subsection{The \LangCVar{} Intermediate Language}
  2570. The output of \code{explicate\_control} is similar to the $C$
  2571. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2572. categories for expressions and statements, so we name it \LangCVar{}.
  2573. This style of intermediate language is also known as
  2574. \emph{three-address code}, to emphasize that the typical form of a
  2575. statement is \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2576. addresses~\citep{Aho:2006wb}.
  2577. The concrete syntax for \LangCVar{} is defined in
  2578. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for
  2579. \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2580. %
  2581. The \LangCVar{} language supports the same operators as \LangVar{} but
  2582. the arguments of operators are restricted to atomic
  2583. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2584. assignment statements which can be executed in sequence using the
  2585. \key{Seq} form. A sequence of statements always ends with
  2586. \key{Return}, a guarantee that is baked into the grammar rules for
  2587. \itm{tail}. The naming of this non-terminal comes from the term
  2588. \emph{tail position}\index{subject}{tail position}, which refers to an
  2589. expression that is the last one to execute within a function.
  2590. A \LangCVar{} program consists of an alist mapping labels to
  2591. tails. This is more general than necessary for the present chapter, as
  2592. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2593. us from having to change the syntax in Chapter~\ref{ch:Lif}. For now
  2594. there will be just one label, \key{start}, and the whole program is
  2595. its tail.
  2596. %
  2597. The $\itm{info}$ field of the \key{CProgram} form, after the
  2598. \code{explicate\_control} pass, contains a mapping from the symbol
  2599. \key{locals} to a list of variables, that is, a list of all the
  2600. variables used in the program. At the start of the program, these
  2601. variables are uninitialized; they become initialized on their first
  2602. assignment.
  2603. \begin{figure}[tbp]
  2604. \fbox{
  2605. \begin{minipage}{0.96\textwidth}
  2606. \[
  2607. \begin{array}{lcl}
  2608. \Atm &::=& \Int \MID \Var \\
  2609. \Exp &::=& \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)}\\
  2610. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  2611. \Tail &::= & \key{return}~\Exp\key{;} \MID \Stmt~\Tail \\
  2612. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2613. \end{array}
  2614. \]
  2615. \end{minipage}
  2616. }
  2617. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2618. \label{fig:c0-concrete-syntax}
  2619. \end{figure}
  2620. \begin{figure}[tbp]
  2621. \fbox{
  2622. \begin{minipage}{0.96\textwidth}
  2623. \[
  2624. \begin{array}{lcl}
  2625. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2626. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2627. &\MID& \ADD{\Atm}{\Atm}\\
  2628. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2629. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} \\
  2630. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2631. \end{array}
  2632. \]
  2633. \end{minipage}
  2634. }
  2635. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2636. \label{fig:c0-syntax}
  2637. \end{figure}
  2638. The definitional interpreter for \LangCVar{} is in the support code,
  2639. in the file \code{interp-Cvar.rkt}.
  2640. \fi}
  2641. {\if\edition\racketEd
  2642. \section{Uniquify Variables}
  2643. \label{sec:uniquify-Lvar}
  2644. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2645. programs in which every \key{let} binds a unique variable name. For
  2646. example, the \code{uniquify} pass should translate the program on the
  2647. left into the program on the right.
  2648. \begin{transformation}
  2649. \begin{lstlisting}
  2650. (let ([x 32])
  2651. (+ (let ([x 10]) x) x))
  2652. \end{lstlisting}
  2653. \compilesto
  2654. \begin{lstlisting}
  2655. (let ([x.1 32])
  2656. (+ (let ([x.2 10]) x.2) x.1))
  2657. \end{lstlisting}
  2658. \end{transformation}
  2659. The following is another example translation, this time of a program
  2660. with a \key{let} nested inside the initializing expression of another
  2661. \key{let}.
  2662. \begin{transformation}
  2663. \begin{lstlisting}
  2664. (let ([x (let ([x 4])
  2665. (+ x 1))])
  2666. (+ x 2))
  2667. \end{lstlisting}
  2668. \compilesto
  2669. \begin{lstlisting}
  2670. (let ([x.2 (let ([x.1 4])
  2671. (+ x.1 1))])
  2672. (+ x.2 2))
  2673. \end{lstlisting}
  2674. \end{transformation}
  2675. We recommend implementing \code{uniquify} by creating a structurally
  2676. recursive function named \code{uniquify-exp} that mostly just copies
  2677. an expression. However, when encountering a \key{let}, it should
  2678. generate a unique name for the variable and associate the old name
  2679. with the new name in an alist.\footnote{The Racket function
  2680. \code{gensym} is handy for generating unique variable names.} The
  2681. \code{uniquify-exp} function needs to access this alist when it gets
  2682. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2683. for the alist.
  2684. The skeleton of the \code{uniquify-exp} function is shown in
  2685. Figure~\ref{fig:uniquify-Lvar}. The function is curried so that it is
  2686. convenient to partially apply it to an alist and then apply it to
  2687. different expressions, as in the last case for primitive operations in
  2688. Figure~\ref{fig:uniquify-Lvar}. The
  2689. %
  2690. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2691. %
  2692. form of Racket is useful for transforming each element of a list to
  2693. produce a new list.\index{subject}{for/list}
  2694. \begin{figure}[tbp]
  2695. \begin{lstlisting}
  2696. (define (uniquify-exp env)
  2697. (lambda (e)
  2698. (match e
  2699. [(Var x) ___]
  2700. [(Int n) (Int n)]
  2701. [(Let x e body) ___]
  2702. [(Prim op es)
  2703. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2704. (define (uniquify p)
  2705. (match p
  2706. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2707. \end{lstlisting}
  2708. \caption{Skeleton for the \key{uniquify} pass.}
  2709. \label{fig:uniquify-Lvar}
  2710. \end{figure}
  2711. \begin{exercise}
  2712. \normalfont % I don't like the italics for exercises. -Jeremy
  2713. Complete the \code{uniquify} pass by filling in the blanks in
  2714. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2715. variables and for the \key{let} form in the file \code{compiler.rkt}
  2716. in the support code.
  2717. \end{exercise}
  2718. \begin{exercise}
  2719. \normalfont % I don't like the italics for exercises. -Jeremy
  2720. \label{ex:Lvar}
  2721. Create five \LangVar{} programs that exercise the most interesting
  2722. parts of the \key{uniquify} pass, that is, the programs should include
  2723. \key{let} forms, variables, and variables that shadow each other.
  2724. The five programs should be placed in the subdirectory named
  2725. \key{tests} and the file names should start with \code{var\_test\_}
  2726. followed by a unique integer and end with the file extension
  2727. \key{.rkt}.
  2728. %
  2729. The \key{run-tests.rkt} script in the support code checks whether the
  2730. output programs produce the same result as the input programs. The
  2731. script uses the \key{interp-tests} function
  2732. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2733. your \key{uniquify} pass on the example programs. The \code{passes}
  2734. parameter of \key{interp-tests} is a list that should have one entry
  2735. for each pass in your compiler. For now, define \code{passes} to
  2736. contain just one entry for \code{uniquify} as shown below.
  2737. \begin{lstlisting}
  2738. (define passes
  2739. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2740. \end{lstlisting}
  2741. Run the \key{run-tests.rkt} script in the support code to check
  2742. whether the output programs produce the same result as the input
  2743. programs.
  2744. \end{exercise}
  2745. \fi}
  2746. \section{Remove Complex Operands}
  2747. \label{sec:remove-complex-opera-Lvar}
  2748. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2749. into a restricted form in which the arguments of operations are atomic
  2750. expressions. Put another way, this pass removes complex
  2751. operands\index{subject}{complex operand}, such as the expression
  2752. \racket{\code{(- 10)}}\python{\code{-10}}
  2753. in the program below. This is accomplished by introducing a new
  2754. temporary variable, assigning the complex operand to the new
  2755. variable, and then using the new variable in place of the complex
  2756. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2757. right.
  2758. {\if\edition\racketEd
  2759. \begin{transformation}
  2760. % var_test_19.rkt
  2761. \begin{lstlisting}
  2762. (let ([x (+ 42 (- 10))])
  2763. (+ x 10))
  2764. \end{lstlisting}
  2765. \compilesto
  2766. \begin{lstlisting}
  2767. (let ([x (let ([tmp.1 (- 10)])
  2768. (+ 42 tmp.1))])
  2769. (+ x 10))
  2770. \end{lstlisting}
  2771. \end{transformation}
  2772. \fi}
  2773. {\if\edition\pythonEd
  2774. \begin{transformation}
  2775. \begin{lstlisting}
  2776. x = 42 + -10
  2777. print(x + 10)
  2778. \end{lstlisting}
  2779. \compilesto
  2780. \begin{lstlisting}
  2781. tmp_0 = -10
  2782. x = 42 + tmp_0
  2783. tmp_1 = x + 10
  2784. print(tmp_1)
  2785. \end{lstlisting}
  2786. \end{transformation}
  2787. \fi}
  2788. \begin{figure}[tp]
  2789. \centering
  2790. \fbox{
  2791. \begin{minipage}{0.96\textwidth}
  2792. {\if\edition\racketEd
  2793. \[
  2794. \begin{array}{rcl}
  2795. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2796. \Exp &::=& \Atm \MID \READ{} \\
  2797. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2798. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2799. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2800. \end{array}
  2801. \]
  2802. \fi}
  2803. {\if\edition\pythonEd
  2804. \[
  2805. \begin{array}{rcl}
  2806. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2807. \Exp{} &::=& \Atm \MID \READ{} \\
  2808. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2809. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2810. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  2811. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2812. \end{array}
  2813. \]
  2814. \fi}
  2815. \end{minipage}
  2816. }
  2817. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2818. atomic expressions.}
  2819. \label{fig:Lvar-anf-syntax}
  2820. \end{figure}
  2821. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2822. of this pass, the language \LangVarANF{}. The only difference is that
  2823. operator arguments are restricted to be atomic expressions that are
  2824. defined by the \Atm{} non-terminal. In particular, integer constants
  2825. and variables are atomic.
  2826. The atomic expressions are pure (they do not cause side-effects or
  2827. depend on them) whereas complex expressions may have side effects,
  2828. such as \READ{}. A language with this separation between pure versus
  2829. side-effecting expressions is said to be in monadic normal
  2830. form~\citep{Moggi:1991in,Danvy:2003fk} which explains the \textit{mon}
  2831. in \LangVarANF{}. An important invariant of the
  2832. \code{remove\_complex\_operands} pass is that the relative ordering
  2833. among complex expressions is not changed, but the relative ordering
  2834. between atomic expressions and complex expressions can change and
  2835. often does. The reason that these changes are behaviour preserving is
  2836. that the atomic expressions are pure.
  2837. Another well-known form for intermediate languages is the
  2838. \emph{administrative normal form}
  2839. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2840. \index{subject}{administrative normal form} \index{subject}{ANF}
  2841. %
  2842. The \LangVarANF{} language is not quite in ANF because we allow the
  2843. right-hand side of a \code{let} to be a complex expression.
  2844. {\if\edition\racketEd
  2845. We recommend implementing this pass with two mutually recursive
  2846. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2847. \code{rco\_atom} to subexpressions that need to become atomic and to
  2848. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2849. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2850. returns an expression. The \code{rco\_atom} function returns two
  2851. things: an atomic expression and an alist mapping temporary variables to
  2852. complex subexpressions. You can return multiple things from a function
  2853. using Racket's \key{values} form and you can receive multiple things
  2854. from a function call using the \key{define-values} form.
  2855. Also, the
  2856. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2857. form is useful for applying a function to each element of a list, in
  2858. the case where the function returns multiple values.
  2859. \index{subject}{for/lists}
  2860. \fi}
  2861. %
  2862. {\if\edition\pythonEd
  2863. %
  2864. We recommend implementing this pass with an auxiliary method named
  2865. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2866. Boolean that specifies whether the expression needs to become atomic
  2867. or not. The \code{rco\_exp} method should return a pair consisting of
  2868. the new expression and a list of pairs, associating new temporary
  2869. variables with their initializing expressions.
  2870. %
  2871. \fi}
  2872. {\if\edition\racketEd
  2873. Returning to the example program with the expression \code{(+ 42 (-
  2874. 10))}, the subexpression \code{(- 10)} should be processed using the
  2875. \code{rco\_atom} function because it is an argument of the \code{+} and
  2876. therefore needs to become atomic. The output of \code{rco\_atom}
  2877. applied to \code{(- 10)} is as follows.
  2878. \begin{transformation}
  2879. \begin{lstlisting}
  2880. (- 10)
  2881. \end{lstlisting}
  2882. \compilesto
  2883. \begin{lstlisting}
  2884. tmp.1
  2885. ((tmp.1 . (- 10)))
  2886. \end{lstlisting}
  2887. \end{transformation}
  2888. \fi}
  2889. %
  2890. {\if\edition\pythonEd
  2891. %
  2892. Returning to the example program with the expression \code{42 + -10},
  2893. the subexpression \code{-10} should be processed using the
  2894. \code{rco\_exp} function with \code{True} as the second argument
  2895. because \code{-10} is an argument of the \code{+} operator and
  2896. therefore needs to become atomic. The output of \code{rco\_exp}
  2897. applied to \code{-10} is as follows.
  2898. \begin{transformation}
  2899. \begin{lstlisting}
  2900. -10
  2901. \end{lstlisting}
  2902. \compilesto
  2903. \begin{lstlisting}
  2904. tmp_1
  2905. [(tmp_1, -10)]
  2906. \end{lstlisting}
  2907. \end{transformation}
  2908. %
  2909. \fi}
  2910. Take special care of programs such as the following that
  2911. %
  2912. \racket{bind a variable to an atomic expression}
  2913. %
  2914. \python{assign an atomic expression to a variable}.
  2915. %
  2916. You should leave such \racket{variable bindings}\python{assignments}
  2917. unchanged, as shown in the program on the right\\
  2918. %
  2919. {\if\edition\racketEd
  2920. \begin{transformation}
  2921. % var_test_20.rkt
  2922. \begin{lstlisting}
  2923. (let ([a 42])
  2924. (let ([b a])
  2925. b))
  2926. \end{lstlisting}
  2927. \compilesto
  2928. \begin{lstlisting}
  2929. (let ([a 42])
  2930. (let ([b a])
  2931. b))
  2932. \end{lstlisting}
  2933. \end{transformation}
  2934. \fi}
  2935. {\if\edition\pythonEd
  2936. \begin{transformation}
  2937. \begin{lstlisting}
  2938. a = 42
  2939. b = a
  2940. print(b)
  2941. \end{lstlisting}
  2942. \compilesto
  2943. \begin{lstlisting}
  2944. a = 42
  2945. b = a
  2946. print(b)
  2947. \end{lstlisting}
  2948. \end{transformation}
  2949. \fi}
  2950. %
  2951. \noindent A careless implementation might produce the following output with
  2952. unnecessary temporary variables.
  2953. \begin{center}
  2954. \begin{minipage}{0.4\textwidth}
  2955. {\if\edition\racketEd
  2956. \begin{lstlisting}
  2957. (let ([tmp.1 42])
  2958. (let ([a tmp.1])
  2959. (let ([tmp.2 a])
  2960. (let ([b tmp.2])
  2961. b))))
  2962. \end{lstlisting}
  2963. \fi}
  2964. {\if\edition\pythonEd
  2965. \begin{lstlisting}
  2966. tmp_1 = 42
  2967. a = tmp_1
  2968. tmp_2 = a
  2969. b = tmp_2
  2970. print(b)
  2971. \end{lstlisting}
  2972. \fi}
  2973. \end{minipage}
  2974. \end{center}
  2975. \begin{exercise}
  2976. \normalfont
  2977. {\if\edition\racketEd
  2978. Implement the \code{remove\_complex\_operands} function in
  2979. \code{compiler.rkt}.
  2980. %
  2981. Create three new \LangVar{} programs that exercise the interesting
  2982. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  2983. regarding file names described in Exercise~\ref{ex:Lvar}.
  2984. %
  2985. In the \code{run-tests.rkt} script, add the following entry to the
  2986. list of \code{passes} and then run the script to test your compiler.
  2987. \begin{lstlisting}
  2988. (list "remove-complex" remove-complex-opera* interp_Lvar type-check-Lvar)
  2989. \end{lstlisting}
  2990. While debugging your compiler, it is often useful to see the
  2991. intermediate programs that are output from each pass. To print the
  2992. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  2993. \code{interp-tests} in \code{run-tests.rkt}.
  2994. \fi}
  2995. %
  2996. {\if\edition\pythonEd
  2997. Implement the \code{remove\_complex\_operands} pass in
  2998. \code{compiler.py}, creating auxiliary functions for each
  2999. non-terminal in the grammar, i.e., \code{rco\_exp}
  3000. and \code{rco\_stmt}.
  3001. \fi}
  3002. \end{exercise}
  3003. {\if\edition\pythonEd
  3004. \begin{exercise}
  3005. \normalfont % I don't like the italics for exercises. -Jeremy
  3006. \label{ex:Lvar}
  3007. Create five \LangVar{} programs that exercise the most interesting
  3008. parts of the \code{remove\_complex\_operands} pass. The five programs
  3009. should be placed in the subdirectory named \key{tests} and the file
  3010. names should start with \code{var\_test\_} followed by a unique
  3011. integer and end with the file extension \key{.py}.
  3012. %% The \key{run-tests.rkt} script in the support code checks whether the
  3013. %% output programs produce the same result as the input programs. The
  3014. %% script uses the \key{interp-tests} function
  3015. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3016. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3017. %% parameter of \key{interp-tests} is a list that should have one entry
  3018. %% for each pass in your compiler. For now, define \code{passes} to
  3019. %% contain just one entry for \code{uniquify} as shown below.
  3020. %% \begin{lstlisting}
  3021. %% (define passes
  3022. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3023. %% \end{lstlisting}
  3024. Run the \key{run-tests.py} script in the support code to check
  3025. whether the output programs produce the same result as the input
  3026. programs.
  3027. \end{exercise}
  3028. \fi}
  3029. {\if\edition\racketEd
  3030. \section{Explicate Control}
  3031. \label{sec:explicate-control-Lvar}
  3032. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3033. programs that make the order of execution explicit in their
  3034. syntax. For now this amounts to flattening \key{let} constructs into a
  3035. sequence of assignment statements. For example, consider the following
  3036. \LangVar{} program.\\
  3037. % var_test_11.rkt
  3038. \begin{minipage}{0.96\textwidth}
  3039. \begin{lstlisting}
  3040. (let ([y (let ([x 20])
  3041. (+ x (let ([x 22]) x)))])
  3042. y)
  3043. \end{lstlisting}
  3044. \end{minipage}\\
  3045. %
  3046. The output of the previous pass and of \code{explicate\_control} is
  3047. shown below. Recall that the right-hand-side of a \key{let} executes
  3048. before its body, so the order of evaluation for this program is to
  3049. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  3050. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  3051. output of \code{explicate\_control} makes this ordering explicit.
  3052. \begin{transformation}
  3053. \begin{lstlisting}
  3054. (let ([y (let ([x.1 20])
  3055. (let ([x.2 22])
  3056. (+ x.1 x.2)))])
  3057. y)
  3058. \end{lstlisting}
  3059. \compilesto
  3060. \begin{lstlisting}[language=C]
  3061. start:
  3062. x.1 = 20;
  3063. x.2 = 22;
  3064. y = (+ x.1 x.2);
  3065. return y;
  3066. \end{lstlisting}
  3067. \end{transformation}
  3068. \begin{figure}[tbp]
  3069. \begin{lstlisting}
  3070. (define (explicate_tail e)
  3071. (match e
  3072. [(Var x) ___]
  3073. [(Int n) (Return (Int n))]
  3074. [(Let x rhs body) ___]
  3075. [(Prim op es) ___]
  3076. [else (error "explicate_tail unhandled case" e)]))
  3077. (define (explicate_assign e x cont)
  3078. (match e
  3079. [(Var x) ___]
  3080. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3081. [(Let y rhs body) ___]
  3082. [(Prim op es) ___]
  3083. [else (error "explicate_assign unhandled case" e)]))
  3084. (define (explicate_control p)
  3085. (match p
  3086. [(Program info body) ___]))
  3087. \end{lstlisting}
  3088. \caption{Skeleton for the \code{explicate\_control} pass.}
  3089. \label{fig:explicate-control-Lvar}
  3090. \end{figure}
  3091. The organization of this pass depends on the notion of tail position
  3092. that we have alluded to earlier.
  3093. \begin{definition}
  3094. The following rules define when an expression is in \textbf{\emph{tail
  3095. position}}\index{subject}{tail position} for the language \LangVar{}.
  3096. \begin{enumerate}
  3097. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3098. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3099. \end{enumerate}
  3100. \end{definition}
  3101. We recommend implementing \code{explicate\_control} using two mutually
  3102. recursive functions, \code{explicate\_tail} and
  3103. \code{explicate\_assign}, as suggested in the skeleton code in
  3104. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3105. function should be applied to expressions in tail position whereas the
  3106. \code{explicate\_assign} should be applied to expressions that occur on
  3107. the right-hand-side of a \key{let}.
  3108. %
  3109. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3110. input and produces a \Tail{} in \LangCVar{} (see
  3111. Figure~\ref{fig:c0-syntax}).
  3112. %
  3113. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3114. the variable that it is to be assigned to, and a \Tail{} in
  3115. \LangCVar{} for the code that comes after the assignment. The
  3116. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3117. The \code{explicate\_assign} function is in accumulator-passing style:
  3118. the \code{cont} parameter is used for accumulating the output. This
  3119. accumulator-passing style plays an important role in how we generate
  3120. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  3121. \begin{exercise}\normalfont
  3122. %
  3123. Implement the \code{explicate\_control} function in
  3124. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3125. exercise the code in \code{explicate\_control}.
  3126. %
  3127. In the \code{run-tests.rkt} script, add the following entry to the
  3128. list of \code{passes} and then run the script to test your compiler.
  3129. \begin{lstlisting}
  3130. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3131. \end{lstlisting}
  3132. \end{exercise}
  3133. \fi}
  3134. \section{Select Instructions}
  3135. \label{sec:select-Lvar}
  3136. \index{subject}{instruction selection}
  3137. In the \code{select\_instructions} pass we begin the work of
  3138. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3139. language of this pass is a variant of x86 that still uses variables,
  3140. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3141. non-terminal of the \LangXInt{} abstract syntax
  3142. (Figure~\ref{fig:x86-int-ast}).
  3143. \racket{We recommend implementing the
  3144. \code{select\_instructions} with three auxiliary functions, one for
  3145. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3146. $\Tail$.}
  3147. \python{We recommend implementing an auxiliary function
  3148. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  3149. \racket{
  3150. The cases for $\Atm$ are straightforward; variables stay
  3151. the same and integer constants change to immediates:
  3152. $\INT{n}$ changes to $\IMM{n}$.}
  3153. We consider the cases for the $\Stmt$ non-terminal, starting with
  3154. arithmetic operations. For example, consider the addition operation
  3155. below, on the left side. There is an \key{addq} instruction in x86,
  3156. but it performs an in-place update. So we could move $\Arg_1$
  3157. into the left-hand side \itm{var} and then add $\Arg_2$ to
  3158. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  3159. $\Atm_1$ and $\Atm_2$ respectively.
  3160. \begin{transformation}
  3161. {\if\edition\racketEd
  3162. \begin{lstlisting}
  3163. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3164. \end{lstlisting}
  3165. \fi}
  3166. {\if\edition\pythonEd
  3167. \begin{lstlisting}
  3168. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3169. \end{lstlisting}
  3170. \fi}
  3171. \compilesto
  3172. \begin{lstlisting}
  3173. movq |$\Arg_1$|, |$\itm{var}$|
  3174. addq |$\Arg_2$|, |$\itm{var}$|
  3175. \end{lstlisting}
  3176. \end{transformation}
  3177. There are also cases that require special care to avoid generating
  3178. needlessly complicated code. For example, if one of the arguments of
  3179. the addition is the same variable as the left-hand side of the
  3180. assignment, as shown below, then there is no need for the extra move
  3181. instruction. The assignment statement can be translated into a single
  3182. \key{addq} instruction as follows.
  3183. \begin{transformation}
  3184. {\if\edition\racketEd
  3185. \begin{lstlisting}
  3186. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3187. \end{lstlisting}
  3188. \fi}
  3189. {\if\edition\pythonEd
  3190. \begin{lstlisting}
  3191. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3192. \end{lstlisting}
  3193. \fi}
  3194. \compilesto
  3195. \begin{lstlisting}
  3196. addq |$\Arg_1$|, |$\itm{var}$|
  3197. \end{lstlisting}
  3198. \end{transformation}
  3199. The \READOP{} operation does not have a direct counterpart in x86
  3200. assembly, so we provide this functionality with the function
  3201. \code{read\_int} in the file \code{runtime.c}, written in
  3202. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3203. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3204. system}, or simply the \emph{runtime} for short. When compiling your
  3205. generated x86 assembly code, you need to compile \code{runtime.c} to
  3206. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3207. \code{-c}) and link it into the executable. For our purposes of code
  3208. generation, all you need to do is translate an assignment of
  3209. \READOP{} into a call to the \code{read\_int} function followed by a
  3210. move from \code{rax} to the left-hand-side variable. (Recall that the
  3211. return value of a function goes into \code{rax}.)
  3212. \begin{transformation}
  3213. {\if\edition\racketEd
  3214. \begin{lstlisting}
  3215. |$\itm{var}$| = (read);
  3216. \end{lstlisting}
  3217. \fi}
  3218. {\if\edition\pythonEd
  3219. \begin{lstlisting}
  3220. |$\itm{var}$| = input_int();
  3221. \end{lstlisting}
  3222. \fi}
  3223. \compilesto
  3224. \begin{lstlisting}
  3225. callq read_int
  3226. movq %rax, |$\itm{var}$|
  3227. \end{lstlisting}
  3228. \end{transformation}
  3229. {\if\edition\pythonEd
  3230. %
  3231. Similarly, we translate the \code{print} operation, shown below, into
  3232. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3233. In x86, the first six arguments to functions are passed in registers,
  3234. with the first argument passed in register \code{rdi}. So we move the
  3235. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3236. \code{callq} instruction.
  3237. \begin{transformation}
  3238. \begin{lstlisting}
  3239. print(|$\Atm$|)
  3240. \end{lstlisting}
  3241. \compilesto
  3242. \begin{lstlisting}
  3243. movq |$\Arg$|, %rdi
  3244. callq print_int
  3245. \end{lstlisting}
  3246. \end{transformation}
  3247. %
  3248. \fi}
  3249. {\if\edition\racketEd
  3250. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3251. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3252. assignment to the \key{rax} register followed by a jump to the
  3253. conclusion of the program (so the conclusion needs to be labeled).
  3254. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3255. recursively and then append the resulting instructions.
  3256. \fi}
  3257. \begin{exercise}
  3258. \normalfont
  3259. {\if\edition\racketEd
  3260. Implement the \code{select\_instructions} pass in
  3261. \code{compiler.rkt}. Create three new example programs that are
  3262. designed to exercise all of the interesting cases in this pass.
  3263. %
  3264. In the \code{run-tests.rkt} script, add the following entry to the
  3265. list of \code{passes} and then run the script to test your compiler.
  3266. \begin{lstlisting}
  3267. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3268. \end{lstlisting}
  3269. \fi}
  3270. {\if\edition\pythonEd
  3271. Implement the \key{select\_instructions} pass in
  3272. \code{compiler.py}. Create three new example programs that are
  3273. designed to exercise all of the interesting cases in this pass.
  3274. Run the \code{run-tests.py} script to to check
  3275. whether the output programs produce the same result as the input
  3276. programs.
  3277. \fi}
  3278. \end{exercise}
  3279. \section{Assign Homes}
  3280. \label{sec:assign-Lvar}
  3281. The \key{assign\_homes} pass compiles \LangXVar{} programs to
  3282. \LangXVar{} programs that no longer use program variables.
  3283. Thus, the \key{assign-homes} pass is responsible for placing all of
  3284. the program variables in registers or on the stack. For runtime
  3285. efficiency, it is better to place variables in registers, but as there
  3286. are only 16 registers, some programs must necessarily resort to
  3287. placing some variables on the stack. In this chapter we focus on the
  3288. mechanics of placing variables on the stack. We study an algorithm for
  3289. placing variables in registers in
  3290. Chapter~\ref{ch:register-allocation-Lvar}.
  3291. Consider again the following \LangVar{} program from
  3292. Section~\ref{sec:remove-complex-opera-Lvar}.
  3293. % var_test_20.rkt
  3294. {\if\edition\racketEd
  3295. \begin{lstlisting}
  3296. (let ([a 42])
  3297. (let ([b a])
  3298. b))
  3299. \end{lstlisting}
  3300. \fi}
  3301. {\if\edition\pythonEd
  3302. \begin{lstlisting}
  3303. a = 42
  3304. b = a
  3305. print(b)
  3306. \end{lstlisting}
  3307. \fi}
  3308. %
  3309. The output of \code{select\_instructions} is shown below, on the left,
  3310. and the output of \code{assign\_homes} is on the right. In this
  3311. example, we assign variable \code{a} to stack location
  3312. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3313. \begin{transformation}
  3314. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3315. movq $42, a
  3316. movq a, b
  3317. movq b, %rax
  3318. \end{lstlisting}
  3319. \compilesto
  3320. %stack-space: 16
  3321. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3322. movq $42, -8(%rbp)
  3323. movq -8(%rbp), -16(%rbp)
  3324. movq -16(%rbp), %rax
  3325. \end{lstlisting}
  3326. \end{transformation}
  3327. \racket{The \code{locals-types} entry in the $\itm{info}$ of the
  3328. \code{X86Program} node is an alist mapping all the variables in the
  3329. program to their types (for now just \code{Integer}). The
  3330. \code{assign\_homes} pass should replace all uses of those variables
  3331. with stack locations. As an aside, the \code{locals-types} entry is
  3332. computed by \code{type-check-Cvar} in the support code, which
  3333. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3334. which should be propagated to the \code{X86Program} node.}
  3335. %
  3336. \python{The \code{assign\_homes} pass should replace all uses of
  3337. variables with stack locations.}
  3338. %
  3339. In the process of assigning variables to stack locations, it is
  3340. convenient for you to compute and store the size of the frame (in
  3341. bytes) in%
  3342. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space}}
  3343. %
  3344. \python{the field \code{stack\_space} of the \key{X86Program} node},
  3345. which is needed later to generate the conclusion of the \code{main}
  3346. procedure. The x86-64 standard requires the frame size to be a
  3347. multiple of 16 bytes.\index{subject}{frame}
  3348. % TODO: store the number of variables instead? -Jeremy
  3349. \begin{exercise}\normalfont
  3350. Implement the \key{assign\_homes} pass in
  3351. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3352. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3353. grammar. We recommend that the auxiliary functions take an extra
  3354. parameter that maps variable names to homes (stack locations for now).
  3355. %
  3356. {\if\edition\racketEd
  3357. In the \code{run-tests.rkt} script, add the following entry to the
  3358. list of \code{passes} and then run the script to test your compiler.
  3359. \begin{lstlisting}
  3360. (list "assign homes" assign-homes interp_x86-0)
  3361. \end{lstlisting}
  3362. \fi}
  3363. {\if\edition\pythonEd
  3364. Run the \code{run-tests.py} script to to check
  3365. whether the output programs produce the same result as the input
  3366. programs.
  3367. \fi}
  3368. \end{exercise}
  3369. \section{Patch Instructions}
  3370. \label{sec:patch-s0}
  3371. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3372. \LangXInt{} by making sure that each instruction adheres to the
  3373. restriction that at most one argument of an instruction may be a
  3374. memory reference.
  3375. We return to the following example.\\
  3376. \begin{minipage}{0.5\textwidth}
  3377. % var_test_20.rkt
  3378. {\if\edition\racketEd
  3379. \begin{lstlisting}
  3380. (let ([a 42])
  3381. (let ([b a])
  3382. b))
  3383. \end{lstlisting}
  3384. \fi}
  3385. {\if\edition\pythonEd
  3386. \begin{lstlisting}
  3387. a = 42
  3388. b = a
  3389. print(b)
  3390. \end{lstlisting}
  3391. \fi}
  3392. \end{minipage}\\
  3393. The \key{assign\_homes} pass produces the following translation. \\
  3394. \begin{minipage}{0.5\textwidth}
  3395. {\if\edition\racketEd
  3396. \begin{lstlisting}
  3397. movq $42, -8(%rbp)
  3398. movq -8(%rbp), -16(%rbp)
  3399. movq -16(%rbp), %rax
  3400. \end{lstlisting}
  3401. \fi}
  3402. {\if\edition\pythonEd
  3403. \begin{lstlisting}
  3404. movq 42, -8(%rbp)
  3405. movq -8(%rbp), -16(%rbp)
  3406. movq -16(%rbp), %rdi
  3407. callq print_int
  3408. \end{lstlisting}
  3409. \fi}
  3410. \end{minipage}\\
  3411. The second \key{movq} instruction is problematic because both
  3412. arguments are stack locations. We suggest fixing this problem by
  3413. moving from the source location to the register \key{rax} and then
  3414. from \key{rax} to the destination location, as follows.
  3415. \begin{lstlisting}
  3416. movq -8(%rbp), %rax
  3417. movq %rax, -16(%rbp)
  3418. \end{lstlisting}
  3419. \begin{exercise}
  3420. \normalfont Implement the \key{patch\_instructions} pass in
  3421. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3422. Create three new example programs that are
  3423. designed to exercise all of the interesting cases in this pass.
  3424. %
  3425. {\if\edition\racketEd
  3426. In the \code{run-tests.rkt} script, add the following entry to the
  3427. list of \code{passes} and then run the script to test your compiler.
  3428. \begin{lstlisting}
  3429. (list "patch instructions" patch_instructions interp_x86-0)
  3430. \end{lstlisting}
  3431. \fi}
  3432. {\if\edition\pythonEd
  3433. Run the \code{run-tests.py} script to to check
  3434. whether the output programs produce the same result as the input
  3435. programs.
  3436. \fi}
  3437. \end{exercise}
  3438. \section{Generate Prelude and Conclusion}
  3439. \label{sec:print-x86}
  3440. \index{subject}{prelude}\index{subject}{conclusion}
  3441. The last step of the compiler from \LangVar{} to x86 is to generate
  3442. the \code{main} function with a prelude and conclusion wrapped around
  3443. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3444. discussed in Section~\ref{sec:x86}.
  3445. When running on Mac OS X, your compiler should prefix an underscore to
  3446. all labels, e.g., changing \key{main} to \key{\_main}.
  3447. %
  3448. \racket{The Racket call \code{(system-type 'os)} is useful for
  3449. determining which operating system the compiler is running on. It
  3450. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3451. %
  3452. \python{The Python \code{platform} library includes a \code{system()}
  3453. function that returns \code{'Linux'}, \code{'Windows'}, or
  3454. \code{'Darwin'} (for Mac).}
  3455. \begin{exercise}\normalfont
  3456. %
  3457. Implement the \key{prelude\_and\_conclusion} pass in
  3458. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3459. %
  3460. {\if\edition\racketEd
  3461. In the \code{run-tests.rkt} script, add the following entry to the
  3462. list of \code{passes} and then run the script to test your compiler.
  3463. \begin{lstlisting}
  3464. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3465. \end{lstlisting}
  3466. %
  3467. Uncomment the call to the \key{compiler-tests} function
  3468. (Appendix~\ref{appendix:utilities}), which tests your complete
  3469. compiler by executing the generated x86 code. It translates the x86
  3470. AST that you produce into a string by invoking the \code{print-x86}
  3471. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3472. the provided \key{runtime.c} file to \key{runtime.o} using
  3473. \key{gcc}. Run the script to test your compiler.
  3474. %
  3475. \fi}
  3476. {\if\edition\pythonEd
  3477. %
  3478. Run the \code{run-tests.py} script to to check whether the output
  3479. programs produce the same result as the input programs. That script
  3480. translates the x86 AST that you produce into a string by invoking the
  3481. \code{repr} method that is implemented by the x86 AST classes in
  3482. \code{x86\_ast.py}.
  3483. %
  3484. \fi}
  3485. \end{exercise}
  3486. \section{Challenge: Partial Evaluator for \LangVar{}}
  3487. \label{sec:pe-Lvar}
  3488. \index{subject}{partial evaluation}
  3489. This section describes two optional challenge exercises that involve
  3490. adapting and improving the partial evaluator for \LangInt{} that was
  3491. introduced in Section~\ref{sec:partial-evaluation}.
  3492. \begin{exercise}\label{ex:pe-Lvar}
  3493. \normalfont
  3494. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3495. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3496. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3497. %
  3498. \racket{\key{let} binding}\python{assignment}
  3499. %
  3500. to the \LangInt{} language, so you will need to add cases for them in
  3501. the \code{pe\_exp}
  3502. %
  3503. \racket{function}
  3504. %
  3505. \python{and \code{pe\_stmt} functions}.
  3506. %
  3507. Once complete, add the partial evaluation pass to the front of your
  3508. compiler and make sure that your compiler still passes all of the
  3509. tests.
  3510. \end{exercise}
  3511. \begin{exercise}
  3512. \normalfont
  3513. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3514. \code{pe\_add} auxiliary functions with functions that know more about
  3515. arithmetic. For example, your partial evaluator should translate
  3516. {\if\edition\racketEd
  3517. \[
  3518. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3519. \code{(+ 2 (read))}
  3520. \]
  3521. \fi}
  3522. {\if\edition\pythonEd
  3523. \[
  3524. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3525. \code{2 + input\_int()}
  3526. \]
  3527. \fi}
  3528. To accomplish this, the \code{pe\_exp} function should produce output
  3529. in the form of the $\itm{residual}$ non-terminal of the following
  3530. grammar. The idea is that when processing an addition expression, we
  3531. can always produce either 1) an integer constant, 2) an addition
  3532. expression with an integer constant on the left-hand side but not the
  3533. right-hand side, or 3) or an addition expression in which neither
  3534. subexpression is a constant.
  3535. {\if\edition\racketEd
  3536. \[
  3537. \begin{array}{lcl}
  3538. \itm{inert} &::=& \Var
  3539. \MID \LP\key{read}\RP
  3540. \MID \LP\key{-} ~\Var\RP
  3541. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3542. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3543. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3544. \itm{residual} &::=& \Int
  3545. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3546. \MID \itm{inert}
  3547. \end{array}
  3548. \]
  3549. \fi}
  3550. {\if\edition\pythonEd
  3551. \[
  3552. \begin{array}{lcl}
  3553. \itm{inert} &::=& \Var
  3554. \MID \key{input\_int}\LP\RP
  3555. \MID \key{-} \Var
  3556. \MID \key{-} \key{input\_int}\LP\RP
  3557. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3558. \itm{residual} &::=& \Int
  3559. \MID \Int ~ \key{+} ~ \itm{inert}
  3560. \MID \itm{inert}
  3561. \end{array}
  3562. \]
  3563. \fi}
  3564. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3565. inputs are $\itm{residual}$ expressions and they should return
  3566. $\itm{residual}$ expressions. Once the improvements are complete,
  3567. make sure that your compiler still passes all of the tests. After
  3568. all, fast code is useless if it produces incorrect results!
  3569. \end{exercise}
  3570. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3571. \chapter{Register Allocation}
  3572. \label{ch:register-allocation-Lvar}
  3573. \index{subject}{register allocation}
  3574. In Chapter~\ref{ch:Lvar} we learned how to store variables on the
  3575. stack. In this chapter we learn how to improve the performance of the
  3576. generated code by assigning some variables to registers. The CPU can
  3577. access a register in a single cycle, whereas accessing the stack can
  3578. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3579. serves as a running example. The source program is on the left and the
  3580. output of instruction selection is on the right. The program is almost
  3581. in the x86 assembly language but it still uses variables.
  3582. \begin{figure}
  3583. \begin{minipage}{0.45\textwidth}
  3584. Example \LangVar{} program:
  3585. % var_test_28.rkt
  3586. {\if\edition\racketEd
  3587. \begin{lstlisting}
  3588. (let ([v 1])
  3589. (let ([w 42])
  3590. (let ([x (+ v 7)])
  3591. (let ([y x])
  3592. (let ([z (+ x w)])
  3593. (+ z (- y)))))))
  3594. \end{lstlisting}
  3595. \fi}
  3596. {\if\edition\pythonEd
  3597. \begin{lstlisting}
  3598. v = 1
  3599. w = 42
  3600. x = v + 7
  3601. y = x
  3602. z = x + w
  3603. print(z + (- y))
  3604. \end{lstlisting}
  3605. \fi}
  3606. \end{minipage}
  3607. \begin{minipage}{0.45\textwidth}
  3608. After instruction selection:
  3609. {\if\edition\racketEd
  3610. \begin{lstlisting}
  3611. locals-types:
  3612. x : Integer, y : Integer,
  3613. z : Integer, t : Integer,
  3614. v : Integer, w : Integer
  3615. start:
  3616. movq $1, v
  3617. movq $42, w
  3618. movq v, x
  3619. addq $7, x
  3620. movq x, y
  3621. movq x, z
  3622. addq w, z
  3623. movq y, t
  3624. negq t
  3625. movq z, %rax
  3626. addq t, %rax
  3627. jmp conclusion
  3628. \end{lstlisting}
  3629. \fi}
  3630. {\if\edition\pythonEd
  3631. \begin{lstlisting}
  3632. movq $1, v
  3633. movq $42, w
  3634. movq v, x
  3635. addq $7, x
  3636. movq x, y
  3637. movq x, z
  3638. addq w, z
  3639. movq y, tmp_0
  3640. negq tmp_0
  3641. movq z, tmp_1
  3642. addq tmp_0, tmp_1
  3643. movq tmp_1, %rdi
  3644. callq print_int
  3645. \end{lstlisting}
  3646. \fi}
  3647. \end{minipage}
  3648. \caption{A running example for register allocation.}
  3649. \label{fig:reg-eg}
  3650. \end{figure}
  3651. The goal of register allocation is to fit as many variables into
  3652. registers as possible. Some programs have more variables than
  3653. registers so we cannot always map each variable to a different
  3654. register. Fortunately, it is common for different variables to be
  3655. needed during different periods of time during program execution, and
  3656. in such cases several variables can be mapped to the same register.
  3657. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3658. After the variable \code{x} is moved to \code{z} it is no longer
  3659. needed. Variable \code{z}, on the other hand, is used only after this
  3660. point, so \code{x} and \code{z} could share the same register. The
  3661. topic of Section~\ref{sec:liveness-analysis-Lvar} is how to compute
  3662. where a variable is needed. Once we have that information, we compute
  3663. which variables are needed at the same time, i.e., which ones
  3664. \emph{interfere} with each other, and represent this relation as an
  3665. undirected graph whose vertices are variables and edges indicate when
  3666. two variables interfere (Section~\ref{sec:build-interference}). We
  3667. then model register allocation as a graph coloring problem
  3668. (Section~\ref{sec:graph-coloring}).
  3669. If we run out of registers despite these efforts, we place the
  3670. remaining variables on the stack, similar to what we did in
  3671. Chapter~\ref{ch:Lvar}. It is common to use the verb \emph{spill} for
  3672. assigning a variable to a stack location. The decision to spill a
  3673. variable is handled as part of the graph coloring process.
  3674. We make the simplifying assumption that each variable is assigned to
  3675. one location (a register or stack address). A more sophisticated
  3676. approach is to assign a variable to one or more locations in different
  3677. regions of the program. For example, if a variable is used many times
  3678. in short sequence and then only used again after many other
  3679. instructions, it could be more efficient to assign the variable to a
  3680. register during the initial sequence and then move it to the stack for
  3681. the rest of its lifetime. We refer the interested reader to
  3682. \citet{Cooper:2011aa} Chapter 13 for more information about that
  3683. approach.
  3684. % discuss prioritizing variables based on how much they are used.
  3685. \section{Registers and Calling Conventions}
  3686. \label{sec:calling-conventions}
  3687. \index{subject}{calling conventions}
  3688. As we perform register allocation, we need to be aware of the
  3689. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  3690. functions calls are performed in x86.
  3691. %
  3692. Even though \LangVar{} does not include programmer-defined functions,
  3693. our generated code includes a \code{main} function that is called by
  3694. the operating system and our generated code contains calls to the
  3695. \code{read\_int} function.
  3696. Function calls require coordination between two pieces of code that
  3697. may be written by different programmers or generated by different
  3698. compilers. Here we follow the System V calling conventions that are
  3699. used by the GNU C compiler on Linux and
  3700. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3701. %
  3702. The calling conventions include rules about how functions share the
  3703. use of registers. In particular, the caller is responsible for freeing
  3704. up some registers prior to the function call for use by the callee.
  3705. These are called the \emph{caller-saved registers}
  3706. \index{subject}{caller-saved registers}
  3707. and they are
  3708. \begin{lstlisting}
  3709. rax rcx rdx rsi rdi r8 r9 r10 r11
  3710. \end{lstlisting}
  3711. On the other hand, the callee is responsible for preserving the values
  3712. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3713. which are
  3714. \begin{lstlisting}
  3715. rsp rbp rbx r12 r13 r14 r15
  3716. \end{lstlisting}
  3717. We can think about this caller/callee convention from two points of
  3718. view, the caller view and the callee view:
  3719. \begin{itemize}
  3720. \item The caller should assume that all the caller-saved registers get
  3721. overwritten with arbitrary values by the callee. On the other hand,
  3722. the caller can safely assume that all the callee-saved registers
  3723. contain the same values after the call that they did before the
  3724. call.
  3725. \item The callee can freely use any of the caller-saved registers.
  3726. However, if the callee wants to use a callee-saved register, the
  3727. callee must arrange to put the original value back in the register
  3728. prior to returning to the caller. This can be accomplished by saving
  3729. the value to the stack in the prelude of the function and restoring
  3730. the value in the conclusion of the function.
  3731. \end{itemize}
  3732. In x86, registers are also used for passing arguments to a function
  3733. and for the return value. In particular, the first six arguments to a
  3734. function are passed in the following six registers, in this order.
  3735. \begin{lstlisting}
  3736. rdi rsi rdx rcx r8 r9
  3737. \end{lstlisting}
  3738. If there are more than six arguments, then the convention is to use
  3739. space on the frame of the caller for the rest of the
  3740. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  3741. need more than six arguments.
  3742. %
  3743. \racket{For now, the only function we care about is \code{read\_int}
  3744. and it takes zero arguments.}
  3745. %
  3746. \python{For now, the only functions we care about are \code{read\_int}
  3747. and \code{print\_int}, which take zero and one argument, respectively.}
  3748. %
  3749. The register \code{rax} is used for the return value of a function.
  3750. The next question is how these calling conventions impact register
  3751. allocation. Consider the \LangVar{} program in
  3752. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3753. example from the caller point of view and then from the callee point
  3754. of view.
  3755. The program makes two calls to \READOP{}. Also, the variable \code{x}
  3756. is in use during the second call to \READOP{}, so we need to make sure
  3757. that the value in \code{x} does not get accidentally wiped out by the
  3758. call to \READOP{}. One obvious approach is to save all the values in
  3759. caller-saved registers to the stack prior to each function call, and
  3760. restore them after each call. That way, if the register allocator
  3761. chooses to assign \code{x} to a caller-saved register, its value will
  3762. be preserved across the call to \READOP{}. However, saving and
  3763. restoring to the stack is relatively slow. If \code{x} is not used
  3764. many times, it may be better to assign \code{x} to a stack location in
  3765. the first place. Or better yet, if we can arrange for \code{x} to be
  3766. placed in a callee-saved register, then it won't need to be saved and
  3767. restored during function calls.
  3768. The approach that we recommend for variables that are in use during a
  3769. function call is to either assign them to callee-saved registers or to
  3770. spill them to the stack. On the other hand, for variables that are not
  3771. in use during a function call, we try the following alternatives in
  3772. order 1) look for an available caller-saved register (to leave room
  3773. for other variables in the callee-saved register), 2) look for a
  3774. callee-saved register, and 3) spill the variable to the stack.
  3775. It is straightforward to implement this approach in a graph coloring
  3776. register allocator. First, we know which variables are in use during
  3777. every function call because we compute that information for every
  3778. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3779. we build the interference graph
  3780. (Section~\ref{sec:build-interference}), we can place an edge between
  3781. each of these call-live variables and the caller-saved registers in
  3782. the interference graph. This will prevent the graph coloring algorithm
  3783. from assigning them to caller-saved registers.
  3784. Returning to the example in
  3785. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3786. generated x86 code on the right-hand side. Notice that variable
  3787. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3788. is already in a safe place during the second call to
  3789. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3790. \code{rcx}, a caller-saved register, because \code{y} is not in the
  3791. live-after set of a \code{callq} instruction.
  3792. Next we analyze the example from the callee point of view, focusing on
  3793. the prelude and conclusion of the \code{main} function. As usual the
  3794. prelude begins with saving the \code{rbp} register to the stack and
  3795. setting the \code{rbp} to the current stack pointer. We now know why
  3796. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3797. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3798. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3799. (\code{x}). The other callee-saved registers are not saved in the
  3800. prelude because they are not used. The prelude subtracts 8 bytes from
  3801. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3802. conclusion, we see that \code{rbx} is restored from the stack with a
  3803. \code{popq} instruction.
  3804. \index{subject}{prelude}\index{subject}{conclusion}
  3805. \begin{figure}[tp]
  3806. \begin{minipage}{0.45\textwidth}
  3807. Example \LangVar{} program:
  3808. %var_test_14.rkt
  3809. {\if\edition\racketEd
  3810. \begin{lstlisting}
  3811. (let ([x (read)])
  3812. (let ([y (read)])
  3813. (+ (+ x y) 42)))
  3814. \end{lstlisting}
  3815. \fi}
  3816. {\if\edition\pythonEd
  3817. \begin{lstlisting}
  3818. x = input_int()
  3819. y = input_int()
  3820. print((x + y) + 42)
  3821. \end{lstlisting}
  3822. \fi}
  3823. \end{minipage}
  3824. \begin{minipage}{0.45\textwidth}
  3825. Generated x86 assembly:
  3826. {\if\edition\racketEd
  3827. \begin{lstlisting}
  3828. start:
  3829. callq read_int
  3830. movq %rax, %rbx
  3831. callq read_int
  3832. movq %rax, %rcx
  3833. addq %rcx, %rbx
  3834. movq %rbx, %rax
  3835. addq $42, %rax
  3836. jmp _conclusion
  3837. .globl main
  3838. main:
  3839. pushq %rbp
  3840. movq %rsp, %rbp
  3841. pushq %rbx
  3842. subq $8, %rsp
  3843. jmp start
  3844. conclusion:
  3845. addq $8, %rsp
  3846. popq %rbx
  3847. popq %rbp
  3848. retq
  3849. \end{lstlisting}
  3850. \fi}
  3851. {\if\edition\pythonEd
  3852. \begin{lstlisting}
  3853. .globl main
  3854. main:
  3855. pushq %rbp
  3856. movq %rsp, %rbp
  3857. pushq %rbx
  3858. subq $8, %rsp
  3859. callq read_int
  3860. movq %rax, %rbx
  3861. callq read_int
  3862. movq %rax, %rcx
  3863. movq %rbx, %rdx
  3864. addq %rcx, %rdx
  3865. movq %rdx, %rcx
  3866. addq $42, %rcx
  3867. movq %rcx, %rdi
  3868. callq print_int
  3869. addq $8, %rsp
  3870. popq %rbx
  3871. popq %rbp
  3872. retq
  3873. \end{lstlisting}
  3874. \fi}
  3875. \end{minipage}
  3876. \caption{An example with function calls.}
  3877. \label{fig:example-calling-conventions}
  3878. \end{figure}
  3879. %\clearpage
  3880. \section{Liveness Analysis}
  3881. \label{sec:liveness-analysis-Lvar}
  3882. \index{subject}{liveness analysis}
  3883. The \code{uncover\_live} \racket{pass}\python{function}
  3884. performs \emph{liveness analysis}, that
  3885. is, it discovers which variables are in-use in different regions of a
  3886. program.
  3887. %
  3888. A variable or register is \emph{live} at a program point if its
  3889. current value is used at some later point in the program. We refer to
  3890. variables, stack locations, and registers collectively as
  3891. \emph{locations}.
  3892. %
  3893. Consider the following code fragment in which there are two writes to
  3894. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3895. \begin{center}
  3896. \begin{minipage}{0.96\textwidth}
  3897. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3898. movq $5, a
  3899. movq $30, b
  3900. movq a, c
  3901. movq $10, b
  3902. addq b, c
  3903. \end{lstlisting}
  3904. \end{minipage}
  3905. \end{center}
  3906. The answer is no because \code{a} is live from line 1 to 3 and
  3907. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3908. line 2 is never used because it is overwritten (line 4) before the
  3909. next read (line 5).
  3910. The live locations can be computed by traversing the instruction
  3911. sequence back to front (i.e., backwards in execution order). Let
  3912. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3913. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3914. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3915. locations before instruction $I_k$.
  3916. \racket{We recommend representing these
  3917. sets with the Racket \code{set} data structure described in
  3918. Figure~\ref{fig:set}.}
  3919. \python{We recommend representing these sets with the Python
  3920. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  3921. data structure.}
  3922. {\if\edition\racketEd
  3923. \begin{figure}[tp]
  3924. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  3925. \small
  3926. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3927. A \emph{set} is an unordered collection of elements without duplicates.
  3928. Here are some of the operations defined on sets.
  3929. \index{subject}{set}
  3930. \begin{description}
  3931. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  3932. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  3933. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  3934. difference of the two sets.
  3935. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  3936. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  3937. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  3938. \end{description}
  3939. \end{tcolorbox}
  3940. %\end{wrapfigure}
  3941. \caption{The \code{set} data structure.}
  3942. \label{fig:set}
  3943. \end{figure}
  3944. \fi}
  3945. The live locations after an instruction are always the same as the
  3946. live locations before the next instruction.
  3947. \index{subject}{live-after} \index{subject}{live-before}
  3948. \begin{equation} \label{eq:live-after-before-next}
  3949. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3950. \end{equation}
  3951. To start things off, there are no live locations after the last
  3952. instruction, so
  3953. \begin{equation}\label{eq:live-last-empty}
  3954. L_{\mathsf{after}}(n) = \emptyset
  3955. \end{equation}
  3956. We then apply the following rule repeatedly, traversing the
  3957. instruction sequence back to front.
  3958. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  3959. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  3960. \end{equation}
  3961. where $W(k)$ are the locations written to by instruction $I_k$ and
  3962. $R(k)$ are the locations read by instruction $I_k$.
  3963. {\if\edition\racketEd
  3964. There is a special case for \code{jmp} instructions. The locations
  3965. that are live before a \code{jmp} should be the locations in
  3966. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  3967. maintaining an alist named \code{label->live} that maps each label to
  3968. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  3969. now the only \code{jmp} in a \LangXVar{} program is the one at the
  3970. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  3971. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  3972. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  3973. \fi}
  3974. Let us walk through the above example, applying these formulas
  3975. starting with the instruction on line 5. We collect the answers in
  3976. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  3977. \code{addq b, c} instruction is $\emptyset$ because it is the last
  3978. instruction (formula~\ref{eq:live-last-empty}). The
  3979. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  3980. because it reads from variables \code{b} and \code{c}
  3981. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  3982. \[
  3983. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  3984. \]
  3985. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  3986. the live-before set from line 5 to be the live-after set for this
  3987. instruction (formula~\ref{eq:live-after-before-next}).
  3988. \[
  3989. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  3990. \]
  3991. This move instruction writes to \code{b} and does not read from any
  3992. variables, so we have the following live-before set
  3993. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  3994. \[
  3995. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  3996. \]
  3997. The live-before for instruction \code{movq a, c}
  3998. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  3999. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  4000. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4001. variable that is not live and does not read from a variable.
  4002. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4003. because it writes to variable \code{a}.
  4004. \begin{figure}[tbp]
  4005. \begin{minipage}{0.45\textwidth}
  4006. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4007. movq $5, a
  4008. movq $30, b
  4009. movq a, c
  4010. movq $10, b
  4011. addq b, c
  4012. \end{lstlisting}
  4013. \end{minipage}
  4014. \vrule\hspace{10pt}
  4015. \begin{minipage}{0.45\textwidth}
  4016. \begin{align*}
  4017. L_{\mathsf{before}}(1)= \emptyset,
  4018. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4019. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4020. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4021. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4022. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4023. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4024. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4025. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4026. L_{\mathsf{after}}(5)= \emptyset
  4027. \end{align*}
  4028. \end{minipage}
  4029. \caption{Example output of liveness analysis on a short example.}
  4030. \label{fig:liveness-example-0}
  4031. \end{figure}
  4032. \begin{exercise}\normalfont
  4033. Perform liveness analysis on the running example in
  4034. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4035. sets for each instruction. Compare your answers to the solution
  4036. shown in Figure~\ref{fig:live-eg}.
  4037. \end{exercise}
  4038. \begin{figure}[tp]
  4039. \hspace{20pt}
  4040. \begin{minipage}{0.45\textwidth}
  4041. {\if\edition\racketEd
  4042. \begin{lstlisting}
  4043. |$\{\ttm{rsp}\}$|
  4044. movq $1, v
  4045. |$\{\ttm{v},\ttm{rsp}\}$|
  4046. movq $42, w
  4047. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4048. movq v, x
  4049. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4050. addq $7, x
  4051. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4052. movq x, y
  4053. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4054. movq x, z
  4055. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4056. addq w, z
  4057. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4058. movq y, t
  4059. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4060. negq t
  4061. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4062. movq z, %rax
  4063. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4064. addq t, %rax
  4065. |$\{\ttm{rax},\ttm{rsp}\}$|
  4066. jmp conclusion
  4067. \end{lstlisting}
  4068. \fi}
  4069. {\if\edition\pythonEd
  4070. \begin{lstlisting}
  4071. movq $1, v
  4072. |$\{\ttm{v}\}$|
  4073. movq $42, w
  4074. |$\{\ttm{w}, \ttm{v}\}$|
  4075. movq v, x
  4076. |$\{\ttm{w}, \ttm{x}\}$|
  4077. addq $7, x
  4078. |$\{\ttm{w}, \ttm{x}\}$|
  4079. movq x, y
  4080. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4081. movq x, z
  4082. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4083. addq w, z
  4084. |$\{\ttm{y}, \ttm{z}\}$|
  4085. movq y, tmp_0
  4086. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4087. negq tmp_0
  4088. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4089. movq z, tmp_1
  4090. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4091. addq tmp_0, tmp_1
  4092. |$\{\ttm{tmp\_1}\}$|
  4093. movq tmp_1, %rdi
  4094. |$\{\ttm{rdi}\}$|
  4095. callq print_int
  4096. |$\{\}$|
  4097. \end{lstlisting}
  4098. \fi}
  4099. \end{minipage}
  4100. \caption{The running example annotated with live-after sets.}
  4101. \label{fig:live-eg}
  4102. \end{figure}
  4103. \begin{exercise}\normalfont
  4104. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4105. %
  4106. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4107. field of the \code{Block} structure.}
  4108. %
  4109. \python{Return a dictionary that maps each instruction to its
  4110. live-after set.}
  4111. %
  4112. \racket{We recommend creating an auxiliary function that takes a list
  4113. of instructions and an initial live-after set (typically empty) and
  4114. returns the list of live-after sets.}
  4115. %
  4116. We recommend creating auxiliary functions to 1) compute the set
  4117. of locations that appear in an \Arg{}, 2) compute the locations read
  4118. by an instruction (the $R$ function), and 3) the locations written by
  4119. an instruction (the $W$ function). The \code{callq} instruction should
  4120. include all of the caller-saved registers in its write-set $W$ because
  4121. the calling convention says that those registers may be written to
  4122. during the function call. Likewise, the \code{callq} instruction
  4123. should include the appropriate argument-passing registers in its
  4124. read-set $R$, depending on the arity of the function being
  4125. called. (This is why the abstract syntax for \code{callq} includes the
  4126. arity.)
  4127. \end{exercise}
  4128. %\clearpage
  4129. \section{Build the Interference Graph}
  4130. \label{sec:build-interference}
  4131. {\if\edition\racketEd
  4132. \begin{figure}[tp]
  4133. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4134. \small
  4135. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4136. A \emph{graph} is a collection of vertices and edges where each
  4137. edge connects two vertices. A graph is \emph{directed} if each
  4138. edge points from a source to a target. Otherwise the graph is
  4139. \emph{undirected}.
  4140. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4141. \begin{description}
  4142. %% We currently don't use directed graphs. We instead use
  4143. %% directed multi-graphs. -Jeremy
  4144. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4145. directed graph from a list of edges. Each edge is a list
  4146. containing the source and target vertex.
  4147. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4148. undirected graph from a list of edges. Each edge is represented by
  4149. a list containing two vertices.
  4150. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4151. inserts a vertex into the graph.
  4152. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4153. inserts an edge between the two vertices.
  4154. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4155. returns a sequence of vertices adjacent to the vertex.
  4156. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4157. returns a sequence of all vertices in the graph.
  4158. \end{description}
  4159. \end{tcolorbox}
  4160. %\end{wrapfigure}
  4161. \caption{The Racket \code{graph} package.}
  4162. \label{fig:graph}
  4163. \end{figure}
  4164. \fi}
  4165. Based on the liveness analysis, we know where each location is live.
  4166. However, during register allocation, we need to answer questions of
  4167. the specific form: are locations $u$ and $v$ live at the same time?
  4168. (And therefore cannot be assigned to the same register.) To make this
  4169. question more efficient to answer, we create an explicit data
  4170. structure, an \emph{interference graph}\index{subject}{interference
  4171. graph}. An interference graph is an undirected graph that has an
  4172. edge between two locations if they are live at the same time, that is,
  4173. if they interfere with each other.
  4174. %
  4175. \racket{We recommend using the Racket \code{graph} package
  4176. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4177. %
  4178. \python{We provide implementations of directed and undirected graph
  4179. data structures in the file \code{graph.py} of the support code.}
  4180. A straightforward way to compute the interference graph is to look at
  4181. the set of live locations between each instruction and add an edge to
  4182. the graph for every pair of variables in the same set. This approach
  4183. is less than ideal for two reasons. First, it can be expensive because
  4184. it takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  4185. locations. Second, in the special case where two locations hold the
  4186. same value (because one was assigned to the other), they can be live
  4187. at the same time without interfering with each other.
  4188. A better way to compute the interference graph is to focus on
  4189. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4190. must not overwrite something in a live location. So for each
  4191. instruction, we create an edge between the locations being written to
  4192. and the live locations. (Except that one should not create self
  4193. edges.) Note that for the \key{callq} instruction, we consider all of
  4194. the caller-saved registers as being written to, so an edge is added
  4195. between every live variable and every caller-saved register. Also, for
  4196. \key{movq} there is the above-mentioned special case to deal with. If
  4197. a live variable $v$ is the same as the source of the \key{movq}, then
  4198. there is no need to add an edge between $v$ and the destination,
  4199. because they both hold the same value.
  4200. %
  4201. So we have the following two rules.
  4202. \begin{enumerate}
  4203. \item If instruction $I_k$ is a move instruction of the form
  4204. \key{movq} $s$\key{,} $d$, then for every $v \in
  4205. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4206. $(d,v)$.
  4207. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4208. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4209. $(d,v)$.
  4210. \end{enumerate}
  4211. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4212. the above rules to each instruction. We highlight a few of the
  4213. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4214. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4215. so \code{v} interferes with \code{rsp}.}
  4216. %
  4217. \python{The first instruction is \lstinline{movq $1, v} and the
  4218. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4219. no interference because $\ttm{v}$ is the destination of the move.}
  4220. %
  4221. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4222. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4223. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4224. %
  4225. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4226. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4227. $\ttm{x}$ interferes with \ttm{w}.}
  4228. %
  4229. \racket{The next instruction is \lstinline{movq x, y} and the
  4230. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4231. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4232. \ttm{x} because \ttm{x} is the source of the move and therefore
  4233. \ttm{x} and \ttm{y} hold the same value.}
  4234. %
  4235. \python{The next instruction is \lstinline{movq x, y} and the
  4236. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4237. applies, so \ttm{y} interferes with \ttm{w} but not
  4238. \ttm{x} because \ttm{x} is the source of the move and therefore
  4239. \ttm{x} and \ttm{y} hold the same value.}
  4240. %
  4241. Figure~\ref{fig:interference-results} lists the interference results
  4242. for all of the instructions and the resulting interference graph is
  4243. shown in Figure~\ref{fig:interfere}.
  4244. \begin{figure}[tbp]
  4245. \begin{quote}
  4246. {\if\edition\racketEd
  4247. \begin{tabular}{ll}
  4248. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4249. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4250. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4251. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4252. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4253. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4254. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4255. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4256. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4257. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4258. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4259. \lstinline!jmp conclusion!& no interference.
  4260. \end{tabular}
  4261. \fi}
  4262. {\if\edition\pythonEd
  4263. \begin{tabular}{ll}
  4264. \lstinline!movq $1, v!& no interference\\
  4265. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4266. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4267. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4268. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4269. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4270. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4271. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4272. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4273. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4274. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4275. \lstinline!movq tmp_1, %rdi! & no interference \\
  4276. \lstinline!callq print_int!& no interference.
  4277. \end{tabular}
  4278. \fi}
  4279. \end{quote}
  4280. \caption{Interference results for the running example.}
  4281. \label{fig:interference-results}
  4282. \end{figure}
  4283. \begin{figure}[tbp]
  4284. \large
  4285. {\if\edition\racketEd
  4286. \[
  4287. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4288. \node (rax) at (0,0) {$\ttm{rax}$};
  4289. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4290. \node (t1) at (0,2) {$\ttm{t}$};
  4291. \node (z) at (3,2) {$\ttm{z}$};
  4292. \node (x) at (6,2) {$\ttm{x}$};
  4293. \node (y) at (3,0) {$\ttm{y}$};
  4294. \node (w) at (6,0) {$\ttm{w}$};
  4295. \node (v) at (9,0) {$\ttm{v}$};
  4296. \draw (t1) to (rax);
  4297. \draw (t1) to (z);
  4298. \draw (z) to (y);
  4299. \draw (z) to (w);
  4300. \draw (x) to (w);
  4301. \draw (y) to (w);
  4302. \draw (v) to (w);
  4303. \draw (v) to (rsp);
  4304. \draw (w) to (rsp);
  4305. \draw (x) to (rsp);
  4306. \draw (y) to (rsp);
  4307. \path[-.,bend left=15] (z) edge node {} (rsp);
  4308. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4309. \draw (rax) to (rsp);
  4310. \end{tikzpicture}
  4311. \]
  4312. \fi}
  4313. {\if\edition\pythonEd
  4314. \[
  4315. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4316. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4317. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4318. \node (z) at (3,2) {$\ttm{z}$};
  4319. \node (x) at (6,2) {$\ttm{x}$};
  4320. \node (y) at (3,0) {$\ttm{y}$};
  4321. \node (w) at (6,0) {$\ttm{w}$};
  4322. \node (v) at (9,0) {$\ttm{v}$};
  4323. \draw (t0) to (t1);
  4324. \draw (t0) to (z);
  4325. \draw (z) to (y);
  4326. \draw (z) to (w);
  4327. \draw (x) to (w);
  4328. \draw (y) to (w);
  4329. \draw (v) to (w);
  4330. \end{tikzpicture}
  4331. \]
  4332. \fi}
  4333. \caption{The interference graph of the example program.}
  4334. \label{fig:interfere}
  4335. \end{figure}
  4336. %% Our next concern is to choose a data structure for representing the
  4337. %% interference graph. There are many choices for how to represent a
  4338. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4339. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4340. %% data structure is to study the algorithm that uses the data structure,
  4341. %% determine what operations need to be performed, and then choose the
  4342. %% data structure that provide the most efficient implementations of
  4343. %% those operations. Often times the choice of data structure can have an
  4344. %% effect on the time complexity of the algorithm, as it does here. If
  4345. %% you skim the next section, you will see that the register allocation
  4346. %% algorithm needs to ask the graph for all of its vertices and, given a
  4347. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4348. %% correct choice of graph representation is that of an adjacency
  4349. %% list. There are helper functions in \code{utilities.rkt} for
  4350. %% representing graphs using the adjacency list representation:
  4351. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4352. %% (Appendix~\ref{appendix:utilities}).
  4353. %% %
  4354. %% \margincomment{\footnotesize To do: change to use the
  4355. %% Racket graph library. \\ --Jeremy}
  4356. %% %
  4357. %% In particular, those functions use a hash table to map each vertex to
  4358. %% the set of adjacent vertices, and the sets are represented using
  4359. %% Racket's \key{set}, which is also a hash table.
  4360. \begin{exercise}\normalfont
  4361. \racket{Implement the compiler pass named \code{build\_interference} according
  4362. to the algorithm suggested above. We recommend using the Racket
  4363. \code{graph} package to create and inspect the interference graph.
  4364. The output graph of this pass should be stored in the $\itm{info}$ field of
  4365. the program, under the key \code{conflicts}.}
  4366. %
  4367. \python{Implement a function named \code{build\_interference}
  4368. according to the algorithm suggested above that
  4369. returns the interference graph.}
  4370. \end{exercise}
  4371. \section{Graph Coloring via Sudoku}
  4372. \label{sec:graph-coloring}
  4373. \index{subject}{graph coloring}
  4374. \index{subject}{Sudoku}
  4375. \index{subject}{color}
  4376. We come to the main event, mapping variables to registers and stack
  4377. locations. Variables that interfere with each other must be mapped to
  4378. different locations. In terms of the interference graph, this means
  4379. that adjacent vertices must be mapped to different locations. If we
  4380. think of locations as colors, the register allocation problem becomes
  4381. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4382. The reader may be more familiar with the graph coloring problem than he
  4383. or she realizes; the popular game of Sudoku is an instance of the
  4384. graph coloring problem. The following describes how to build a graph
  4385. out of an initial Sudoku board.
  4386. \begin{itemize}
  4387. \item There is one vertex in the graph for each Sudoku square.
  4388. \item There is an edge between two vertices if the corresponding squares
  4389. are in the same row, in the same column, or if the squares are in
  4390. the same $3\times 3$ region.
  4391. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4392. \item Based on the initial assignment of numbers to squares in the
  4393. Sudoku board, assign the corresponding colors to the corresponding
  4394. vertices in the graph.
  4395. \end{itemize}
  4396. If you can color the remaining vertices in the graph with the nine
  4397. colors, then you have also solved the corresponding game of Sudoku.
  4398. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4399. the corresponding graph with colored vertices. We map the Sudoku
  4400. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4401. sampling of the vertices (the colored ones) because showing edges for
  4402. all of the vertices would make the graph unreadable.
  4403. \begin{figure}[tbp]
  4404. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4405. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4406. \caption{A Sudoku game board and the corresponding colored graph.}
  4407. \label{fig:sudoku-graph}
  4408. \end{figure}
  4409. Some techniques for playing Sudoku correspond to heuristics used in
  4410. graph coloring algorithms. For example, one of the basic techniques
  4411. for Sudoku is called Pencil Marks. The idea is to use a process of
  4412. elimination to determine what numbers are no longer available for a
  4413. square and write down those numbers in the square (writing very
  4414. small). For example, if the number $1$ is assigned to a square, then
  4415. write the pencil mark $1$ in all the squares in the same row, column,
  4416. and region to indicate that $1$ is no longer an option for those other
  4417. squares.
  4418. %
  4419. The Pencil Marks technique corresponds to the notion of
  4420. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4421. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4422. are no longer available. In graph terminology, we have the following
  4423. definition:
  4424. \begin{equation*}
  4425. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4426. \text{ and } \mathrm{color}(v) = c \}
  4427. \end{equation*}
  4428. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4429. edge with $u$.
  4430. The Pencil Marks technique leads to a simple strategy for filling in
  4431. numbers: if there is a square with only one possible number left, then
  4432. choose that number! But what if there are no squares with only one
  4433. possibility left? One brute-force approach is to try them all: choose
  4434. the first one and if that ultimately leads to a solution, great. If
  4435. not, backtrack and choose the next possibility. One good thing about
  4436. Pencil Marks is that it reduces the degree of branching in the search
  4437. tree. Nevertheless, backtracking can be terribly time consuming. One
  4438. way to reduce the amount of backtracking is to use the
  4439. most-constrained-first heuristic (aka. minimum remaining
  4440. values)~\citep{Russell2003}. That is, when choosing a square, always
  4441. choose one with the fewest possibilities left (the vertex with the
  4442. highest saturation). The idea is that choosing highly constrained
  4443. squares earlier rather than later is better because later on there may
  4444. not be any possibilities left in the highly saturated squares.
  4445. However, register allocation is easier than Sudoku because the
  4446. register allocator can fall back to assigning variables to stack
  4447. locations when the registers run out. Thus, it makes sense to replace
  4448. backtracking with greedy search: make the best choice at the time and
  4449. keep going. We still wish to minimize the number of colors needed, so
  4450. we use the most-constrained-first heuristic in the greedy search.
  4451. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4452. algorithm for register allocation based on saturation and the
  4453. most-constrained-first heuristic. It is roughly equivalent to the
  4454. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4455. %,Gebremedhin:1999fk,Omari:2006uq
  4456. Just as in Sudoku, the algorithm represents colors with integers. The
  4457. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4458. for register allocation. The integers $k$ and larger correspond to
  4459. stack locations. The registers that are not used for register
  4460. allocation, such as \code{rax}, are assigned to negative integers. In
  4461. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4462. %% One might wonder why we include registers at all in the liveness
  4463. %% analysis and interference graph. For example, we never allocate a
  4464. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4465. %% leave them out. As we see in Chapter~\ref{ch:Lvec}, when we begin
  4466. %% to use register for passing arguments to functions, it will be
  4467. %% necessary for those registers to appear in the interference graph
  4468. %% because those registers will also be assigned to variables, and we
  4469. %% don't want those two uses to encroach on each other. Regarding
  4470. %% registers such as \code{rax} and \code{rsp} that are not used for
  4471. %% variables, we could omit them from the interference graph but that
  4472. %% would require adding special cases to our algorithm, which would
  4473. %% complicate the logic for little gain.
  4474. \begin{figure}[btp]
  4475. \centering
  4476. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4477. Algorithm: DSATUR
  4478. Input: a graph |$G$|
  4479. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4480. |$W \gets \mathrm{vertices}(G)$|
  4481. while |$W \neq \emptyset$| do
  4482. pick a vertex |$u$| from |$W$| with the highest saturation,
  4483. breaking ties randomly
  4484. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4485. |$\mathrm{color}[u] \gets c$|
  4486. |$W \gets W - \{u\}$|
  4487. \end{lstlisting}
  4488. \caption{The saturation-based greedy graph coloring algorithm.}
  4489. \label{fig:satur-algo}
  4490. \end{figure}
  4491. {\if\edition\racketEd
  4492. With the DSATUR algorithm in hand, let us return to the running
  4493. example and consider how to color the interference graph in
  4494. Figure~\ref{fig:interfere}.
  4495. %
  4496. We start by assigning the register nodes to their own color. For
  4497. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4498. assigned $-2$. The variables are not yet colored, so they are
  4499. annotated with a dash. We then update the saturation for vertices that
  4500. are adjacent to a register, obtaining the following annotated
  4501. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4502. it interferes with both \code{rax} and \code{rsp}.
  4503. \[
  4504. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4505. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4506. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4507. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4508. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4509. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4510. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4511. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4512. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4513. \draw (t1) to (rax);
  4514. \draw (t1) to (z);
  4515. \draw (z) to (y);
  4516. \draw (z) to (w);
  4517. \draw (x) to (w);
  4518. \draw (y) to (w);
  4519. \draw (v) to (w);
  4520. \draw (v) to (rsp);
  4521. \draw (w) to (rsp);
  4522. \draw (x) to (rsp);
  4523. \draw (y) to (rsp);
  4524. \path[-.,bend left=15] (z) edge node {} (rsp);
  4525. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4526. \draw (rax) to (rsp);
  4527. \end{tikzpicture}
  4528. \]
  4529. The algorithm says to select a maximally saturated vertex. So we pick
  4530. $\ttm{t}$ and color it with the first available integer, which is
  4531. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4532. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4533. \[
  4534. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4535. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4536. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4537. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4538. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4539. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4540. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4541. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4542. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4543. \draw (t1) to (rax);
  4544. \draw (t1) to (z);
  4545. \draw (z) to (y);
  4546. \draw (z) to (w);
  4547. \draw (x) to (w);
  4548. \draw (y) to (w);
  4549. \draw (v) to (w);
  4550. \draw (v) to (rsp);
  4551. \draw (w) to (rsp);
  4552. \draw (x) to (rsp);
  4553. \draw (y) to (rsp);
  4554. \path[-.,bend left=15] (z) edge node {} (rsp);
  4555. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4556. \draw (rax) to (rsp);
  4557. \end{tikzpicture}
  4558. \]
  4559. We repeat the process, selecting a maximally saturated vertex,
  4560. choosing is \code{z}, and color it with the first available number, which
  4561. is $1$. We add $1$ to the saturation for the neighboring vertices
  4562. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4563. \[
  4564. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4565. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4566. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4567. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4568. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4569. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4570. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4571. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4572. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4573. \draw (t1) to (rax);
  4574. \draw (t1) to (z);
  4575. \draw (z) to (y);
  4576. \draw (z) to (w);
  4577. \draw (x) to (w);
  4578. \draw (y) to (w);
  4579. \draw (v) to (w);
  4580. \draw (v) to (rsp);
  4581. \draw (w) to (rsp);
  4582. \draw (x) to (rsp);
  4583. \draw (y) to (rsp);
  4584. \path[-.,bend left=15] (z) edge node {} (rsp);
  4585. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4586. \draw (rax) to (rsp);
  4587. \end{tikzpicture}
  4588. \]
  4589. The most saturated vertices are now \code{w} and \code{y}. We color
  4590. \code{w} with the first available color, which is $0$.
  4591. \[
  4592. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4593. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4594. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4595. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4596. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4597. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4598. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4599. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4600. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4601. \draw (t1) to (rax);
  4602. \draw (t1) to (z);
  4603. \draw (z) to (y);
  4604. \draw (z) to (w);
  4605. \draw (x) to (w);
  4606. \draw (y) to (w);
  4607. \draw (v) to (w);
  4608. \draw (v) to (rsp);
  4609. \draw (w) to (rsp);
  4610. \draw (x) to (rsp);
  4611. \draw (y) to (rsp);
  4612. \path[-.,bend left=15] (z) edge node {} (rsp);
  4613. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4614. \draw (rax) to (rsp);
  4615. \end{tikzpicture}
  4616. \]
  4617. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4618. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4619. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4620. and \code{z}, whose colors are $0$ and $1$ respectively.
  4621. \[
  4622. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4623. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4624. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4625. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4626. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4627. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4628. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4629. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4630. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4631. \draw (t1) to (rax);
  4632. \draw (t1) to (z);
  4633. \draw (z) to (y);
  4634. \draw (z) to (w);
  4635. \draw (x) to (w);
  4636. \draw (y) to (w);
  4637. \draw (v) to (w);
  4638. \draw (v) to (rsp);
  4639. \draw (w) to (rsp);
  4640. \draw (x) to (rsp);
  4641. \draw (y) to (rsp);
  4642. \path[-.,bend left=15] (z) edge node {} (rsp);
  4643. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4644. \draw (rax) to (rsp);
  4645. \end{tikzpicture}
  4646. \]
  4647. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4648. \[
  4649. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4650. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4651. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4652. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4653. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4654. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4655. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4656. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4657. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4658. \draw (t1) to (rax);
  4659. \draw (t1) to (z);
  4660. \draw (z) to (y);
  4661. \draw (z) to (w);
  4662. \draw (x) to (w);
  4663. \draw (y) to (w);
  4664. \draw (v) to (w);
  4665. \draw (v) to (rsp);
  4666. \draw (w) to (rsp);
  4667. \draw (x) to (rsp);
  4668. \draw (y) to (rsp);
  4669. \path[-.,bend left=15] (z) edge node {} (rsp);
  4670. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4671. \draw (rax) to (rsp);
  4672. \end{tikzpicture}
  4673. \]
  4674. In the last step of the algorithm, we color \code{x} with $1$.
  4675. \[
  4676. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4677. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4678. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4679. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4680. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4681. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4682. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4683. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4684. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4685. \draw (t1) to (rax);
  4686. \draw (t1) to (z);
  4687. \draw (z) to (y);
  4688. \draw (z) to (w);
  4689. \draw (x) to (w);
  4690. \draw (y) to (w);
  4691. \draw (v) to (w);
  4692. \draw (v) to (rsp);
  4693. \draw (w) to (rsp);
  4694. \draw (x) to (rsp);
  4695. \draw (y) to (rsp);
  4696. \path[-.,bend left=15] (z) edge node {} (rsp);
  4697. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4698. \draw (rax) to (rsp);
  4699. \end{tikzpicture}
  4700. \]
  4701. So we obtain the following coloring:
  4702. \[
  4703. \{
  4704. \ttm{rax} \mapsto -1,
  4705. \ttm{rsp} \mapsto -2,
  4706. \ttm{t} \mapsto 0,
  4707. \ttm{z} \mapsto 1,
  4708. \ttm{x} \mapsto 1,
  4709. \ttm{y} \mapsto 2,
  4710. \ttm{w} \mapsto 0,
  4711. \ttm{v} \mapsto 1
  4712. \}
  4713. \]
  4714. \fi}
  4715. %
  4716. {\if\edition\pythonEd
  4717. %
  4718. With the DSATUR algorithm in hand, let us return to the running
  4719. example and consider how to color the interference graph in
  4720. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4721. to indicate that it has not yet been assigned a color. The saturation
  4722. sets are also shown for each node; all of them start as the empty set.
  4723. (We do not include the register nodes in the graph below because there
  4724. were no interference edges involving registers in this program, but in
  4725. general there can be.)
  4726. %
  4727. \[
  4728. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4729. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4730. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4731. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4732. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4733. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4734. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4735. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4736. \draw (t0) to (t1);
  4737. \draw (t0) to (z);
  4738. \draw (z) to (y);
  4739. \draw (z) to (w);
  4740. \draw (x) to (w);
  4741. \draw (y) to (w);
  4742. \draw (v) to (w);
  4743. \end{tikzpicture}
  4744. \]
  4745. The algorithm says to select a maximally saturated vertex, but they
  4746. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4747. then color it with the first available integer, which is $0$. We mark
  4748. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4749. they interfere with $\ttm{tmp\_0}$.
  4750. \[
  4751. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4752. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4753. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4754. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4755. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4756. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4757. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4758. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4759. \draw (t0) to (t1);
  4760. \draw (t0) to (z);
  4761. \draw (z) to (y);
  4762. \draw (z) to (w);
  4763. \draw (x) to (w);
  4764. \draw (y) to (w);
  4765. \draw (v) to (w);
  4766. \end{tikzpicture}
  4767. \]
  4768. We repeat the process. The most saturated vertices are \code{z} and
  4769. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4770. available number, which is $1$. We add $1$ to the saturation for the
  4771. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4772. \[
  4773. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4774. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4775. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4776. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4777. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4778. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4779. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4780. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4781. \draw (t0) to (t1);
  4782. \draw (t0) to (z);
  4783. \draw (z) to (y);
  4784. \draw (z) to (w);
  4785. \draw (x) to (w);
  4786. \draw (y) to (w);
  4787. \draw (v) to (w);
  4788. \end{tikzpicture}
  4789. \]
  4790. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4791. \code{y}. We color \code{w} with the first available color, which
  4792. is $0$.
  4793. \[
  4794. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4795. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4796. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4797. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4798. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4799. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4800. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4801. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4802. \draw (t0) to (t1);
  4803. \draw (t0) to (z);
  4804. \draw (z) to (y);
  4805. \draw (z) to (w);
  4806. \draw (x) to (w);
  4807. \draw (y) to (w);
  4808. \draw (v) to (w);
  4809. \end{tikzpicture}
  4810. \]
  4811. Now \code{y} is the most saturated, so we color it with $2$.
  4812. \[
  4813. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4814. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4815. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4816. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4817. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4818. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4819. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4820. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4821. \draw (t0) to (t1);
  4822. \draw (t0) to (z);
  4823. \draw (z) to (y);
  4824. \draw (z) to (w);
  4825. \draw (x) to (w);
  4826. \draw (y) to (w);
  4827. \draw (v) to (w);
  4828. \end{tikzpicture}
  4829. \]
  4830. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  4831. We choose to color \code{v} with $1$.
  4832. \[
  4833. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4834. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4835. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4836. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4837. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4838. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4839. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4840. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4841. \draw (t0) to (t1);
  4842. \draw (t0) to (z);
  4843. \draw (z) to (y);
  4844. \draw (z) to (w);
  4845. \draw (x) to (w);
  4846. \draw (y) to (w);
  4847. \draw (v) to (w);
  4848. \end{tikzpicture}
  4849. \]
  4850. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4851. \[
  4852. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4853. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4854. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4855. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4856. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4857. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4858. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4859. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4860. \draw (t0) to (t1);
  4861. \draw (t0) to (z);
  4862. \draw (z) to (y);
  4863. \draw (z) to (w);
  4864. \draw (x) to (w);
  4865. \draw (y) to (w);
  4866. \draw (v) to (w);
  4867. \end{tikzpicture}
  4868. \]
  4869. So we obtain the following coloring:
  4870. \[
  4871. \{ \ttm{tmp\_0} \mapsto 0,
  4872. \ttm{tmp\_1} \mapsto 1,
  4873. \ttm{z} \mapsto 1,
  4874. \ttm{x} \mapsto 1,
  4875. \ttm{y} \mapsto 2,
  4876. \ttm{w} \mapsto 0,
  4877. \ttm{v} \mapsto 1 \}
  4878. \]
  4879. \fi}
  4880. We recommend creating an auxiliary function named \code{color\_graph}
  4881. that takes an interference graph and a list of all the variables in
  4882. the program. This function should return a mapping of variables to
  4883. their colors (represented as natural numbers). By creating this helper
  4884. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  4885. when we add support for functions.
  4886. To prioritize the processing of highly saturated nodes inside the
  4887. \code{color\_graph} function, we recommend using the priority queue
  4888. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  4889. addition, you will need to maintain a mapping from variables to their
  4890. ``handles'' in the priority queue so that you can notify the priority
  4891. queue when their saturation changes.}
  4892. {\if\edition\racketEd
  4893. \begin{figure}[tp]
  4894. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4895. \small
  4896. \begin{tcolorbox}[title=Priority Queue]
  4897. A \emph{priority queue} is a collection of items in which the
  4898. removal of items is governed by priority. In a ``min'' queue,
  4899. lower priority items are removed first. An implementation is in
  4900. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4901. queue} \index{subject}{minimum priority queue}
  4902. \begin{description}
  4903. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4904. priority queue that uses the $\itm{cmp}$ predicate to determine
  4905. whether its first argument has lower or equal priority to its
  4906. second argument.
  4907. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4908. items in the queue.
  4909. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4910. the item into the queue and returns a handle for the item in the
  4911. queue.
  4912. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4913. the lowest priority.
  4914. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4915. notifies the queue that the priority has decreased for the item
  4916. associated with the given handle.
  4917. \end{description}
  4918. \end{tcolorbox}
  4919. %\end{wrapfigure}
  4920. \caption{The priority queue data structure.}
  4921. \label{fig:priority-queue}
  4922. \end{figure}
  4923. \fi}
  4924. With the coloring complete, we finalize the assignment of variables to
  4925. registers and stack locations. We map the first $k$ colors to the $k$
  4926. registers and the rest of the colors to stack locations. Suppose for
  4927. the moment that we have just one register to use for register
  4928. allocation, \key{rcx}. Then we have the following map from colors to
  4929. locations.
  4930. \[
  4931. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4932. \]
  4933. Composing this mapping with the coloring, we arrive at the following
  4934. assignment of variables to locations.
  4935. {\if\edition\racketEd
  4936. \begin{gather*}
  4937. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4938. \ttm{w} \mapsto \key{\%rcx}, \,
  4939. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4940. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4941. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4942. \ttm{t} \mapsto \key{\%rcx} \}
  4943. \end{gather*}
  4944. \fi}
  4945. {\if\edition\pythonEd
  4946. \begin{gather*}
  4947. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4948. \ttm{w} \mapsto \key{\%rcx}, \,
  4949. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4950. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4951. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4952. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  4953. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  4954. \end{gather*}
  4955. \fi}
  4956. Adapt the code from the \code{assign\_homes} pass
  4957. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  4958. assigned location. Applying the above assignment to our running
  4959. example, on the left, yields the program on the right.
  4960. % why frame size of 32? -JGS
  4961. \begin{center}
  4962. {\if\edition\racketEd
  4963. \begin{minipage}{0.3\textwidth}
  4964. \begin{lstlisting}
  4965. movq $1, v
  4966. movq $42, w
  4967. movq v, x
  4968. addq $7, x
  4969. movq x, y
  4970. movq x, z
  4971. addq w, z
  4972. movq y, t
  4973. negq t
  4974. movq z, %rax
  4975. addq t, %rax
  4976. jmp conclusion
  4977. \end{lstlisting}
  4978. \end{minipage}
  4979. $\Rightarrow\qquad$
  4980. \begin{minipage}{0.45\textwidth}
  4981. \begin{lstlisting}
  4982. movq $1, -8(%rbp)
  4983. movq $42, %rcx
  4984. movq -8(%rbp), -8(%rbp)
  4985. addq $7, -8(%rbp)
  4986. movq -8(%rbp), -16(%rbp)
  4987. movq -8(%rbp), -8(%rbp)
  4988. addq %rcx, -8(%rbp)
  4989. movq -16(%rbp), %rcx
  4990. negq %rcx
  4991. movq -8(%rbp), %rax
  4992. addq %rcx, %rax
  4993. jmp conclusion
  4994. \end{lstlisting}
  4995. \end{minipage}
  4996. \fi}
  4997. {\if\edition\pythonEd
  4998. \begin{minipage}{0.3\textwidth}
  4999. \begin{lstlisting}
  5000. movq $1, v
  5001. movq $42, w
  5002. movq v, x
  5003. addq $7, x
  5004. movq x, y
  5005. movq x, z
  5006. addq w, z
  5007. movq y, tmp_0
  5008. negq tmp_0
  5009. movq z, tmp_1
  5010. addq tmp_0, tmp_1
  5011. movq tmp_1, %rdi
  5012. callq print_int
  5013. \end{lstlisting}
  5014. \end{minipage}
  5015. $\Rightarrow\qquad$
  5016. \begin{minipage}{0.45\textwidth}
  5017. \begin{lstlisting}
  5018. movq $1, -8(%rbp)
  5019. movq $42, %rcx
  5020. movq -8(%rbp), -8(%rbp)
  5021. addq $7, -8(%rbp)
  5022. movq -8(%rbp), -16(%rbp)
  5023. movq -8(%rbp), -8(%rbp)
  5024. addq %rcx, -8(%rbp)
  5025. movq -16(%rbp), %rcx
  5026. negq %rcx
  5027. movq -8(%rbp), -8(%rbp)
  5028. addq %rcx, -8(%rbp)
  5029. movq -8(%rbp), %rdi
  5030. callq print_int
  5031. \end{lstlisting}
  5032. \end{minipage}
  5033. \fi}
  5034. \end{center}
  5035. \begin{exercise}\normalfont
  5036. %
  5037. Implement the compiler pass \code{allocate\_registers}.
  5038. %
  5039. Create five programs that exercise all aspects of the register
  5040. allocation algorithm, including spilling variables to the stack.
  5041. %
  5042. \racket{Replace \code{assign\_homes} in the list of \code{passes} in the
  5043. \code{run-tests.rkt} script with the three new passes:
  5044. \code{uncover\_live}, \code{build\_interference}, and
  5045. \code{allocate\_registers}.
  5046. %
  5047. Temporarily remove the \code{print\_x86} pass from the list of passes
  5048. and the call to \code{compiler-tests}.
  5049. Run the script to test the register allocator.
  5050. }
  5051. %
  5052. \python{Run the \code{run-tests.py} script to to check whether the
  5053. output programs produce the same result as the input programs.}
  5054. \end{exercise}
  5055. \section{Patch Instructions}
  5056. \label{sec:patch-instructions}
  5057. The remaining step in the compilation to x86 is to ensure that the
  5058. instructions have at most one argument that is a memory access.
  5059. %
  5060. In the running example, the instruction \code{movq -8(\%rbp),
  5061. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  5062. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5063. then move \code{rax} into \code{-16(\%rbp)}.
  5064. %
  5065. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5066. problematic, but they can simply be deleted. In general, we recommend
  5067. deleting all the trivial moves whose source and destination are the
  5068. same location.
  5069. %
  5070. The following is the output of \code{patch\_instructions} on the
  5071. running example.
  5072. \begin{center}
  5073. {\if\edition\racketEd
  5074. \begin{minipage}{0.4\textwidth}
  5075. \begin{lstlisting}
  5076. movq $1, -8(%rbp)
  5077. movq $42, %rcx
  5078. movq -8(%rbp), -8(%rbp)
  5079. addq $7, -8(%rbp)
  5080. movq -8(%rbp), -16(%rbp)
  5081. movq -8(%rbp), -8(%rbp)
  5082. addq %rcx, -8(%rbp)
  5083. movq -16(%rbp), %rcx
  5084. negq %rcx
  5085. movq -8(%rbp), %rax
  5086. addq %rcx, %rax
  5087. jmp conclusion
  5088. \end{lstlisting}
  5089. \end{minipage}
  5090. $\Rightarrow\qquad$
  5091. \begin{minipage}{0.45\textwidth}
  5092. \begin{lstlisting}
  5093. movq $1, -8(%rbp)
  5094. movq $42, %rcx
  5095. addq $7, -8(%rbp)
  5096. movq -8(%rbp), %rax
  5097. movq %rax, -16(%rbp)
  5098. addq %rcx, -8(%rbp)
  5099. movq -16(%rbp), %rcx
  5100. negq %rcx
  5101. movq -8(%rbp), %rax
  5102. addq %rcx, %rax
  5103. jmp conclusion
  5104. \end{lstlisting}
  5105. \end{minipage}
  5106. \fi}
  5107. {\if\edition\pythonEd
  5108. \begin{minipage}{0.4\textwidth}
  5109. \begin{lstlisting}
  5110. movq $1, -8(%rbp)
  5111. movq $42, %rcx
  5112. movq -8(%rbp), -8(%rbp)
  5113. addq $7, -8(%rbp)
  5114. movq -8(%rbp), -16(%rbp)
  5115. movq -8(%rbp), -8(%rbp)
  5116. addq %rcx, -8(%rbp)
  5117. movq -16(%rbp), %rcx
  5118. negq %rcx
  5119. movq -8(%rbp), -8(%rbp)
  5120. addq %rcx, -8(%rbp)
  5121. movq -8(%rbp), %rdi
  5122. callq print_int
  5123. \end{lstlisting}
  5124. \end{minipage}
  5125. $\Rightarrow\qquad$
  5126. \begin{minipage}{0.45\textwidth}
  5127. \begin{lstlisting}
  5128. movq $1, -8(%rbp)
  5129. movq $42, %rcx
  5130. addq $7, -8(%rbp)
  5131. movq -8(%rbp), %rax
  5132. movq %rax, -16(%rbp)
  5133. addq %rcx, -8(%rbp)
  5134. movq -16(%rbp), %rcx
  5135. negq %rcx
  5136. addq %rcx, -8(%rbp)
  5137. movq -8(%rbp), %rdi
  5138. callq print_int
  5139. \end{lstlisting}
  5140. \end{minipage}
  5141. \fi}
  5142. \end{center}
  5143. \begin{exercise}\normalfont
  5144. %
  5145. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5146. %
  5147. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5148. %in the \code{run-tests.rkt} script.
  5149. %
  5150. Run the script to test the \code{patch\_instructions} pass.
  5151. \end{exercise}
  5152. \section{Prelude and Conclusion}
  5153. \label{sec:print-x86-reg-alloc}
  5154. \index{subject}{calling conventions}
  5155. \index{subject}{prelude}\index{subject}{conclusion}
  5156. Recall that this pass generates the prelude and conclusion
  5157. instructions to satisfy the x86 calling conventions
  5158. (Section~\ref{sec:calling-conventions}). With the addition of the
  5159. register allocator, the callee-saved registers used by the register
  5160. allocator must be saved in the prelude and restored in the conclusion.
  5161. In the \code{allocate\_registers} pass,
  5162. %
  5163. \racket{add an entry to the \itm{info}
  5164. of \code{X86Program} named \code{used\_callee}}
  5165. %
  5166. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5167. %
  5168. that stores the set of callee-saved registers that were assigned to
  5169. variables. The \code{prelude\_and\_conclusion} pass can then access
  5170. this information to decide which callee-saved registers need to be
  5171. saved and restored.
  5172. %
  5173. When calculating the size of the frame to adjust the \code{rsp} in the
  5174. prelude, make sure to take into account the space used for saving the
  5175. callee-saved registers. Also, don't forget that the frame needs to be
  5176. a multiple of 16 bytes!
  5177. \racket{An overview of all of the passes involved in register
  5178. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5179. {\if\edition\racketEd
  5180. \begin{figure}[tbp]
  5181. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5182. \node (Lvar) at (0,2) {\large \LangVar{}};
  5183. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5184. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  5185. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5186. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5187. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5188. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5189. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5190. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5191. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5192. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5193. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5194. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5195. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5196. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5197. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5198. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5199. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5200. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  5201. \end{tikzpicture}
  5202. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5203. \label{fig:reg-alloc-passes}
  5204. \end{figure}
  5205. \fi}
  5206. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5207. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5208. use of registers and the stack, we limit the register allocator for
  5209. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5210. the prelude\index{subject}{prelude} of the \code{main} function, we
  5211. push \code{rbx} onto the stack because it is a callee-saved register
  5212. and it was assigned to variable by the register allocator. We
  5213. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5214. reserve space for the one spilled variable. After that subtraction,
  5215. the \code{rsp} is aligned to 16 bytes.
  5216. Moving on to the program proper, we see how the registers were
  5217. allocated.
  5218. %
  5219. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5220. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5221. %
  5222. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5223. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5224. were assigned to \code{rbx}.}
  5225. %
  5226. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5227. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5228. callee-save register \code{rbx} onto the stack. The spilled variables
  5229. must be placed lower on the stack than the saved callee-save
  5230. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5231. \code{-16(\%rbp)}.
  5232. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5233. done in the prelude. We move the stack pointer up by \code{8} bytes
  5234. (the room for spilled variables), then we pop the old values of
  5235. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5236. \code{retq} to return control to the operating system.
  5237. \begin{figure}[tbp]
  5238. % var_test_28.rkt
  5239. % (use-minimal-set-of-registers! #t)
  5240. % and only rbx rcx
  5241. % tmp 0 rbx
  5242. % z 1 rcx
  5243. % y 0 rbx
  5244. % w 2 16(%rbp)
  5245. % v 0 rbx
  5246. % x 0 rbx
  5247. {\if\edition\racketEd
  5248. \begin{lstlisting}
  5249. start:
  5250. movq $1, %rbx
  5251. movq $42, -16(%rbp)
  5252. addq $7, %rbx
  5253. movq %rbx, %rcx
  5254. addq -16(%rbp), %rcx
  5255. negq %rbx
  5256. movq %rcx, %rax
  5257. addq %rbx, %rax
  5258. jmp conclusion
  5259. .globl main
  5260. main:
  5261. pushq %rbp
  5262. movq %rsp, %rbp
  5263. pushq %rbx
  5264. subq $8, %rsp
  5265. jmp start
  5266. conclusion:
  5267. addq $8, %rsp
  5268. popq %rbx
  5269. popq %rbp
  5270. retq
  5271. \end{lstlisting}
  5272. \fi}
  5273. {\if\edition\pythonEd
  5274. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5275. \begin{lstlisting}
  5276. .globl main
  5277. main:
  5278. pushq %rbp
  5279. movq %rsp, %rbp
  5280. pushq %rbx
  5281. subq $8, %rsp
  5282. movq $1, %rcx
  5283. movq $42, %rbx
  5284. addq $7, %rcx
  5285. movq %rcx, -16(%rbp)
  5286. addq %rbx, -16(%rbp)
  5287. negq %rcx
  5288. movq -16(%rbp), %rbx
  5289. addq %rcx, %rbx
  5290. movq %rbx, %rdi
  5291. callq print_int
  5292. addq $8, %rsp
  5293. popq %rbx
  5294. popq %rbp
  5295. retq
  5296. \end{lstlisting}
  5297. \fi}
  5298. \caption{The x86 output from the running example
  5299. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5300. and \code{rcx}.}
  5301. \label{fig:running-example-x86}
  5302. \end{figure}
  5303. \begin{exercise}\normalfont
  5304. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5305. %
  5306. \racket{
  5307. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5308. list of passes and the call to \code{compiler-tests}.}
  5309. %
  5310. Run the script to test the complete compiler for \LangVar{} that
  5311. performs register allocation.
  5312. \end{exercise}
  5313. \section{Challenge: Move Biasing}
  5314. \label{sec:move-biasing}
  5315. \index{subject}{move biasing}
  5316. This section describes an enhancement to the register allocator,
  5317. called move biasing, for students who are looking for an extra
  5318. challenge.
  5319. {\if\edition\racketEd
  5320. To motivate the need for move biasing we return to the running example
  5321. but this time use all of the general purpose registers. So we have
  5322. the following mapping of color numbers to registers.
  5323. \[
  5324. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  5325. \]
  5326. Using the same assignment of variables to color numbers that was
  5327. produced by the register allocator described in the last section, we
  5328. get the following program.
  5329. \begin{center}
  5330. \begin{minipage}{0.3\textwidth}
  5331. \begin{lstlisting}
  5332. movq $1, v
  5333. movq $42, w
  5334. movq v, x
  5335. addq $7, x
  5336. movq x, y
  5337. movq x, z
  5338. addq w, z
  5339. movq y, t
  5340. negq t
  5341. movq z, %rax
  5342. addq t, %rax
  5343. jmp conclusion
  5344. \end{lstlisting}
  5345. \end{minipage}
  5346. $\Rightarrow\qquad$
  5347. \begin{minipage}{0.45\textwidth}
  5348. \begin{lstlisting}
  5349. movq $1, %rdx
  5350. movq $42, %rcx
  5351. movq %rdx, %rdx
  5352. addq $7, %rdx
  5353. movq %rdx, %rsi
  5354. movq %rdx, %rdx
  5355. addq %rcx, %rdx
  5356. movq %rsi, %rcx
  5357. negq %rcx
  5358. movq %rdx, %rax
  5359. addq %rcx, %rax
  5360. jmp conclusion
  5361. \end{lstlisting}
  5362. \end{minipage}
  5363. \end{center}
  5364. In the above output code there are two \key{movq} instructions that
  5365. can be removed because their source and target are the same. However,
  5366. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5367. register, we could instead remove three \key{movq} instructions. We
  5368. can accomplish this by taking into account which variables appear in
  5369. \key{movq} instructions with which other variables.
  5370. \fi}
  5371. {\if\edition\pythonEd
  5372. %
  5373. To motivate the need for move biasing we return to the running example
  5374. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5375. remove three trivial move instructions from the running
  5376. example. However, we could remove another trivial move if we were able
  5377. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5378. We say that two variables $p$ and $q$ are \emph{move
  5379. related}\index{subject}{move related} if they participate together in
  5380. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5381. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5382. when there are multiple variables with the same saturation, prefer
  5383. variables that can be assigned to a color that is the same as the
  5384. color of a move related variable. Furthermore, when the register
  5385. allocator chooses a color for a variable, it should prefer a color
  5386. that has already been used for a move-related variable (assuming that
  5387. they do not interfere). Of course, this preference should not override
  5388. the preference for registers over stack locations. So this preference
  5389. should be used as a tie breaker when choosing between registers or
  5390. when choosing between stack locations.
  5391. We recommend representing the move relationships in a graph, similar
  5392. to how we represented interference. The following is the \emph{move
  5393. graph} for our running example.
  5394. {\if\edition\racketEd
  5395. \[
  5396. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5397. \node (rax) at (0,0) {$\ttm{rax}$};
  5398. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5399. \node (t) at (0,2) {$\ttm{t}$};
  5400. \node (z) at (3,2) {$\ttm{z}$};
  5401. \node (x) at (6,2) {$\ttm{x}$};
  5402. \node (y) at (3,0) {$\ttm{y}$};
  5403. \node (w) at (6,0) {$\ttm{w}$};
  5404. \node (v) at (9,0) {$\ttm{v}$};
  5405. \draw (v) to (x);
  5406. \draw (x) to (y);
  5407. \draw (x) to (z);
  5408. \draw (y) to (t);
  5409. \end{tikzpicture}
  5410. \]
  5411. \fi}
  5412. %
  5413. {\if\edition\pythonEd
  5414. \[
  5415. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5416. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5417. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5418. \node (z) at (3,2) {$\ttm{z}$};
  5419. \node (x) at (6,2) {$\ttm{x}$};
  5420. \node (y) at (3,0) {$\ttm{y}$};
  5421. \node (w) at (6,0) {$\ttm{w}$};
  5422. \node (v) at (9,0) {$\ttm{v}$};
  5423. \draw (y) to (t0);
  5424. \draw (z) to (x);
  5425. \draw (z) to (t1);
  5426. \draw (x) to (y);
  5427. \draw (x) to (v);
  5428. \end{tikzpicture}
  5429. \]
  5430. \fi}
  5431. {\if\edition\racketEd
  5432. Now we replay the graph coloring, pausing to see the coloring of
  5433. \code{y}. Recall the following configuration. The most saturated vertices
  5434. were \code{w} and \code{y}.
  5435. \[
  5436. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5437. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5438. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5439. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5440. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5441. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5442. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5443. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5444. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5445. \draw (t1) to (rax);
  5446. \draw (t1) to (z);
  5447. \draw (z) to (y);
  5448. \draw (z) to (w);
  5449. \draw (x) to (w);
  5450. \draw (y) to (w);
  5451. \draw (v) to (w);
  5452. \draw (v) to (rsp);
  5453. \draw (w) to (rsp);
  5454. \draw (x) to (rsp);
  5455. \draw (y) to (rsp);
  5456. \path[-.,bend left=15] (z) edge node {} (rsp);
  5457. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5458. \draw (rax) to (rsp);
  5459. \end{tikzpicture}
  5460. \]
  5461. %
  5462. Last time we chose to color \code{w} with $0$. But this time we see
  5463. that \code{w} is not move related to any vertex, but \code{y} is move
  5464. related to \code{t}. So we choose to color \code{y} the same color as
  5465. \code{t}, $0$.
  5466. \[
  5467. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5468. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5469. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5470. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5471. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5472. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5473. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5474. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5475. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5476. \draw (t1) to (rax);
  5477. \draw (t1) to (z);
  5478. \draw (z) to (y);
  5479. \draw (z) to (w);
  5480. \draw (x) to (w);
  5481. \draw (y) to (w);
  5482. \draw (v) to (w);
  5483. \draw (v) to (rsp);
  5484. \draw (w) to (rsp);
  5485. \draw (x) to (rsp);
  5486. \draw (y) to (rsp);
  5487. \path[-.,bend left=15] (z) edge node {} (rsp);
  5488. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5489. \draw (rax) to (rsp);
  5490. \end{tikzpicture}
  5491. \]
  5492. Now \code{w} is the most saturated, so we color it $2$.
  5493. \[
  5494. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5495. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5496. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5497. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5498. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5499. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5500. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5501. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5502. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5503. \draw (t1) to (rax);
  5504. \draw (t1) to (z);
  5505. \draw (z) to (y);
  5506. \draw (z) to (w);
  5507. \draw (x) to (w);
  5508. \draw (y) to (w);
  5509. \draw (v) to (w);
  5510. \draw (v) to (rsp);
  5511. \draw (w) to (rsp);
  5512. \draw (x) to (rsp);
  5513. \draw (y) to (rsp);
  5514. \path[-.,bend left=15] (z) edge node {} (rsp);
  5515. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5516. \draw (rax) to (rsp);
  5517. \end{tikzpicture}
  5518. \]
  5519. At this point, vertices \code{x} and \code{v} are most saturated, but
  5520. \code{x} is move related to \code{y} and \code{z}, so we color
  5521. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5522. \[
  5523. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5524. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5525. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5526. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5527. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5528. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5529. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5530. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5531. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5532. \draw (t1) to (rax);
  5533. \draw (t) to (z);
  5534. \draw (z) to (y);
  5535. \draw (z) to (w);
  5536. \draw (x) to (w);
  5537. \draw (y) to (w);
  5538. \draw (v) to (w);
  5539. \draw (v) to (rsp);
  5540. \draw (w) to (rsp);
  5541. \draw (x) to (rsp);
  5542. \draw (y) to (rsp);
  5543. \path[-.,bend left=15] (z) edge node {} (rsp);
  5544. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5545. \draw (rax) to (rsp);
  5546. \end{tikzpicture}
  5547. \]
  5548. \fi}
  5549. %
  5550. {\if\edition\pythonEd
  5551. Now we replay the graph coloring, pausing before the coloring of
  5552. \code{w}. Recall the following configuration. The most saturated vertices
  5553. were \code{tmp\_1}, \code{w}, and \code{y}.
  5554. \[
  5555. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5556. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5557. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5558. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5559. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5560. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5561. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5562. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5563. \draw (t0) to (t1);
  5564. \draw (t0) to (z);
  5565. \draw (z) to (y);
  5566. \draw (z) to (w);
  5567. \draw (x) to (w);
  5568. \draw (y) to (w);
  5569. \draw (v) to (w);
  5570. \end{tikzpicture}
  5571. \]
  5572. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5573. or \code{y}, but note that \code{w} is not move related to any
  5574. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5575. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5576. \code{y} and color it $0$, we can delete another move instruction.
  5577. \[
  5578. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5579. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5580. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5581. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5582. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5583. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5584. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5585. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5586. \draw (t0) to (t1);
  5587. \draw (t0) to (z);
  5588. \draw (z) to (y);
  5589. \draw (z) to (w);
  5590. \draw (x) to (w);
  5591. \draw (y) to (w);
  5592. \draw (v) to (w);
  5593. \end{tikzpicture}
  5594. \]
  5595. Now \code{w} is the most saturated, so we color it $2$.
  5596. \[
  5597. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5598. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5599. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5600. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5601. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5602. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5603. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5604. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5605. \draw (t0) to (t1);
  5606. \draw (t0) to (z);
  5607. \draw (z) to (y);
  5608. \draw (z) to (w);
  5609. \draw (x) to (w);
  5610. \draw (y) to (w);
  5611. \draw (v) to (w);
  5612. \end{tikzpicture}
  5613. \]
  5614. To finish the coloring, \code{x} and \code{v} get $0$ and
  5615. \code{tmp\_1} gets $1$.
  5616. \[
  5617. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5618. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5619. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5620. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5621. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5622. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5623. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5624. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5625. \draw (t0) to (t1);
  5626. \draw (t0) to (z);
  5627. \draw (z) to (y);
  5628. \draw (z) to (w);
  5629. \draw (x) to (w);
  5630. \draw (y) to (w);
  5631. \draw (v) to (w);
  5632. \end{tikzpicture}
  5633. \]
  5634. \fi}
  5635. So we have the following assignment of variables to registers.
  5636. {\if\edition\racketEd
  5637. \begin{gather*}
  5638. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5639. \ttm{w} \mapsto \key{\%rsi}, \,
  5640. \ttm{x} \mapsto \key{\%rcx}, \,
  5641. \ttm{y} \mapsto \key{\%rcx}, \,
  5642. \ttm{z} \mapsto \key{\%rdx}, \,
  5643. \ttm{t} \mapsto \key{\%rcx} \}
  5644. \end{gather*}
  5645. \fi}
  5646. {\if\edition\pythonEd
  5647. \begin{gather*}
  5648. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5649. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5650. \ttm{x} \mapsto \key{\%rcx}, \,
  5651. \ttm{y} \mapsto \key{\%rcx}, \\
  5652. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5653. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5654. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5655. \end{gather*}
  5656. \fi}
  5657. We apply this register assignment to the running example, on the left,
  5658. to obtain the code in the middle. The \code{patch\_instructions} then
  5659. deletes the trivial moves to obtain the code on the right.
  5660. {\if\edition\racketEd
  5661. \begin{minipage}{0.25\textwidth}
  5662. \begin{lstlisting}
  5663. movq $1, v
  5664. movq $42, w
  5665. movq v, x
  5666. addq $7, x
  5667. movq x, y
  5668. movq x, z
  5669. addq w, z
  5670. movq y, t
  5671. negq t
  5672. movq z, %rax
  5673. addq t, %rax
  5674. jmp conclusion
  5675. \end{lstlisting}
  5676. \end{minipage}
  5677. $\Rightarrow\qquad$
  5678. \begin{minipage}{0.25\textwidth}
  5679. \begin{lstlisting}
  5680. movq $1, %rcx
  5681. movq $42, %rsi
  5682. movq %rcx, %rcx
  5683. addq $7, %rcx
  5684. movq %rcx, %rcx
  5685. movq %rcx, %rdx
  5686. addq %rsi, %rdx
  5687. movq %rcx, %rcx
  5688. negq %rcx
  5689. movq %rdx, %rax
  5690. addq %rcx, %rax
  5691. jmp conclusion
  5692. \end{lstlisting}
  5693. \end{minipage}
  5694. $\Rightarrow\qquad$
  5695. \begin{minipage}{0.25\textwidth}
  5696. \begin{lstlisting}
  5697. movq $1, %rcx
  5698. movq $42, %rsi
  5699. addq $7, %rcx
  5700. movq %rcx, %rdx
  5701. addq %rsi, %rdx
  5702. negq %rcx
  5703. movq %rdx, %rax
  5704. addq %rcx, %rax
  5705. jmp conclusion
  5706. \end{lstlisting}
  5707. \end{minipage}
  5708. \fi}
  5709. {\if\edition\pythonEd
  5710. \begin{minipage}{0.20\textwidth}
  5711. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5712. movq $1, v
  5713. movq $42, w
  5714. movq v, x
  5715. addq $7, x
  5716. movq x, y
  5717. movq x, z
  5718. addq w, z
  5719. movq y, tmp_0
  5720. negq tmp_0
  5721. movq z, tmp_1
  5722. addq tmp_0, tmp_1
  5723. movq tmp_1, %rdi
  5724. callq _print_int
  5725. \end{lstlisting}
  5726. \end{minipage}
  5727. ${\Rightarrow\qquad}$
  5728. \begin{minipage}{0.30\textwidth}
  5729. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5730. movq $1, %rcx
  5731. movq $42, -16(%rbp)
  5732. movq %rcx, %rcx
  5733. addq $7, %rcx
  5734. movq %rcx, %rcx
  5735. movq %rcx, -8(%rbp)
  5736. addq -16(%rbp), -8(%rbp)
  5737. movq %rcx, %rcx
  5738. negq %rcx
  5739. movq -8(%rbp), -8(%rbp)
  5740. addq %rcx, -8(%rbp)
  5741. movq -8(%rbp), %rdi
  5742. callq _print_int
  5743. \end{lstlisting}
  5744. \end{minipage}
  5745. ${\Rightarrow\qquad}$
  5746. \begin{minipage}{0.20\textwidth}
  5747. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5748. movq $1, %rcx
  5749. movq $42, -16(%rbp)
  5750. addq $7, %rcx
  5751. movq %rcx, -8(%rbp)
  5752. movq -16(%rbp), %rax
  5753. addq %rax, -8(%rbp)
  5754. negq %rcx
  5755. addq %rcx, -8(%rbp)
  5756. movq -8(%rbp), %rdi
  5757. callq print_int
  5758. \end{lstlisting}
  5759. \end{minipage}
  5760. \fi}
  5761. \begin{exercise}\normalfont
  5762. Change your implementation of \code{allocate\_registers} to take move
  5763. biasing into account. Create two new tests that include at least one
  5764. opportunity for move biasing and visually inspect the output x86
  5765. programs to make sure that your move biasing is working properly. Make
  5766. sure that your compiler still passes all of the tests.
  5767. \end{exercise}
  5768. %To do: another neat challenge would be to do
  5769. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5770. %% \subsection{Output of the Running Example}
  5771. %% \label{sec:reg-alloc-output}
  5772. % challenge: prioritize variables based on execution frequencies
  5773. % and the number of uses of a variable
  5774. % challenge: enhance the coloring algorithm using Chaitin's
  5775. % approach of prioritizing high-degree variables
  5776. % by removing low-degree variables (coloring them later)
  5777. % from the interference graph
  5778. \section{Further Reading}
  5779. \label{sec:register-allocation-further-reading}
  5780. Early register allocation algorithms were developed for Fortran
  5781. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5782. of graph coloring began in the late 1970s and early 1980s with the
  5783. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5784. algorithm is based on the following observation of
  5785. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5786. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5787. $v$ removed is also $k$ colorable. To see why, suppose that the
  5788. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5789. different colors, but since there are less than $k$ neighbors, there
  5790. will be one or more colors left over to use for coloring $v$ in $G$.
  5791. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5792. less than $k$ from the graph and recursively colors the rest of the
  5793. graph. Upon returning from the recursion, it colors $v$ with one of
  5794. the available colors and returns. \citet{Chaitin:1982vn} augments
  5795. this algorithm to handle spilling as follows. If there are no vertices
  5796. of degree lower than $k$ then pick a vertex at random, spill it,
  5797. remove it from the graph, and proceed recursively to color the rest of
  5798. the graph.
  5799. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5800. move-related and that don't interfere with each other, a process
  5801. called \emph{coalescing}. While coalescing decreases the number of
  5802. moves, it can make the graph more difficult to
  5803. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5804. which two variables are merged only if they have fewer than $k$
  5805. neighbors of high degree. \citet{George:1996aa} observe that
  5806. conservative coalescing is sometimes too conservative and make it more
  5807. aggressive by iterating the coalescing with the removal of low-degree
  5808. vertices.
  5809. %
  5810. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5811. also propose \emph{biased coloring} in which a variable is assigned to
  5812. the same color as another move-related variable if possible, as
  5813. discussed in Section~\ref{sec:move-biasing}.
  5814. %
  5815. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5816. performs coalescing, graph coloring, and spill code insertion until
  5817. all variables have been assigned a location.
  5818. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5819. spills variables that don't have to be: a high-degree variable can be
  5820. colorable if many of its neighbors are assigned the same color.
  5821. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5822. high-degree vertex is not immediately spilled. Instead the decision is
  5823. deferred until after the recursive call, at which point it is apparent
  5824. whether there is actually an available color or not. We observe that
  5825. this algorithm is equivalent to the smallest-last ordering
  5826. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5827. be registers and the rest to be stack locations.
  5828. %% biased coloring
  5829. Earlier editions of the compiler course at Indiana University
  5830. \citep{Dybvig:2010aa} were based on the algorithm of
  5831. \citet{Briggs:1994kx}.
  5832. The smallest-last ordering algorithm is one of many \emph{greedy}
  5833. coloring algorithms. A greedy coloring algorithm visits all the
  5834. vertices in a particular order and assigns each one the first
  5835. available color. An \emph{offline} greedy algorithm chooses the
  5836. ordering up-front, prior to assigning colors. The algorithm of
  5837. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5838. ordering does not depend on the colors assigned. Other orderings are
  5839. possible. For example, \citet{Chow:1984ys} order variables according
  5840. to an estimate of runtime cost.
  5841. An \emph{online} greedy coloring algorithm uses information about the
  5842. current assignment of colors to influence the order in which the
  5843. remaining vertices are colored. The saturation-based algorithm
  5844. described in this chapter is one such algorithm. We choose to use
  5845. saturation-based coloring because it is fun to introduce graph
  5846. coloring via Sudoku!
  5847. A register allocator may choose to map each variable to just one
  5848. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5849. variable to one or more locations. The later can be achieved by
  5850. \emph{live range splitting}, where a variable is replaced by several
  5851. variables that each handle part of its live
  5852. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5853. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5854. %% replacement algorithm, bottom-up local
  5855. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5856. %% Cooper: top-down (priority bassed), bottom-up
  5857. %% top-down
  5858. %% order variables by priority (estimated cost)
  5859. %% caveat: split variables into two groups:
  5860. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5861. %% color the constrained ones first
  5862. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5863. %% cite J. Cocke for an algorithm that colors variables
  5864. %% in a high-degree first ordering
  5865. %Register Allocation via Usage Counts, Freiburghouse CACM
  5866. \citet{Palsberg:2007si} observe that many of the interference graphs
  5867. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5868. that is, every cycle with four or more edges has an edge which is not
  5869. part of the cycle but which connects two vertices on the cycle. Such
  5870. graphs can be optimally colored by the greedy algorithm with a vertex
  5871. ordering determined by maximum cardinality search.
  5872. In situations where compile time is of utmost importance, such as in
  5873. just-in-time compilers, graph coloring algorithms can be too expensive
  5874. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  5875. appropriate.
  5876. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5877. \chapter{Booleans and Conditionals}
  5878. \label{ch:Lif}
  5879. \index{subject}{Boolean}
  5880. \index{subject}{control flow}
  5881. \index{subject}{conditional expression}
  5882. The \LangInt{} and \LangVar{} languages only have a single kind of
  5883. value, the integers. In this chapter we add a second kind of value,
  5884. the Booleans, to create the \LangIf{} language. The Boolean values
  5885. \emph{true} and \emph{false} are written \TRUE{} and \FALSE{}
  5886. respectively in \racket{Racket}\python{Python}. The \LangIf{}
  5887. language includes several operations that involve Booleans (\key{and},
  5888. \key{not}, \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the
  5889. \key{if} expression \python{and statement}. With the addition of
  5890. \key{if}, programs can have non-trivial control flow which
  5891. %
  5892. \racket{impacts \code{explicate\_control} and liveness analysis}
  5893. %
  5894. \python{impacts liveness analysis and motivates a new pass named
  5895. \code{explicate\_control}}.
  5896. %
  5897. Also, because we now have two kinds of values, we need to handle
  5898. programs that apply an operation to the wrong kind of value, such as
  5899. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5900. There are two language design options for such situations. One option
  5901. is to signal an error and the other is to provide a wider
  5902. interpretation of the operation. \racket{The Racket
  5903. language}\python{Python} uses a mixture of these two options,
  5904. depending on the operation and the kind of value. For example, the
  5905. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  5906. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  5907. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  5908. %
  5909. \racket{On the other hand, \code{(car 1)} results in a run-time error
  5910. in Racket because \code{car} expects a pair.}
  5911. %
  5912. \python{On the other hand, \code{1[0]} results in a run-time error
  5913. in Python because an ``\code{int} object is not subscriptable''.}
  5914. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  5915. design choices as \racket{Racket}\python{Python}, except much of the
  5916. error detection happens at compile time instead of run
  5917. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  5918. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  5919. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  5920. Racket}\python{MyPy} reports a compile-time error
  5921. %
  5922. \racket{because Racket expects the type of the argument to be of the form
  5923. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  5924. %
  5925. \python{stating that a ``value of type \code{int} is not indexable''.}
  5926. The \LangIf{} language performs type checking during compilation like
  5927. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Rdyn} we study the
  5928. alternative choice, that is, a dynamically typed language like
  5929. \racket{Racket}\python{Python}.
  5930. The \LangIf{} language is a subset of \racket{Typed Racket}\python{MyPy};
  5931. for some operations we are more restrictive, for example, rejecting
  5932. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5933. This chapter is organized as follows. We begin by defining the syntax
  5934. and interpreter for the \LangIf{} language
  5935. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  5936. checking and define a type checker for \LangIf{}
  5937. (Section~\ref{sec:type-check-Lif}).
  5938. %
  5939. \racket{To compile \LangIf{} we need to enlarge the intermediate
  5940. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  5941. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  5942. %
  5943. The remaining sections of this chapter discuss how the addition of
  5944. Booleans and conditional control flow to the language requires changes
  5945. to the existing compiler passes and the addition of new ones. In
  5946. particular, we introduce the \code{shrink} pass to translates some
  5947. operators into others, thereby reducing the number of operators that
  5948. need to be handled in later passes.
  5949. %
  5950. The main event of this chapter is the \code{explicate\_control} pass
  5951. that is responsible for translating \code{if}'s into conditional
  5952. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  5953. %
  5954. Regarding register allocation, there is the interesting question of
  5955. how to handle conditional \code{goto}'s during liveness analysis.
  5956. \section{The \LangIf{} Language}
  5957. \label{sec:lang-if}
  5958. The concrete syntax of the \LangIf{} language is defined in
  5959. Figure~\ref{fig:Lif-concrete-syntax} and the abstract syntax is defined
  5960. in Figure~\ref{fig:Lif-syntax}. The \LangIf{} language includes all of
  5961. \LangVar{}\racket{(shown in gray)}, the Boolean literals \TRUE{} and
  5962. \FALSE{}, and the \code{if} expression \python{and statement}. We expand the
  5963. operators to include
  5964. \begin{enumerate}
  5965. \item subtraction on integers,
  5966. \item the logical operators \key{and}, \key{or}, and \key{not},
  5967. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  5968. for comparing integers or Booleans for equality, and
  5969. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  5970. comparing integers.
  5971. \end{enumerate}
  5972. \racket{We reorganize the abstract syntax for the primitive
  5973. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  5974. rule for all of them. This means that the grammar no longer checks
  5975. whether the arity of an operators matches the number of
  5976. arguments. That responsibility is moved to the type checker for
  5977. \LangIf{}, which we introduce in Section~\ref{sec:type-check-Lif}.}
  5978. \newcommand{\LifGrammarRacket}{
  5979. \begin{array}{lcl}
  5980. \Type &::=& \key{Boolean} \\
  5981. \itm{bool} &::=& \TRUE \MID \FALSE \\
  5982. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5983. \Exp &::=& \CSUB{\Exp}{\Exp} \MID \itm{bool}
  5984. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  5985. \MID (\key{not}\;\Exp) \\
  5986. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  5987. \end{array}
  5988. }
  5989. \newcommand{\LifAST}{
  5990. \begin{array}{lcl}
  5991. \Type &::=& \key{Boolean} \\
  5992. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  5993. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  5994. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  5995. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  5996. \end{array}
  5997. }
  5998. \newcommand{\LintOpAST}{
  5999. \begin{array}{rcl}
  6000. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6001. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6002. \end{array}
  6003. }
  6004. \newcommand{\LifGrammarPython}{
  6005. \begin{array}{rcl}
  6006. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6007. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6008. \MID \key{not}~\Exp \\
  6009. &\MID& \Exp ~\itm{cmp} ~\Exp
  6010. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6011. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6012. \end{array}
  6013. }
  6014. \newcommand{\LifASTPython}{
  6015. \begin{array}{lcl}
  6016. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6017. \itm{unaryop} &::=& \code{Not()} \\
  6018. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6019. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6020. \Exp &::=& \BOOL{\itm{bool}}
  6021. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6022. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6023. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6024. \end{array}
  6025. }
  6026. \begin{figure}[tp]
  6027. \centering
  6028. \fbox{
  6029. \begin{minipage}{0.96\textwidth}
  6030. {\if\edition\racketEd
  6031. \[
  6032. \begin{array}{l}
  6033. \gray{\LintGrammarRacket{}} \\ \hline
  6034. \gray{\LvarGrammarRacket{}} \\ \hline
  6035. \LifGrammarRacket{} \\
  6036. \begin{array}{lcl}
  6037. \LangIfM{} &::=& \Exp
  6038. \end{array}
  6039. \end{array}
  6040. \]
  6041. \fi}
  6042. {\if\edition\pythonEd
  6043. \[
  6044. \begin{array}{l}
  6045. \gray{\LintGrammarPython} \\ \hline
  6046. \gray{\LvarGrammarPython} \\ \hline
  6047. \LifGrammarPython \\
  6048. \begin{array}{rcl}
  6049. \LangIfM{} &::=& \Stmt^{*}
  6050. \end{array}
  6051. \end{array}
  6052. \]
  6053. \fi}
  6054. \end{minipage}
  6055. }
  6056. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6057. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6058. \label{fig:Lif-concrete-syntax}
  6059. \end{figure}
  6060. \begin{figure}[tp]
  6061. \centering
  6062. \fbox{
  6063. \begin{minipage}{0.96\textwidth}
  6064. {\if\edition\racketEd
  6065. \[
  6066. \begin{array}{l}
  6067. \gray{\LintOpAST} \\ \hline
  6068. \gray{\LvarAST{}} \\ \hline
  6069. \LifAST{} \\
  6070. \begin{array}{lcl}
  6071. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6072. \end{array}
  6073. \end{array}
  6074. \]
  6075. \fi}
  6076. {\if\edition\pythonEd
  6077. \[
  6078. \begin{array}{l}
  6079. \gray{\LintASTPython} \\ \hline
  6080. \gray{\LvarASTPython} \\ \hline
  6081. \LifASTPython \\
  6082. \begin{array}{lcl}
  6083. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6084. \end{array}
  6085. \end{array}
  6086. \]
  6087. \fi}
  6088. \end{minipage}
  6089. }
  6090. \caption{The abstract syntax of \LangIf{}.}
  6091. \label{fig:Lif-syntax}
  6092. \end{figure}
  6093. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  6094. which inherits from the interpreter for \LangVar{}
  6095. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6096. evaluate to the corresponding Boolean values. The conditional
  6097. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  6098. and then either evaluates $e_2$ or $e_3$ depending on whether
  6099. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  6100. \code{and}, \code{or}, and \code{not} behave according to propositional logic,
  6101. but note that the \code{and} and \code{or} operations are
  6102. short-circuiting.
  6103. %
  6104. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6105. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6106. %
  6107. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6108. evaluated if $e_1$ evaluates to \TRUE{}.
  6109. \racket{With the increase in the number of primitive operations, the
  6110. interpreter would become repetitive without some care. We refactor
  6111. the case for \code{Prim}, moving the code that differs with each
  6112. operation into the \code{interp\_op} method shown in in
  6113. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6114. \code{or} operations separately because of their short-circuiting
  6115. behavior.}
  6116. \begin{figure}[tbp]
  6117. {\if\edition\racketEd
  6118. \begin{lstlisting}
  6119. (define interp_Lif_class
  6120. (class interp_Lvar_class
  6121. (super-new)
  6122. (define/public (interp_op op) ...)
  6123. (define/override ((interp_exp env) e)
  6124. (define recur (interp_exp env))
  6125. (match e
  6126. [(Bool b) b]
  6127. [(If cnd thn els)
  6128. (match (recur cnd)
  6129. [#t (recur thn)]
  6130. [#f (recur els)])]
  6131. [(Prim 'and (list e1 e2))
  6132. (match (recur e1)
  6133. [#t (match (recur e2) [#t #t] [#f #f])]
  6134. [#f #f])]
  6135. [(Prim 'or (list e1 e2))
  6136. (define v1 (recur e1))
  6137. (match v1
  6138. [#t #t]
  6139. [#f (match (recur e2) [#t #t] [#f #f])])]
  6140. [(Prim op args)
  6141. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6142. [else ((super interp_exp env) e)]))
  6143. ))
  6144. (define (interp_Lif p)
  6145. (send (new interp_Lif_class) interp_program p))
  6146. \end{lstlisting}
  6147. \fi}
  6148. {\if\edition\pythonEd
  6149. \begin{lstlisting}
  6150. class InterpLif(InterpLvar):
  6151. def interp_exp(self, e, env):
  6152. match e:
  6153. case IfExp(test, body, orelse):
  6154. if self.interp_exp(test, env):
  6155. return self.interp_exp(body, env)
  6156. else:
  6157. return self.interp_exp(orelse, env)
  6158. case BinOp(left, Sub(), right):
  6159. return self.interp_exp(left, env) - self.interp_exp(right, env)
  6160. case UnaryOp(Not(), v):
  6161. return not self.interp_exp(v, env)
  6162. case BoolOp(And(), values):
  6163. if self.interp_exp(values[0], env):
  6164. return self.interp_exp(values[1], env)
  6165. else:
  6166. return False
  6167. case BoolOp(Or(), values):
  6168. if self.interp_exp(values[0], env):
  6169. return True
  6170. else:
  6171. return self.interp_exp(values[1], env)
  6172. case Compare(left, [cmp], [right]):
  6173. l = self.interp_exp(left, env)
  6174. r = self.interp_exp(right, env)
  6175. return self.interp_cmp(cmp)(l, r)
  6176. case _:
  6177. return super().interp_exp(e, env)
  6178. def interp_stmts(self, ss, env):
  6179. if len(ss) == 0:
  6180. return
  6181. match ss[0]:
  6182. case If(test, body, orelse):
  6183. if self.interp_exp(test, env):
  6184. return self.interp_stmts(body + ss[1:], env)
  6185. else:
  6186. return self.interp_stmts(orelse + ss[1:], env)
  6187. case _:
  6188. return super().interp_stmts(ss, env)
  6189. ...
  6190. \end{lstlisting}
  6191. \fi}
  6192. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6193. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6194. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6195. \label{fig:interp-Lif}
  6196. \end{figure}
  6197. {\if\edition\racketEd
  6198. \begin{figure}[tbp]
  6199. \begin{lstlisting}
  6200. (define/public (interp_op op)
  6201. (match op
  6202. ['+ fx+]
  6203. ['- fx-]
  6204. ['read read-fixnum]
  6205. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6206. ['eq? (lambda (v1 v2)
  6207. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6208. (and (boolean? v1) (boolean? v2))
  6209. (and (vector? v1) (vector? v2)))
  6210. (eq? v1 v2)]))]
  6211. ['< (lambda (v1 v2)
  6212. (cond [(and (fixnum? v1) (fixnum? v2))
  6213. (< v1 v2)]))]
  6214. ['<= (lambda (v1 v2)
  6215. (cond [(and (fixnum? v1) (fixnum? v2))
  6216. (<= v1 v2)]))]
  6217. ['> (lambda (v1 v2)
  6218. (cond [(and (fixnum? v1) (fixnum? v2))
  6219. (> v1 v2)]))]
  6220. ['>= (lambda (v1 v2)
  6221. (cond [(and (fixnum? v1) (fixnum? v2))
  6222. (>= v1 v2)]))]
  6223. [else (error 'interp_op "unknown operator")]))
  6224. \end{lstlisting}
  6225. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6226. \label{fig:interp-op-Lif}
  6227. \end{figure}
  6228. \fi}
  6229. {\if\edition\pythonEd
  6230. \begin{figure}
  6231. \begin{lstlisting}
  6232. class InterpLif(InterpLvar):
  6233. ...
  6234. def interp_cmp(self, cmp):
  6235. match cmp:
  6236. case Lt():
  6237. return lambda x, y: x < y
  6238. case LtE():
  6239. return lambda x, y: x <= y
  6240. case Gt():
  6241. return lambda x, y: x > y
  6242. case GtE():
  6243. return lambda x, y: x >= y
  6244. case Eq():
  6245. return lambda x, y: x == y
  6246. case NotEq():
  6247. return lambda x, y: x != y
  6248. \end{lstlisting}
  6249. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6250. \label{fig:interp-cmp-Lif}
  6251. \end{figure}
  6252. \fi}
  6253. \section{Type Checking \LangIf{} Programs}
  6254. \label{sec:type-check-Lif}
  6255. \index{subject}{type checking}
  6256. \index{subject}{semantic analysis}
  6257. It is helpful to think about type checking in two complementary
  6258. ways. A type checker predicts the type of value that will be produced
  6259. by each expression in the program. For \LangIf{}, we have just two types,
  6260. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6261. {\if\edition\racketEd
  6262. \begin{lstlisting}
  6263. (+ 10 (- (+ 12 20)))
  6264. \end{lstlisting}
  6265. \fi}
  6266. {\if\edition\pythonEd
  6267. \begin{lstlisting}
  6268. 10 + -(12 + 20)
  6269. \end{lstlisting}
  6270. \fi}
  6271. \noindent produces a value of type \INTTY{} while
  6272. {\if\edition\racketEd
  6273. \begin{lstlisting}
  6274. (and (not #f) #t)
  6275. \end{lstlisting}
  6276. \fi}
  6277. {\if\edition\pythonEd
  6278. \begin{lstlisting}
  6279. (not False) and True
  6280. \end{lstlisting}
  6281. \fi}
  6282. \noindent produces a value of type \BOOLTY{}.
  6283. A second way to think about type checking is that it enforces a set of
  6284. rules about which operators can be applied to which kinds of
  6285. values. For example, our type checker for \LangIf{} signals an error
  6286. for the below expression {\if\edition\racketEd
  6287. \begin{lstlisting}
  6288. (not (+ 10 (- (+ 12 20))))
  6289. \end{lstlisting}
  6290. \fi}
  6291. {\if\edition\pythonEd
  6292. \begin{lstlisting}
  6293. not (10 + -(12 + 20))
  6294. \end{lstlisting}
  6295. \fi}
  6296. The subexpression
  6297. \racket{\code{(+ 10 (- (+ 12 20)))}}\python{\code{(10 + -(12 + 20))}}
  6298. has type \INTTY{} but the type checker enforces the rule that the argument of
  6299. \code{not} must be an expression of type \BOOLTY{}.
  6300. We implement type checking using classes and methods because they
  6301. provide the open recursion needed to reuse code as we extend the type
  6302. checker in later chapters, analogous to the use of classes and methods
  6303. for the interpreters (Section~\ref{sec:extensible-interp}).
  6304. We separate the type checker for the \LangVar{} subset into its own
  6305. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6306. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6307. from the type checker for \LangVar{}. These type checkers are in the
  6308. files
  6309. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6310. and
  6311. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6312. of the support code.
  6313. %
  6314. Each type checker is a structurally recursive function over the AST.
  6315. Given an input expression \code{e}, the type checker either signals an
  6316. error or returns \racket{an expression and} its type (\INTTY{} or
  6317. \BOOLTY{}).
  6318. %
  6319. \racket{It returns an expression because there are situations in which
  6320. we want to change or update the expression.}
  6321. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6322. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6323. \INTTY{}. To handle variables, the type checker uses the environment
  6324. \code{env} to map variables to types.
  6325. %
  6326. \racket{Consider the case for \key{let}. We type check the
  6327. initializing expression to obtain its type \key{T} and then
  6328. associate type \code{T} with the variable \code{x} in the
  6329. environment used to type check the body of the \key{let}. Thus,
  6330. when the type checker encounters a use of variable \code{x}, it can
  6331. find its type in the environment.}
  6332. %
  6333. \python{Consider the case for assignment. We type check the
  6334. initializing expression to obtain its type \key{t}. If the variable
  6335. \code{lhs.id} is already in the environment because there was a
  6336. prior assignment, we check that this initializer has the same type
  6337. as the prior one. If this is the first assignment to the variable,
  6338. we associate type \code{t} with the variable \code{lhs.id} in the
  6339. environment. Thus, when the type checker encounters a use of
  6340. variable \code{x}, it can find its type in the environment.}
  6341. %
  6342. \racket{Regarding primitive operators, we recursively analyze the
  6343. arguments and then invoke \code{type\_check\_op} to check whether
  6344. the argument types are allowed.}
  6345. %
  6346. \python{Regarding addition and negation, we recursively analyze the
  6347. arguments, check that they have type \INT{}, and return \INT{}.}
  6348. \racket{Several auxiliary methods are used in the type checker. The
  6349. method \code{operator-types} defines a dictionary that maps the
  6350. operator names to their parameter and return types. The
  6351. \code{type-equal?} method determines whether two types are equal,
  6352. which for now simply dispatches to \code{equal?} (deep
  6353. equality). The \code{check-type-equal?} method triggers an error if
  6354. the two types are not equal. The \code{type-check-op} method looks
  6355. up the operator in the \code{operator-types} dictionary and then
  6356. checks whether the argument types are equal to the parameter types.
  6357. The result is the return type of the operator.}
  6358. %
  6359. \python{The auxiliary method \code{check\_type\_equal} method triggers
  6360. an error if the two types are not equal.}
  6361. \begin{figure}[tbp]
  6362. {\if\edition\racketEd
  6363. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6364. (define type-check-Lvar_class
  6365. (class object%
  6366. (super-new)
  6367. (define/public (operator-types)
  6368. '((+ . ((Integer Integer) . Integer))
  6369. (- . ((Integer) . Integer))
  6370. (read . (() . Integer))))
  6371. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6372. (define/public (check-type-equal? t1 t2 e)
  6373. (unless (type-equal? t1 t2)
  6374. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6375. (define/public (type-check-op op arg-types e)
  6376. (match (dict-ref (operator-types) op)
  6377. [`(,param-types . ,return-type)
  6378. (for ([at arg-types] [pt param-types])
  6379. (check-type-equal? at pt e))
  6380. return-type]
  6381. [else (error 'type-check-op "unrecognized ~a" op)]))
  6382. (define/public (type-check-exp env)
  6383. (lambda (e)
  6384. (match e
  6385. [(Int n) (values (Int n) 'Integer)]
  6386. [(Var x) (values (Var x) (dict-ref env x))]
  6387. [(Let x e body)
  6388. (define-values (e^ Te) ((type-check-exp env) e))
  6389. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6390. (values (Let x e^ b) Tb)]
  6391. [(Prim op es)
  6392. (define-values (new-es ts)
  6393. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6394. (values (Prim op new-es) (type-check-op op ts e))]
  6395. [else (error 'type-check-exp "couldn't match" e)])))
  6396. (define/public (type-check-program e)
  6397. (match e
  6398. [(Program info body)
  6399. (define-values (body^ Tb) ((type-check-exp '()) body))
  6400. (check-type-equal? Tb 'Integer body)
  6401. (Program info body^)]
  6402. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6403. ))
  6404. (define (type-check-Lvar p)
  6405. (send (new type-check-Lvar_class) type-check-program p))
  6406. \end{lstlisting}
  6407. \fi}
  6408. {\if\edition\pythonEd
  6409. \begin{lstlisting}
  6410. class TypeCheckLvar:
  6411. def check_type_equal(self, t1, t2, e):
  6412. if t1 != t2:
  6413. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6414. raise Exception(msg)
  6415. def type_check_exp(self, e, env):
  6416. match e:
  6417. case BinOp(left, Add(), right):
  6418. l = self.type_check_exp(left, env)
  6419. check_type_equal(l, int, left)
  6420. r = self.type_check_exp(right, env)
  6421. check_type_equal(r, int, right)
  6422. return int
  6423. case UnaryOp(USub(), v):
  6424. t = self.type_check_exp(v, env)
  6425. check_type_equal(t, int, v)
  6426. return int
  6427. case Name(id):
  6428. return env[id]
  6429. case Constant(value) if isinstance(value, int):
  6430. return int
  6431. case Call(Name('input_int'), []):
  6432. return int
  6433. def type_check_stmts(self, ss, env):
  6434. if len(ss) == 0:
  6435. return
  6436. match ss[0]:
  6437. case Assign([lhs], value):
  6438. t = self.type_check_exp(value, env)
  6439. if lhs.id in env:
  6440. check_type_equal(env[lhs.id], t, value)
  6441. else:
  6442. env[lhs.id] = t
  6443. return self.type_check_stmts(ss[1:], env)
  6444. case Expr(Call(Name('print'), [arg])):
  6445. t = self.type_check_exp(arg, env)
  6446. check_type_equal(t, int, arg)
  6447. return self.type_check_stmts(ss[1:], env)
  6448. case Expr(value):
  6449. self.type_check_exp(value, env)
  6450. return self.type_check_stmts(ss[1:], env)
  6451. def type_check_P(self, p):
  6452. match p:
  6453. case Module(body):
  6454. self.type_check_stmts(body, {})
  6455. \end{lstlisting}
  6456. \fi}
  6457. \caption{Type checker for the \LangVar{} language.}
  6458. \label{fig:type-check-Lvar}
  6459. \end{figure}
  6460. \begin{figure}[tbp]
  6461. {\if\edition\racketEd
  6462. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6463. (define type-check-Lif_class
  6464. (class type-check-Lvar_class
  6465. (super-new)
  6466. (inherit check-type-equal?)
  6467. (define/override (operator-types)
  6468. (append '((- . ((Integer Integer) . Integer))
  6469. (and . ((Boolean Boolean) . Boolean))
  6470. (or . ((Boolean Boolean) . Boolean))
  6471. (< . ((Integer Integer) . Boolean))
  6472. (<= . ((Integer Integer) . Boolean))
  6473. (> . ((Integer Integer) . Boolean))
  6474. (>= . ((Integer Integer) . Boolean))
  6475. (not . ((Boolean) . Boolean))
  6476. )
  6477. (super operator-types)))
  6478. (define/override (type-check-exp env)
  6479. (lambda (e)
  6480. (match e
  6481. [(Bool b) (values (Bool b) 'Boolean)]
  6482. [(Prim 'eq? (list e1 e2))
  6483. (define-values (e1^ T1) ((type-check-exp env) e1))
  6484. (define-values (e2^ T2) ((type-check-exp env) e2))
  6485. (check-type-equal? T1 T2 e)
  6486. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6487. [(If cnd thn els)
  6488. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6489. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6490. (define-values (els^ Te) ((type-check-exp env) els))
  6491. (check-type-equal? Tc 'Boolean e)
  6492. (check-type-equal? Tt Te e)
  6493. (values (If cnd^ thn^ els^) Te)]
  6494. [else ((super type-check-exp env) e)])))
  6495. ))
  6496. (define (type-check-Lif p)
  6497. (send (new type-check-Lif_class) type-check-program p))
  6498. \end{lstlisting}
  6499. \fi}
  6500. {\if\edition\pythonEd
  6501. \begin{lstlisting}
  6502. class TypeCheckLif(TypeCheckLvar):
  6503. def type_check_exp(self, e, env):
  6504. match e:
  6505. case Constant(value) if isinstance(value, bool):
  6506. return bool
  6507. case BinOp(left, Sub(), right):
  6508. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6509. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6510. return int
  6511. case UnaryOp(Not(), v):
  6512. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6513. return bool
  6514. case BoolOp(op, values):
  6515. left = values[0] ; right = values[1]
  6516. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6517. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6518. return bool
  6519. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6520. or isinstance(cmp, NotEq):
  6521. l = self.type_check_exp(left, env)
  6522. r = self.type_check_exp(right, env)
  6523. check_type_equal(l, r, e)
  6524. return bool
  6525. case Compare(left, [cmp], [right]):
  6526. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6527. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6528. return bool
  6529. case IfExp(test, body, orelse):
  6530. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6531. b = self.type_check_exp(body, env)
  6532. o = self.type_check_exp(orelse, env)
  6533. check_type_equal(b, o, e)
  6534. return b
  6535. case _:
  6536. return super().type_check_exp(e, env)
  6537. def type_check_stmts(self, ss, env):
  6538. if len(ss) == 0:
  6539. return
  6540. match ss[0]:
  6541. case If(test, body, orelse):
  6542. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6543. b = self.type_check_stmts(body, env)
  6544. o = self.type_check_stmts(orelse, env)
  6545. check_type_equal(b, o, ss[0])
  6546. return self.type_check_stmts(ss[1:], env)
  6547. case _:
  6548. return super().type_check_stmts(ss, env)
  6549. \end{lstlisting}
  6550. \fi}
  6551. \caption{Type checker for the \LangIf{} language.}
  6552. \label{fig:type-check-Lif}
  6553. \end{figure}
  6554. We shift our focus to Figure~\ref{fig:type-check-Lif}, the type
  6555. checker for \LangIf{}.
  6556. %
  6557. The type of a Boolean constant is \BOOLTY{}.
  6558. %
  6559. \racket{The \code{operator-types} function adds dictionary entries for
  6560. the other new operators.}
  6561. %
  6562. \python{Subtraction requires its arguments to be of type \INTTY{} and produces
  6563. an \INTTY{}. Negation requires its argument to be a \BOOLTY{} and
  6564. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6565. %
  6566. The equality operators requires the two arguments to have the same
  6567. type.
  6568. %
  6569. \python{The other comparisons (less-than, etc.) require their
  6570. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6571. %
  6572. The condition of an \code{if} must
  6573. be of \BOOLTY{} type and the two branches must have the same type.
  6574. \begin{exercise}\normalfont
  6575. Create 10 new test programs in \LangIf{}. Half of the programs should
  6576. have a type error. For those programs, create an empty file with the
  6577. same base name but with file extension \code{.tyerr}. For example, if
  6578. the test
  6579. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6580. is expected to error, then create
  6581. an empty file named \code{cond\_test\_14.tyerr}.
  6582. %
  6583. \racket{This indicates to \code{interp-tests} and
  6584. \code{compiler-tests} that a type error is expected. }
  6585. %
  6586. \racket{This indicates to the \code{run-tests.rkt} scripts that a type
  6587. error is expected.}
  6588. %
  6589. The other half of the test programs should not have type errors.
  6590. %
  6591. \racket{In the \code{run-tests.rkt} script, change the second argument
  6592. of \code{interp-tests} and \code{compiler-tests} to
  6593. \code{type-check-Lif}, which causes the type checker to run prior to
  6594. the compiler passes. Temporarily change the \code{passes} to an
  6595. empty list and run the script, thereby checking that the new test
  6596. programs either type check or not as intended.}
  6597. %
  6598. Run the test script to check that these test programs type check as
  6599. expected.
  6600. \end{exercise}
  6601. \clearpage
  6602. \section{The \LangCIf{} Intermediate Language}
  6603. \label{sec:Cif}
  6604. {\if\edition\racketEd
  6605. %
  6606. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6607. \LangCIf{} intermediate language and Figure~\ref{fig:c1-syntax}
  6608. defines its abstract syntax. Compared to \LangCVar{}, the \LangCIf{}
  6609. language adds logical and comparison operators to the \Exp{}
  6610. non-terminal and the literals \TRUE{} and \FALSE{} to the \Arg{}
  6611. non-terminal.
  6612. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  6613. statements to the \Tail{} non-terminal. The condition of an \code{if}
  6614. statement is a comparison operation and the branches are \code{goto}
  6615. statements, making it straightforward to compile \code{if} statements
  6616. to x86.
  6617. %
  6618. \fi}
  6619. %
  6620. {\if\edition\pythonEd
  6621. %
  6622. The output of \key{explicate\_control} is a language similar to the
  6623. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6624. \code{goto} statements, so we name it \LangCIf{}. The
  6625. concrete syntax for \LangCIf{} is defined in
  6626. Figure~\ref{fig:c1-concrete-syntax}
  6627. and the abstract syntax is defined in Figure~\ref{fig:c1-syntax}.
  6628. %
  6629. The \LangCIf{} language supports the same operators as \LangIf{} but
  6630. the arguments of operators are restricted to atomic expressions. The
  6631. \LangCIf{} language does not include \code{if} expressions but it does
  6632. include a restricted form of \code{if} statment. The condition must be
  6633. a comparison and the two branches may only contain \code{goto}
  6634. statements. These restrictions make it easier to translate \code{if}
  6635. statements to x86.
  6636. %
  6637. \fi}
  6638. %
  6639. The \key{CProgram} construct contains
  6640. %
  6641. \racket{an alist}\python{a dictionary}
  6642. %
  6643. mapping labels to $\Tail$ expressions, which can be return statements,
  6644. an assignment statement followed by a $\Tail$ expression, a
  6645. \code{goto}, or a conditional \code{goto}.
  6646. \begin{figure}[tbp]
  6647. \fbox{
  6648. \begin{minipage}{0.96\textwidth}
  6649. \small
  6650. \[
  6651. \begin{array}{lcl}
  6652. \Atm &::=& \gray{ \Int \MID \Var } \MID \itm{bool} \\
  6653. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6654. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} \MID \key{(-}~\Atm~\Atm\key{)} } \\
  6655. &\MID& \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6656. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  6657. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  6658. \MID \key{goto}~\itm{label}\key{;}\\
  6659. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  6660. \LangCIfM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  6661. \end{array}
  6662. \]
  6663. \end{minipage}
  6664. }
  6665. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  6666. \label{fig:c1-concrete-syntax}
  6667. \end{figure}
  6668. \begin{figure}[tp]
  6669. \fbox{
  6670. \begin{minipage}{0.96\textwidth}
  6671. \small
  6672. {\if\edition\racketEd
  6673. \[
  6674. \begin{array}{lcl}
  6675. \Atm &::=& \gray{\INT{\Int} \MID \VAR{\Var}} \MID \BOOL{\itm{bool}} \\
  6676. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6677. \Exp &::= & \gray{ \Atm \MID \READ{} }\\
  6678. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6679. &\MID& \UNIOP{\key{'not}}{\Atm}
  6680. \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6681. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  6682. \Tail &::= & \gray{\RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} }
  6683. \MID \GOTO{\itm{label}} \\
  6684. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  6685. \LangCIfM{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  6686. \end{array}
  6687. \]
  6688. \fi}
  6689. {\if\edition\pythonEd
  6690. \[
  6691. \begin{array}{lcl}
  6692. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6693. \Exp &::= & \Atm \MID \READ{} \\
  6694. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6695. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6696. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm}
  6697. \MID \BOOLOP{\itm{boolop}}{\Atm}{\Atm} \\
  6698. \Stmt &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  6699. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6700. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6701. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS} \\
  6702. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\,\key{:}\,\Stmt^{*}, \ldots \RC}
  6703. \end{array}
  6704. \]
  6705. \fi}
  6706. \end{minipage}
  6707. }
  6708. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6709. (Figure~\ref{fig:c0-syntax})}.}
  6710. \label{fig:c1-syntax}
  6711. \end{figure}
  6712. \section{The \LangXIf{} Language}
  6713. \label{sec:x86-if}
  6714. \index{subject}{x86} To implement the new logical operations, the comparison
  6715. operations, and the \key{if} expression, we need to delve further into
  6716. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  6717. define the concrete and abstract syntax for the \LangXIf{} subset
  6718. of x86, which includes instructions for logical operations,
  6719. comparisons, and \racket{conditional} jumps.
  6720. One challenge is that x86 does not provide an instruction that
  6721. directly implements logical negation (\code{not} in \LangIf{} and
  6722. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6723. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6724. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6725. bit of its arguments, and writes the results into its second argument.
  6726. Recall the truth table for exclusive-or:
  6727. \begin{center}
  6728. \begin{tabular}{l|cc}
  6729. & 0 & 1 \\ \hline
  6730. 0 & 0 & 1 \\
  6731. 1 & 1 & 0
  6732. \end{tabular}
  6733. \end{center}
  6734. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6735. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6736. for the bit $1$, the result is the opposite of the second bit. Thus,
  6737. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6738. the first argument as follows, where $\Arg$ is the translation of
  6739. $\Atm$.
  6740. \[
  6741. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  6742. \qquad\Rightarrow\qquad
  6743. \begin{array}{l}
  6744. \key{movq}~ \Arg\key{,} \Var\\
  6745. \key{xorq}~ \key{\$1,} \Var
  6746. \end{array}
  6747. \]
  6748. \begin{figure}[tp]
  6749. \fbox{
  6750. \begin{minipage}{0.96\textwidth}
  6751. \[
  6752. \begin{array}{lcl}
  6753. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6754. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6755. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  6756. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6757. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  6758. \key{subq} \; \Arg\key{,} \Arg \MID
  6759. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  6760. && \gray{ \key{callq} \; \itm{label} \MID
  6761. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \racket{\key{jmp}\,\itm{label} \MID} } \python{\key{jmp}\,\itm{label} \MID} \\
  6762. && \racket{\gray{ \itm{label}\key{:}\; \Instr }}\python{\itm{label}\key{:}\; \Instr}
  6763. \MID \key{xorq}~\Arg\key{,}~\Arg
  6764. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  6765. && \key{set}cc~\Arg
  6766. \MID \key{movzbq}~\Arg\key{,}~\Arg
  6767. \MID \key{j}cc~\itm{label}
  6768. \\
  6769. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  6770. & & \gray{ \key{main:} \; \Instr\ldots }
  6771. \end{array}
  6772. \]
  6773. \end{minipage}
  6774. }
  6775. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6776. \label{fig:x86-1-concrete}
  6777. \end{figure}
  6778. \begin{figure}[tp]
  6779. \fbox{
  6780. \begin{minipage}{0.98\textwidth}
  6781. \small
  6782. {\if\edition\racketEd
  6783. \[
  6784. \begin{array}{lcl}
  6785. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6786. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6787. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6788. \MID \BYTEREG{\itm{bytereg}} \\
  6789. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6790. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6791. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6792. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  6793. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6794. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6795. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6796. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6797. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6798. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6799. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6800. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}} \\
  6801. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  6802. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  6803. \end{array}
  6804. \]
  6805. \fi}
  6806. %
  6807. {\if\edition\pythonEd
  6808. \[
  6809. \begin{array}{lcl}
  6810. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6811. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6812. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6813. \MID \BYTEREG{\itm{bytereg}} \\
  6814. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6815. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6816. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6817. &\MID& \gray{ \BININSTR{\code{movq}}{\Arg}{\Arg}
  6818. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6819. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6820. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  6821. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6822. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6823. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6824. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6825. &\MID& \JMPIF{\key{'}\itm{cc}\key{'}}{\itm{label}} \\
  6826. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Instr^{*} \key{,} \ldots \RC }
  6827. \end{array}
  6828. \]
  6829. \fi}
  6830. \end{minipage}
  6831. }
  6832. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  6833. \label{fig:x86-1}
  6834. \end{figure}
  6835. Next we consider the x86 instructions that are relevant for compiling
  6836. the comparison operations. The \key{cmpq} instruction compares its two
  6837. arguments to determine whether one argument is less than, equal, or
  6838. greater than the other argument. The \key{cmpq} instruction is unusual
  6839. regarding the order of its arguments and where the result is
  6840. placed. The argument order is backwards: if you want to test whether
  6841. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  6842. \key{cmpq} is placed in the special EFLAGS register. This register
  6843. cannot be accessed directly but it can be queried by a number of
  6844. instructions, including the \key{set} instruction. The instruction
  6845. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  6846. depending on whether the comparison comes out according to the
  6847. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  6848. for less-or-equal, \key{g} for greater, \key{ge} for
  6849. greater-or-equal). The \key{set} instruction has a quirk in
  6850. that its destination argument must be single byte register, such as
  6851. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  6852. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  6853. instruction can be used to move from a single byte register to a
  6854. normal 64-bit register. The abstract syntax for the \code{set}
  6855. instruction differs from the concrete syntax in that it separates the
  6856. instruction name from the condition code.
  6857. \python{The x86 instructions for jumping are relevant to the
  6858. compilation of \key{if} expressions.}
  6859. %
  6860. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  6861. counter to the address of the instruction after the specified
  6862. label.}
  6863. %
  6864. \racket{The x86 instruction for conditional jump is relevant to the
  6865. compilation of \key{if} expressions.}
  6866. %
  6867. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  6868. counter to point to the instruction after \itm{label} depending on
  6869. whether the result in the EFLAGS register matches the condition code
  6870. \itm{cc}, otherwise the jump instruction falls through to the next
  6871. instruction. Like the abstract syntax for \code{set}, the abstract
  6872. syntax for conditional jump separates the instruction name from the
  6873. condition code. For example, \JMPIF{\key{'le'}}{\key{foo}} corresponds
  6874. to \code{jle foo}. Because the conditional jump instruction relies on
  6875. the EFLAGS register, it is common for it to be immediately preceded by
  6876. a \key{cmpq} instruction to set the EFLAGS register.
  6877. \section{Shrink the \LangIf{} Language}
  6878. \label{sec:shrink-Lif}
  6879. The \LangIf{} language includes several features that are easily
  6880. expressible with other features. For example, \code{and} and \code{or}
  6881. are expressible using \code{if} as follows.
  6882. \begin{align*}
  6883. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  6884. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  6885. \end{align*}
  6886. By performing these translations in the front-end of the compiler, the
  6887. later passes of the compiler do not need to deal with these features,
  6888. making the passes shorter.
  6889. %% For example, subtraction is
  6890. %% expressible using addition and negation.
  6891. %% \[
  6892. %% \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  6893. %% \]
  6894. %% Several of the comparison operations are expressible using less-than
  6895. %% and logical negation.
  6896. %% \[
  6897. %% \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  6898. %% \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  6899. %% \]
  6900. %% The \key{let} is needed in the above translation to ensure that
  6901. %% expression $e_1$ is evaluated before $e_2$.
  6902. On the other hand, sometimes translations reduce the efficiency of the
  6903. generated code by increasing the number of instructions. For example,
  6904. expressing subtraction in terms of negation
  6905. \[
  6906. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  6907. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  6908. \]
  6909. produces code with two x86 instructions (\code{negq} and \code{addq})
  6910. instead of just one (\code{subq}).
  6911. %% However,
  6912. %% these differences typically do not affect the number of accesses to
  6913. %% memory, which is the primary factor that determines execution time on
  6914. %% modern computer architectures.
  6915. \begin{exercise}\normalfont
  6916. %
  6917. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  6918. the language by translating them to \code{if} expressions in \LangIf{}.
  6919. %
  6920. Create four test programs that involve these operators.
  6921. %
  6922. {\if\edition\racketEd
  6923. In the \code{run-tests.rkt} script, add the following entry for
  6924. \code{shrink} to the list of passes (it should be the only pass at
  6925. this point).
  6926. \begin{lstlisting}
  6927. (list "shrink" shrink interp_Lif type-check-Lif)
  6928. \end{lstlisting}
  6929. This instructs \code{interp-tests} to run the intepreter
  6930. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  6931. output of \code{shrink}.
  6932. \fi}
  6933. %
  6934. Run the script to test your compiler on all the test programs.
  6935. \end{exercise}
  6936. {\if\edition\racketEd
  6937. \section{Uniquify Variables}
  6938. \label{sec:uniquify-Lif}
  6939. Add cases to \code{uniquify-exp} to handle Boolean constants and
  6940. \code{if} expressions.
  6941. \begin{exercise}\normalfont
  6942. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  6943. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  6944. \begin{lstlisting}
  6945. (list "uniquify" uniquify interp_Lif type_check_Lif)
  6946. \end{lstlisting}
  6947. Run the script to test your compiler.
  6948. \end{exercise}
  6949. \fi}
  6950. \section{Remove Complex Operands}
  6951. \label{sec:remove-complex-opera-Lif}
  6952. The output language of \code{remove\_complex\_operands} is
  6953. \LangIfANF{} (Figure~\ref{fig:Lif-anf-syntax}), the administrative
  6954. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  6955. but the \code{if} expression is not. All three sub-expressions of an
  6956. \code{if} are allowed to be complex expressions but the operands of
  6957. \code{not} and the comparisons must be atomic.
  6958. %
  6959. \python{We add a new language form, the \code{Let} expression, to aid
  6960. in the translation of \code{if} expressions. When we recursively
  6961. process the two branches of the \code{if}, we generate temporary
  6962. variables and their initializing expressions. However, these
  6963. expressions may contain side effects and should only be executed
  6964. when the condition of the \code{if} is true (for the ``then''
  6965. branch) or false (for the ``else'' branch). The \code{Let} provides
  6966. a way to initialize the temporary variables within the two branches
  6967. of the \code{if} expression. In general, the $\LET{x}{e_1}{e_2}$
  6968. form assigns the result of $e_1$ to the variable $x$, an then
  6969. evaluates $e_2$, which may reference $x$.}
  6970. Add cases for Boolean constants, \python{comparisons,} and \code{if}
  6971. expressions to the \code{rco\_exp} and \code{rco\_atom} functions
  6972. according to whether the output needs to be \Exp{} or \Atm{} as
  6973. specified in the grammar for \LangIfANF{}. Regarding \code{if}, it is
  6974. particularly important to \textbf{not} replace its condition with a
  6975. temporary variable because that would interfere with the generation of
  6976. high-quality output in the \code{explicate\_control} pass.
  6977. \begin{figure}[tp]
  6978. \centering
  6979. \fbox{
  6980. \begin{minipage}{0.96\textwidth}
  6981. {\if\edition\racketEd
  6982. \[
  6983. \begin{array}{rcl}
  6984. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  6985. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  6986. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6987. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6988. &\MID& \UNIOP{\key{not}}{\Atm} \\
  6989. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6990. R^{\mathsf{ANF}}_{\mathsf{if}} &::=& \PROGRAM{\code{()}}{\Exp}
  6991. \end{array}
  6992. \]
  6993. \fi}
  6994. {\if\edition\pythonEd
  6995. \[
  6996. \begin{array}{rcl}
  6997. \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  6998. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6999. \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7000. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7001. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  7002. \Exp &::=& \Atm \MID \READ{} \\
  7003. &\MID& \BINOP{\itm{binaryop}}{\Atm}{\Atm} \MID \UNIOP{\key{unaryop}}{\Atm} \\
  7004. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7005. &\MID& \LET{\Var}{\Exp}{\Exp}\\
  7006. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7007. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}\\
  7008. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7009. \end{array}
  7010. \]
  7011. \fi}
  7012. \end{minipage}
  7013. }
  7014. \caption{\LangIfANF{} is \LangIf{} in monadic normal form.}
  7015. \label{fig:Lif-anf-syntax}
  7016. \end{figure}
  7017. \begin{exercise}\normalfont
  7018. %
  7019. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7020. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7021. %
  7022. Create three new \LangIf{} programs that exercise the interesting
  7023. code in this pass.
  7024. %
  7025. {\if\edition\racketEd
  7026. In the \code{run-tests.rkt} script, add the following entry to the
  7027. list of \code{passes} and then run the script to test your compiler.
  7028. \begin{lstlisting}
  7029. (list "remove-complex" remove-complex-opera* interp-Lif type-check-Lif)
  7030. \end{lstlisting}
  7031. \fi}
  7032. \end{exercise}
  7033. \section{Explicate Control}
  7034. \label{sec:explicate-control-Lif}
  7035. \racket{Recall that the purpose of \code{explicate\_control} is to
  7036. make the order of evaluation explicit in the syntax of the program.
  7037. With the addition of \key{if} this get more interesting.}
  7038. %
  7039. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7040. %
  7041. The main challenge to overcome is that the condition of an \key{if}
  7042. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  7043. condition must be a comparison.
  7044. As a motivating example, consider the following program that has an
  7045. \key{if} expression nested in the condition of another \key{if}.%
  7046. \python{\footnote{Programmers rarely write nested \code{if}
  7047. expressions, but it is not uncommon for the condition of an
  7048. \code{if} statement to be a call of a function that also contains an
  7049. \code{if} statement. When such a function is inlined, the result is
  7050. a nested \code{if} that requires the techniques discussed in this
  7051. section.}}
  7052. % cond_test_41.rkt, if_lt_eq.py
  7053. \begin{center}
  7054. \begin{minipage}{0.96\textwidth}
  7055. {\if\edition\racketEd
  7056. \begin{lstlisting}
  7057. (let ([x (read)])
  7058. (let ([y (read)])
  7059. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7060. (+ y 2)
  7061. (+ y 10))))
  7062. \end{lstlisting}
  7063. \fi}
  7064. {\if\edition\pythonEd
  7065. \begin{lstlisting}
  7066. x = input_int()
  7067. y = input_int()
  7068. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7069. \end{lstlisting}
  7070. \fi}
  7071. \end{minipage}
  7072. \end{center}
  7073. %
  7074. The naive way to compile \key{if} and the comparison operations would
  7075. be to handle each of them in isolation, regardless of their context.
  7076. Each comparison would be translated into a \key{cmpq} instruction
  7077. followed by a couple instructions to move the result from the EFLAGS
  7078. register into a general purpose register or stack location. Each
  7079. \key{if} would be translated into a \key{cmpq} instruction followed by
  7080. a conditional jump. The generated code for the inner \key{if} in the
  7081. above example would be as follows.
  7082. \begin{center}
  7083. \begin{minipage}{0.96\textwidth}
  7084. \begin{lstlisting}
  7085. cmpq $1, x
  7086. setl %al
  7087. movzbq %al, tmp
  7088. cmpq $1, tmp
  7089. je then_branch_1
  7090. jmp else_branch_1
  7091. \end{lstlisting}
  7092. \end{minipage}
  7093. \end{center}
  7094. However, if we take context into account we can do better and reduce
  7095. the use of \key{cmpq} instructions for accessing the EFLAG register.
  7096. Our goal will be to compile \key{if} expressions so that the relevant
  7097. comparison instruction appears directly before the conditional jump.
  7098. For example, we want to generate the following code for the inner
  7099. \code{if}.
  7100. \begin{center}
  7101. \begin{minipage}{0.96\textwidth}
  7102. \begin{lstlisting}
  7103. cmpq $1, x
  7104. jl then_branch_1
  7105. jmp else_branch_1
  7106. \end{lstlisting}
  7107. \end{minipage}
  7108. \end{center}
  7109. One way to achieve this is to reorganize the code at the level of
  7110. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7111. the following code.
  7112. \begin{center}
  7113. \begin{minipage}{0.96\textwidth}
  7114. {\if\edition\racketEd
  7115. \begin{lstlisting}
  7116. (let ([x (read)])
  7117. (let ([y (read)])
  7118. (if (< x 1)
  7119. (if (eq? x 0)
  7120. (+ y 2)
  7121. (+ y 10))
  7122. (if (eq? x 2)
  7123. (+ y 2)
  7124. (+ y 10)))))
  7125. \end{lstlisting}
  7126. \fi}
  7127. {\if\edition\pythonEd
  7128. \begin{lstlisting}
  7129. x = input_int()
  7130. y = intput_int()
  7131. print(((y + 2) if x == 0 else (y + 10)) \
  7132. if (x < 1) \
  7133. else ((y + 2) if (x == 2) else (y + 10)))
  7134. \end{lstlisting}
  7135. \fi}
  7136. \end{minipage}
  7137. \end{center}
  7138. Unfortunately, this approach duplicates the two branches from the
  7139. outer \code{if} and a compiler must never duplicate code! After all,
  7140. the two branches could have been very large expressions.
  7141. We need a way to perform the above transformation but without
  7142. duplicating code. That is, we need a way for different parts of a
  7143. program to refer to the same piece of code.
  7144. %
  7145. Put another way, we need to move away from abstract syntax
  7146. \emph{trees} and instead use \emph{graphs}.
  7147. %
  7148. At the level of x86 assembly this is straightforward because we can
  7149. label the code for each branch and insert jumps in all the places that
  7150. need to execute the branch.
  7151. %
  7152. Likewise, our language \LangCIf{} provides the ability to label a
  7153. sequence of code and to jump to a label via \code{goto}.
  7154. %
  7155. %% In particular, we use a standard program representation called a
  7156. %% \emph{control flow graph} (CFG), due to Frances Elizabeth
  7157. %% \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex
  7158. %% is a labeled sequence of code, called a \emph{basic block}, and each
  7159. %% edge represents a jump to another block.
  7160. %
  7161. %% The nice thing about the output of \code{explicate\_control} is that
  7162. %% there are no unnecessary comparisons and every comparison is part of a
  7163. %% conditional jump.
  7164. %% The down-side of this output is that it includes
  7165. %% trivial blocks, such as the blocks labeled \code{block92} through
  7166. %% \code{block95}, that only jump to another block. We discuss a solution
  7167. %% to this problem in Section~\ref{sec:opt-jumps}.
  7168. {\if\edition\racketEd
  7169. %
  7170. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  7171. \code{explicate\_control} for \LangVar{} using two mutually recursive
  7172. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7173. former function translates expressions in tail position whereas the
  7174. later function translates expressions on the right-hand-side of a
  7175. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  7176. have a new kind of position to deal with: the predicate position of
  7177. the \key{if}. We need another function, \code{explicate\_pred}, that
  7178. decides how to compile an \key{if} by analyzing its predicate. So
  7179. \code{explicate\_pred} takes an \LangIf{} expression and two \LangCIf{}
  7180. tails for the then-branch and else-branch and outputs a tail. In the
  7181. following paragraphs we discuss specific cases in the
  7182. \code{explicate\_tail}, \code{explicate\_assign}, and
  7183. \code{explicate\_pred} functions.
  7184. %
  7185. \fi}
  7186. %
  7187. {\if\edition\pythonEd
  7188. %
  7189. We recommend implementing \code{explicate\_control} using the
  7190. following four auxiliary functions.
  7191. \begin{description}
  7192. \item[\code{explicate\_effect}] generates code for expressions as
  7193. statements, so their result is ignored and only their side effects
  7194. matter.
  7195. \item[\code{explicate\_assign}] generates code for expressions
  7196. on the right-hand side of an assignment.
  7197. \item[\code{explicate\_pred}] generates code for an \code{if}
  7198. expression or statement by analyzing the condition expression.
  7199. \item[\code{explicate\_stmt}] generates code for statements.
  7200. \end{description}
  7201. These four functions should build the dictionary of basic blocks. The
  7202. following auxiliary function can be used to create a new basic block
  7203. from a list of statements. It returns a \code{goto} statement that
  7204. jumps to the new basic block.
  7205. \begin{center}
  7206. \begin{minipage}{\textwidth}
  7207. \begin{lstlisting}
  7208. def create_block(stmts, basic_blocks):
  7209. label = label_name(generate_name('block'))
  7210. basic_blocks[label] = stmts
  7211. return Goto(label)
  7212. \end{lstlisting}
  7213. \end{minipage}
  7214. \end{center}
  7215. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7216. \code{explicate\_control} pass.
  7217. The \code{explicate\_effect} function has three parameters: 1) the
  7218. expression to be compiled, 2) the already-compiled code for this
  7219. expression's \emph{continuation}, that is, the list of statements that
  7220. should execute after this expression, and 3) the dictionary of
  7221. generated basic blocks. The \code{explicate\_effect} function returns
  7222. a list of \LangCIf{} statements and it may add to the dictionary of
  7223. basic blocks.
  7224. %
  7225. Let's consider a few of the cases for the expression to be compiled.
  7226. If the expression to be compiled is a constant, then it can be
  7227. discarded because it has no side effects. If it's a \CREAD{}, then it
  7228. has a side-effect and should be preserved. So the exprssion should be
  7229. translated into a statement using the \code{Expr} AST class. If the
  7230. expression to be compiled is an \code{if} expression, we translate the
  7231. two branches using \code{explicate\_effect} and then translate the
  7232. condition expression using \code{explicate\_pred}, which generates
  7233. code for the entire \code{if}.
  7234. The \code{explicate\_assign} function has four parameters: 1) the
  7235. right-hand-side of the assignment, 2) the left-hand-side of the
  7236. assignment (the variable), 3) the continuation, and 4) the dictionary
  7237. of basic blocks. The \code{explicate\_assign} function returns a list
  7238. of \LangCIf{} statements and it may add to the dictionary of basic
  7239. blocks.
  7240. When the right-hand-side is an \code{if} expression, there is some
  7241. work to do. In particular, the two branches should be translated using
  7242. \code{explicate\_assign} and the condition expression should be
  7243. translated using \code{explicate\_pred}. Otherwise we can simply
  7244. generate an assignment statement, with the given left and right-hand
  7245. sides, concatenated with its continuation.
  7246. \begin{figure}[tbp]
  7247. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7248. def explicate_effect(e, cont, basic_blocks):
  7249. match e:
  7250. case IfExp(test, body, orelse):
  7251. ...
  7252. case Call(func, args):
  7253. ...
  7254. case Let(var, rhs, body):
  7255. ...
  7256. case _:
  7257. ...
  7258. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7259. match rhs:
  7260. case IfExp(test, body, orelse):
  7261. ...
  7262. case Let(var, rhs, body):
  7263. ...
  7264. case _:
  7265. return [Assign([lhs], rhs)] + cont
  7266. def explicate_pred(cnd, thn, els, basic_blocks):
  7267. match cnd:
  7268. case Compare(left, [op], [right]):
  7269. goto_thn = create_block(thn, basic_blocks)
  7270. goto_els = create_block(els, basic_blocks)
  7271. return [If(cnd, [goto_thn], [goto_els])]
  7272. case Constant(True):
  7273. return thn;
  7274. case Constant(False):
  7275. return els;
  7276. case UnaryOp(Not(), operand):
  7277. ...
  7278. case IfExp(test, body, orelse):
  7279. ...
  7280. case Let(var, rhs, body):
  7281. ...
  7282. case _:
  7283. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7284. [create_block(els, basic_blocks)],
  7285. [create_block(thn, basic_blocks)])]
  7286. def explicate_stmt(s, cont, basic_blocks):
  7287. match s:
  7288. case Assign([lhs], rhs):
  7289. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7290. case Expr(value):
  7291. return explicate_effect(value, cont, basic_blocks)
  7292. case If(test, body, orelse):
  7293. ...
  7294. def explicate_control(p):
  7295. match p:
  7296. case Module(body):
  7297. new_body = [Return(Constant(0))]
  7298. basic_blocks = {}
  7299. for s in reversed(body):
  7300. new_body = explicate_stmt(s, new_body, basic_blocks)
  7301. basic_blocks[label_name('start')] = new_body
  7302. return CProgram(basic_blocks)
  7303. \end{lstlisting}
  7304. \caption{Skeleton for the \code{explicate\_control} pass.}
  7305. \label{fig:explicate-control-Lif}
  7306. \end{figure}
  7307. \fi}
  7308. {\if\edition\racketEd
  7309. %
  7310. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7311. additional cases for Boolean constants and \key{if}. The cases for
  7312. \code{if} should recursively compile the two branches using either
  7313. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7314. cases should then invoke \code{explicate\_pred} on the condition
  7315. expression, passing in the generated code for the two branches. For
  7316. example, consider the following program with an \code{if} in tail
  7317. position.
  7318. \begin{lstlisting}
  7319. (let ([x (read)])
  7320. (if (eq? x 0) 42 777))
  7321. \end{lstlisting}
  7322. The two branches are recursively compiled to \code{return 42;} and
  7323. \code{return 777;}. We then delegate to \code{explicate\_pred},
  7324. passing the condition \code{(eq? x 0)} and the two return statements, which is
  7325. used as the result for \code{explicate\_tail}.
  7326. Next let us consider a program with an \code{if} on the right-hand
  7327. side of a \code{let}.
  7328. \begin{lstlisting}
  7329. (let ([y (read)])
  7330. (let ([x (if (eq? y 0) 40 777)])
  7331. (+ x 2)))
  7332. \end{lstlisting}
  7333. Note that the body of the inner \code{let} will have already been
  7334. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7335. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7336. to recursively process both branches of the \code{if}, so we generate
  7337. the following block using an auxiliary function named \code{create\_block}.
  7338. \begin{lstlisting}
  7339. block_6:
  7340. return (+ x 2)
  7341. \end{lstlisting}
  7342. and use \code{goto block\_6;} as the \code{cont} argument for
  7343. compiling the branches. So the two branches compile to
  7344. \begin{lstlisting}
  7345. x = 40;
  7346. goto block_6;
  7347. \end{lstlisting}
  7348. and
  7349. \begin{lstlisting}
  7350. x = 777;
  7351. goto block_6;
  7352. \end{lstlisting}
  7353. We then delegate to \code{explicate\_pred}, passing the condition \code{(eq? y
  7354. 0)} and the above code for the branches.
  7355. \fi}
  7356. {\if\edition\racketEd
  7357. \begin{figure}[tbp]
  7358. \begin{lstlisting}
  7359. (define (explicate_pred cnd thn els)
  7360. (match cnd
  7361. [(Var x) ___]
  7362. [(Let x rhs body) ___]
  7363. [(Prim 'not (list e)) ___]
  7364. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7365. (IfStmt (Prim op es) (create_block thn)
  7366. (create_block els))]
  7367. [(Bool b) (if b thn els)]
  7368. [(If cnd^ thn^ els^) ___]
  7369. [else (error "explicate_pred unhandled case" cnd)]))
  7370. \end{lstlisting}
  7371. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7372. \label{fig:explicate-pred}
  7373. \end{figure}
  7374. \fi}
  7375. \racket{The skeleton for the \code{explicate\_pred} function is given
  7376. in Figure~\ref{fig:explicate-pred}. It takes three parameters:
  7377. 1) \code{cnd}, the condition expression of the \code{if},
  7378. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7379. and 3) \code{els}, the code generated by
  7380. explicate for the ``else'' branch. The \code{explicate\_pred}
  7381. function should match on \code{cnd} with a case for
  7382. every kind of expression that can have type \code{Boolean}.}
  7383. %
  7384. \python{The \code{explicate\_pred} function has four parameters: 1)
  7385. the condition expession, 2) the generated statements for the
  7386. ``then'' branch, 3) the generated statements for the ``else''
  7387. branch, and 4) the dictionary of basic blocks. The
  7388. \code{explicate\_pred} function returns a list of \LangCIf{}
  7389. statements and it may add to the dictionary of basic blocks.}
  7390. Consider the case for comparison operators. We translate the
  7391. comparison to an \code{if} statement whose branches are \code{goto}
  7392. statements created by applying \code{create\_block} to the code
  7393. generated for the \code{thn} and \code{els} branches. Let us
  7394. illustrate this translation with an example. Returning
  7395. to the program with an \code{if} expression in tail position,
  7396. we invoke \code{explicate\_pred} on its condition \code{(eq? x 0)}
  7397. which happens to be a comparison operator.
  7398. \begin{lstlisting}
  7399. (let ([x (read)])
  7400. (if (eq? x 0) 42 777))
  7401. \end{lstlisting}
  7402. The two branches \code{42} and \code{777} were already compiled to \code{return}
  7403. statements, from which we now create the following blocks.
  7404. \begin{center}
  7405. \begin{minipage}{\textwidth}
  7406. \begin{lstlisting}
  7407. block_1:
  7408. return 42;
  7409. block_2:
  7410. return 777;
  7411. \end{lstlisting}
  7412. \end{minipage}
  7413. \end{center}
  7414. %
  7415. So \code{explicate\_pred} compiles the comparison \code{(eq? x 0)}
  7416. to the following \code{if} statement.
  7417. %
  7418. \begin{center}
  7419. \begin{minipage}{\textwidth}
  7420. \begin{lstlisting}
  7421. if (eq? x 0)
  7422. goto block_1;
  7423. else
  7424. goto block_2;
  7425. \end{lstlisting}
  7426. \end{minipage}
  7427. \end{center}
  7428. Next consider the case for Boolean constants. We perform a kind of
  7429. partial evaluation\index{subject}{partial evaluation} and output
  7430. either the \code{thn} or \code{els} branch depending on whether the
  7431. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7432. following program.
  7433. \begin{center}
  7434. \begin{minipage}{\textwidth}
  7435. \begin{lstlisting}
  7436. (if #t 42 777)
  7437. \end{lstlisting}
  7438. \end{minipage}
  7439. \end{center}
  7440. %
  7441. Again, the two branches \code{42} and \code{777} were compiled to
  7442. \code{return} statements, so \code{explicate\_pred} compiles the
  7443. constant \code{\#t} to the code for the ``then'' branch.
  7444. \begin{center}
  7445. \begin{minipage}{\textwidth}
  7446. \begin{lstlisting}
  7447. return 42;
  7448. \end{lstlisting}
  7449. \end{minipage}
  7450. \end{center}
  7451. %
  7452. This case demonstrates that we sometimes discard the \code{thn} or
  7453. \code{els} blocks that are input to \code{explicate\_pred}.
  7454. The case for \key{if} expressions in \code{explicate\_pred} is
  7455. particularly illuminating because it deals with the challenges we
  7456. discussed above regarding nested \key{if} expressions
  7457. (Figure~\ref{fig:explicate-control-s1-38}). The
  7458. \racket{\lstinline{thn^}}\python{\code{body}} and
  7459. \racket{\lstinline{els^}}\python{\code{orlese}} branches of the
  7460. \key{if} inherit their context from the current one, that is,
  7461. predicate context. So you should recursively apply
  7462. \code{explicate\_pred} to the
  7463. \racket{\lstinline{thn^}}\python{\code{body}} and
  7464. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7465. those recursive calls, pass \code{thn} and \code{els} as the extra
  7466. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7467. inside each recursive call. As discussed above, to avoid duplicating
  7468. code, we need to add them to the dictionary of basic blocks so that we
  7469. can instead refer to them by name and execute them with a \key{goto}.
  7470. {\if\edition\pythonEd
  7471. %
  7472. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7473. three parameters: 1) the statement to be compiled, 2) the code for its
  7474. continuation, and 3) the dictionary of basic blocks. The
  7475. \code{explicate\_stmt} returns a list of statements and it may add to
  7476. the dictionary of basic blocks. The cases for assignment and an
  7477. expression-statement are given in full in the skeleton code: they
  7478. simply dispatch to \code{explicate\_assign} and
  7479. \code{explicate\_effect}, respectively. The case for \code{if}
  7480. statements is not given, and is similar to the case for \code{if}
  7481. expressions.
  7482. The \code{explicate\_control} function itself is given in
  7483. Figure~\ref{fig:explicate-control-Lif}. It applies
  7484. \code{explicate\_stmt} to each statement in the program, from back to
  7485. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7486. used as the continuation parameter in the next call to
  7487. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7488. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7489. the dictionary of basic blocks, labeling it as the ``start'' block.
  7490. %
  7491. \fi}
  7492. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7493. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7494. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7495. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7496. %% results from the two recursive calls. We complete the case for
  7497. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7498. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7499. %% the result $B_5$.
  7500. %% \[
  7501. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7502. %% \quad\Rightarrow\quad
  7503. %% B_5
  7504. %% \]
  7505. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7506. %% inherit the current context, so they are in tail position. Thus, the
  7507. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7508. %% \code{explicate\_tail}.
  7509. %% %
  7510. %% We need to pass $B_0$ as the accumulator argument for both of these
  7511. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7512. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7513. %% to the control-flow graph and obtain a promised goto $G_0$.
  7514. %% %
  7515. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7516. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7517. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7518. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7519. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7520. %% \[
  7521. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7522. %% \]
  7523. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7524. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7525. %% should not be confused with the labels for the blocks that appear in
  7526. %% the generated code. We initially construct unlabeled blocks; we only
  7527. %% attach labels to blocks when we add them to the control-flow graph, as
  7528. %% we see in the next case.
  7529. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7530. %% function. The context of the \key{if} is an assignment to some
  7531. %% variable $x$ and then the control continues to some promised block
  7532. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7533. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7534. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7535. %% branches of the \key{if} inherit the current context, so they are in
  7536. %% assignment positions. Let $B_2$ be the result of applying
  7537. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7538. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7539. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7540. %% the result of applying \code{explicate\_pred} to the predicate
  7541. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7542. %% translates to the promise $B_4$.
  7543. %% \[
  7544. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7545. %% \]
  7546. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7547. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7548. \code{remove\_complex\_operands} pass and then the
  7549. \code{explicate\_control} pass on the example program. We walk through
  7550. the output program.
  7551. %
  7552. Following the order of evaluation in the output of
  7553. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7554. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7555. in the predicate of the inner \key{if}. In the output of
  7556. \code{explicate\_control}, in the
  7557. block labeled \code{start}, are two assignment statements followed by a
  7558. \code{if} statement that branches to \code{block\_8} or
  7559. \code{block\_9}. The blocks associated with those labels contain the
  7560. translations of the code
  7561. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7562. and
  7563. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7564. respectively. In particular, we start \code{block\_8} with the
  7565. comparison
  7566. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7567. and then branch to \code{block\_4} or \code{block\_5}.
  7568. Here was see that our algorithm sometimes inserts unnecessary blocks:
  7569. \code{block\_4} is just a \code{goto} to \code{block\_2}
  7570. and \code{block\_5} is just a \code{goto} to \code{block\_3}.
  7571. It would be better to skip blocks \code{block\_4} and \code{block\_5}
  7572. and go directly to \code{block\_2} and \code{block\_3},
  7573. which we investigate in Section~\ref{sec:opt-jumps}.
  7574. Getting back to the example, \code{block\_2} and \code{block\_3},
  7575. corresponds to the two branches of the outer \key{if}, i.e.,
  7576. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7577. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7578. %
  7579. The story for \code{block\_9} is similar to that of \code{block\_8}.
  7580. %
  7581. \python{The \code{block\_1} corresponds to the \code{print} statment
  7582. at the end of the program.}
  7583. \begin{figure}[tbp]
  7584. {\if\edition\racketEd
  7585. \begin{tabular}{lll}
  7586. \begin{minipage}{0.4\textwidth}
  7587. % cond_test_41.rkt
  7588. \begin{lstlisting}
  7589. (let ([x (read)])
  7590. (let ([y (read)])
  7591. (if (if (< x 1)
  7592. (eq? x 0)
  7593. (eq? x 2))
  7594. (+ y 2)
  7595. (+ y 10))))
  7596. \end{lstlisting}
  7597. \end{minipage}
  7598. &
  7599. $\Rightarrow$
  7600. &
  7601. \begin{minipage}{0.55\textwidth}
  7602. \begin{lstlisting}
  7603. start:
  7604. x = (read);
  7605. y = (read);
  7606. if (< x 1)
  7607. goto block_8;
  7608. else
  7609. goto block_9;
  7610. block_8:
  7611. if (eq? x 0)
  7612. goto block_4;
  7613. else
  7614. goto block_5;
  7615. block_9:
  7616. if (eq? x 2)
  7617. goto block_6;
  7618. else
  7619. goto block_7;
  7620. block_4:
  7621. goto block_2;
  7622. block_5:
  7623. goto block_3;
  7624. block_6:
  7625. goto block_2;
  7626. block_7:
  7627. goto block_3;
  7628. block_2:
  7629. return (+ y 2);
  7630. block_3:
  7631. return (+ y 10);
  7632. \end{lstlisting}
  7633. \end{minipage}
  7634. \end{tabular}
  7635. \fi}
  7636. {\if\edition\pythonEd
  7637. \begin{tabular}{lll}
  7638. \begin{minipage}{0.4\textwidth}
  7639. % cond_test_41.rkt
  7640. \begin{lstlisting}
  7641. x = input_int()
  7642. y = input_int()
  7643. print(y + 2 \
  7644. if (x == 0 \
  7645. if x < 1 \
  7646. else x == 2) \
  7647. else y + 10)
  7648. \end{lstlisting}
  7649. \end{minipage}
  7650. &
  7651. $\Rightarrow$
  7652. &
  7653. \begin{minipage}{0.55\textwidth}
  7654. \begin{lstlisting}
  7655. start:
  7656. x = input_int()
  7657. y = input_int()
  7658. if x < 1:
  7659. goto block_8
  7660. else:
  7661. goto block_9
  7662. block_8:
  7663. if x == 0:
  7664. goto block_4
  7665. else:
  7666. goto block_5
  7667. block_9:
  7668. if x == 2:
  7669. goto block_6
  7670. else:
  7671. goto block_7
  7672. block_4:
  7673. goto block_2
  7674. block_5:
  7675. goto block_3
  7676. block_6:
  7677. goto block_2
  7678. block_7:
  7679. goto block_3
  7680. block_2:
  7681. tmp_0 = y + 2
  7682. goto block_1
  7683. block_3:
  7684. tmp_0 = y + 10
  7685. goto block_1
  7686. block_1:
  7687. print(tmp_0)
  7688. return 0
  7689. \end{lstlisting}
  7690. \end{minipage}
  7691. \end{tabular}
  7692. \fi}
  7693. \caption{Translation from \LangIf{} to \LangCIf{}
  7694. via the \code{explicate\_control}.}
  7695. \label{fig:explicate-control-s1-38}
  7696. \end{figure}
  7697. {\if\edition\racketEd
  7698. The way in which the \code{shrink} pass transforms logical operations
  7699. such as \code{and} and \code{or} can impact the quality of code
  7700. generated by \code{explicate\_control}. For example, consider the
  7701. following program.
  7702. % cond_test_21.rkt, and_eq_input.py
  7703. \begin{lstlisting}
  7704. (if (and (eq? (read) 0) (eq? (read) 1))
  7705. 0
  7706. 42)
  7707. \end{lstlisting}
  7708. The \code{and} operation should transform into something that the
  7709. \code{explicate\_pred} function can still analyze and descend through to
  7710. reach the underlying \code{eq?} conditions. Ideally, your
  7711. \code{explicate\_control} pass should generate code similar to the
  7712. following for the above program.
  7713. \begin{center}
  7714. \begin{lstlisting}
  7715. start:
  7716. tmp1 = (read);
  7717. if (eq? tmp1 0) goto block40;
  7718. else goto block39;
  7719. block40:
  7720. tmp2 = (read);
  7721. if (eq? tmp2 1) goto block38;
  7722. else goto block39;
  7723. block38:
  7724. return 0;
  7725. block39:
  7726. return 42;
  7727. \end{lstlisting}
  7728. \end{center}
  7729. \fi}
  7730. \begin{exercise}\normalfont
  7731. \racket{
  7732. Implement the pass \code{explicate\_control} by adding the cases for
  7733. Boolean constants and \key{if} to the \code{explicate\_tail} and
  7734. \code{explicate\_assign} functions. Implement the auxiliary function
  7735. \code{explicate\_pred} for predicate contexts.}
  7736. \python{Implement \code{explicate\_control} pass with its
  7737. four auxiliary functions.}
  7738. %
  7739. Create test cases that exercise all of the new cases in the code for
  7740. this pass.
  7741. %
  7742. {\if\edition\racketEd
  7743. Add the following entry to the list of \code{passes} in
  7744. \code{run-tests.rkt} and then run this script to test your compiler.
  7745. \begin{lstlisting}
  7746. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  7747. \end{lstlisting}
  7748. \fi}
  7749. \end{exercise}
  7750. \clearpage
  7751. \section{Select Instructions}
  7752. \label{sec:select-Lif}
  7753. \index{subject}{instruction selection}
  7754. The \code{select\_instructions} pass translates \LangCIf{} to
  7755. \LangXIfVar{}.
  7756. %
  7757. \racket{Recall that we implement this pass using three auxiliary
  7758. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  7759. $\Tail$.}
  7760. %
  7761. \racket{For $\Atm$, we have new cases for the Booleans.}
  7762. %
  7763. \python{We begin with the Boolean constants.}
  7764. We take the usual approach of encoding them as integers.
  7765. \[
  7766. \TRUE{} \quad\Rightarrow\quad \key{1}
  7767. \qquad\qquad
  7768. \FALSE{} \quad\Rightarrow\quad \key{0}
  7769. \]
  7770. For translating statements, we discuss a couple cases. The \code{not}
  7771. operation can be implemented in terms of \code{xorq} as we discussed
  7772. at the beginning of this section. Given an assignment, if the
  7773. left-hand side variable is the same as the argument of \code{not},
  7774. then just the \code{xorq} instruction suffices.
  7775. \[
  7776. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  7777. \quad\Rightarrow\quad
  7778. \key{xorq}~\key{\$}1\key{,}~\Var
  7779. \]
  7780. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  7781. semantics of x86. In the following translation, let $\Arg$ be the
  7782. result of translating $\Atm$ to x86.
  7783. \[
  7784. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  7785. \quad\Rightarrow\quad
  7786. \begin{array}{l}
  7787. \key{movq}~\Arg\key{,}~\Var\\
  7788. \key{xorq}~\key{\$}1\key{,}~\Var
  7789. \end{array}
  7790. \]
  7791. Next consider the cases for equality. Translating this operation to
  7792. x86 is slightly involved due to the unusual nature of the \key{cmpq}
  7793. instruction discussed above. We recommend translating an assignment
  7794. with an equality on the right-hand side into a sequence of three
  7795. instructions. \\
  7796. \begin{tabular}{lll}
  7797. \begin{minipage}{0.4\textwidth}
  7798. \begin{lstlisting}
  7799. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  7800. \end{lstlisting}
  7801. \end{minipage}
  7802. &
  7803. $\Rightarrow$
  7804. &
  7805. \begin{minipage}{0.4\textwidth}
  7806. \begin{lstlisting}
  7807. cmpq |$\Arg_2$|, |$\Arg_1$|
  7808. sete %al
  7809. movzbq %al, |$\Var$|
  7810. \end{lstlisting}
  7811. \end{minipage}
  7812. \end{tabular} \\
  7813. The translations for the other comparison operators are similar to the
  7814. above but use different suffixes for the \code{set} instruction.
  7815. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  7816. \key{goto} and \key{if} statements. Both are straightforward to
  7817. translate to x86.}
  7818. %
  7819. A \key{goto} statement becomes a jump instruction.
  7820. \[
  7821. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  7822. \]
  7823. %
  7824. An \key{if} statement becomes a compare instruction followed by a
  7825. conditional jump (for the ``then'' branch) and the fall-through is to
  7826. a regular jump (for the ``else'' branch).\\
  7827. \begin{tabular}{lll}
  7828. \begin{minipage}{0.4\textwidth}
  7829. \begin{lstlisting}
  7830. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  7831. goto |$\ell_1$||$\racket{\key{;}}$|
  7832. else|$\python{\key{:}}$|
  7833. goto |$\ell_2$||$\racket{\key{;}}$|
  7834. \end{lstlisting}
  7835. \end{minipage}
  7836. &
  7837. $\Rightarrow$
  7838. &
  7839. \begin{minipage}{0.4\textwidth}
  7840. \begin{lstlisting}
  7841. cmpq |$\Arg_2$|, |$\Arg_1$|
  7842. je |$\ell_1$|
  7843. jmp |$\ell_2$|
  7844. \end{lstlisting}
  7845. \end{minipage}
  7846. \end{tabular} \\
  7847. Again, the translations for the other comparison operators are similar to the
  7848. above but use different suffixes for the conditional jump instruction.
  7849. \python{Regarding the \key{return} statement, we recommend treating it
  7850. as an assignment to the \key{rax} register followed by a jump to the
  7851. conclusion of the \code{main} function.}
  7852. \begin{exercise}\normalfont
  7853. Expand your \code{select\_instructions} pass to handle the new
  7854. features of the \LangIf{} language.
  7855. %
  7856. {\if\edition\racketEd
  7857. Add the following entry to the list of \code{passes} in
  7858. \code{run-tests.rkt}
  7859. \begin{lstlisting}
  7860. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  7861. \end{lstlisting}
  7862. \fi}
  7863. %
  7864. Run the script to test your compiler on all the test programs.
  7865. \end{exercise}
  7866. \section{Register Allocation}
  7867. \label{sec:register-allocation-Lif}
  7868. \index{subject}{register allocation}
  7869. The changes required for \LangIf{} affect liveness analysis, building the
  7870. interference graph, and assigning homes, but the graph coloring
  7871. algorithm itself does not change.
  7872. \subsection{Liveness Analysis}
  7873. \label{sec:liveness-analysis-Lif}
  7874. \index{subject}{liveness analysis}
  7875. Recall that for \LangVar{} we implemented liveness analysis for a
  7876. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  7877. the addition of \key{if} expressions to \LangIf{},
  7878. \code{explicate\_control} produces many basic blocks.
  7879. %% We recommend that you create a new auxiliary function named
  7880. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  7881. %% control-flow graph.
  7882. The first question is: what order should we process the basic blocks?
  7883. Recall that to perform liveness analysis on a basic block we need to
  7884. know the live-after set for the last instruction in the block. If a
  7885. basic block has no successors (i.e. contains no jumps to other
  7886. blocks), then it has an empty live-after set and we can immediately
  7887. apply liveness analysis to it. If a basic block has some successors,
  7888. then we need to complete liveness analysis on those blocks
  7889. first. These ordering contraints are the reverse of a
  7890. \emph{topological order}\index{subject}{topological order} on a graph
  7891. representation of the program. In particular, the \emph{control flow
  7892. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  7893. of a program has a node for each basic block and an edge for each jump
  7894. from one block to another. It is straightforward to generate a CFG
  7895. from the dictionary of basic blocks. One then transposes the CFG and
  7896. applies the topological sort algorithm.
  7897. %
  7898. %
  7899. \racket{We recommend using the \code{tsort} and \code{transpose}
  7900. functions of the Racket \code{graph} package to accomplish this.}
  7901. %
  7902. \python{We provide implementations of \code{topological\_sort} and
  7903. \code{transpose} in the file \code{graph.py} of the support code.}
  7904. %
  7905. As an aside, a topological ordering is only guaranteed to exist if the
  7906. graph does not contain any cycles. This is the case for the
  7907. control-flow graphs that we generate from \LangIf{} programs.
  7908. However, in Chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  7909. and learn how to handle cycles in the control-flow graph.
  7910. \racket{You'll need to construct a directed graph to represent the
  7911. control-flow graph. Do not use the \code{directed-graph} of the
  7912. \code{graph} package because that only allows at most one edge
  7913. between each pair of vertices, but a control-flow graph may have
  7914. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  7915. file in the support code implements a graph representation that
  7916. allows multiple edges between a pair of vertices.}
  7917. {\if\edition\racketEd
  7918. The next question is how to analyze jump instructions. Recall that in
  7919. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  7920. \code{label->live} that maps each label to the set of live locations
  7921. at the beginning of its block. We use \code{label->live} to determine
  7922. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  7923. that we have many basic blocks, \code{label->live} needs to be updated
  7924. as we process the blocks. In particular, after performing liveness
  7925. analysis on a block, we take the live-before set of its first
  7926. instruction and associate that with the block's label in the
  7927. \code{label->live}.
  7928. \fi}
  7929. %
  7930. {\if\edition\pythonEd
  7931. %
  7932. The next question is how to analyze jump instructions. The locations
  7933. that are live before a \code{jmp} should be the locations in
  7934. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  7935. maintaining a dictionary named \code{live\_before\_block} that maps each
  7936. label to the $L_{\mathtt{before}}$ for the first instruction in its
  7937. block. After performing liveness analysis on each block, we take the
  7938. live-before set of its first instruction and associate that with the
  7939. block's label in the \code{live\_before\_block} dictionary.
  7940. %
  7941. \fi}
  7942. In \LangXIfVar{} we also have the conditional jump
  7943. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  7944. this instruction is particularly interesting because, during
  7945. compilation, we do not know which way a conditional jump will go. So
  7946. we do not know whether to use the live-before set for the following
  7947. instruction or the live-before set for the block associated with the
  7948. $\itm{label}$. However, there is no harm to the correctness of the
  7949. generated code if we classify more locations as live than the ones
  7950. that are truly live during one particular execution of the
  7951. instruction. Thus, we can take the union of the live-before sets from
  7952. the following instruction and from the mapping for $\itm{label}$ in
  7953. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  7954. The auxiliary functions for computing the variables in an
  7955. instruction's argument and for computing the variables read-from ($R$)
  7956. or written-to ($W$) by an instruction need to be updated to handle the
  7957. new kinds of arguments and instructions in \LangXIfVar{}.
  7958. \begin{exercise}\normalfont
  7959. {\if\edition\racketEd
  7960. %
  7961. Update the \code{uncover\_live} pass to apply liveness analysis to
  7962. every basic block in the program.
  7963. %
  7964. Add the following entry to the list of \code{passes} in the
  7965. \code{run-tests.rkt} script.
  7966. \begin{lstlisting}
  7967. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  7968. \end{lstlisting}
  7969. \fi}
  7970. {\if\edition\pythonEd
  7971. %
  7972. Update the \code{uncover\_live} function to perform liveness analysis,
  7973. in reverse topological order, on all of the basic blocks in the
  7974. program.
  7975. %
  7976. \fi}
  7977. % Check that the live-after sets that you generate for
  7978. % example X matches the following... -Jeremy
  7979. \end{exercise}
  7980. \subsection{Build the Interference Graph}
  7981. \label{sec:build-interference-Lif}
  7982. Many of the new instructions in \LangXIfVar{} can be handled in the
  7983. same way as the instructions in \LangXVar{}. Thus, if your code was
  7984. already quite general, it will not need to be changed to handle the
  7985. new instructions. If you code is not general enough, we recommend that
  7986. you change your code to be more general. For example, you can factor
  7987. out the computing of the the read and write sets for each kind of
  7988. instruction into auxiliary functions.
  7989. Note that the \key{movzbq} instruction requires some special care,
  7990. similar to the \key{movq} instruction. See rule number 1 in
  7991. Section~\ref{sec:build-interference}.
  7992. \begin{exercise}\normalfont
  7993. Update the \code{build\_interference} pass for \LangXIfVar{}.
  7994. {\if\edition\racketEd
  7995. Add the following entries to the list of \code{passes} in the
  7996. \code{run-tests.rkt} script.
  7997. \begin{lstlisting}
  7998. (list "build_interference" build_interference interp-pseudo-x86-1)
  7999. (list "allocate_registers" allocate_registers interp-x86-1)
  8000. \end{lstlisting}
  8001. \fi}
  8002. % Check that the interference graph that you generate for
  8003. % example X matches the following graph G... -Jeremy
  8004. \end{exercise}
  8005. \section{Patch Instructions}
  8006. The new instructions \key{cmpq} and \key{movzbq} have some special
  8007. restrictions that need to be handled in the \code{patch\_instructions}
  8008. pass.
  8009. %
  8010. The second argument of the \key{cmpq} instruction must not be an
  8011. immediate value (such as an integer). So if you are comparing two
  8012. immediates, we recommend inserting a \key{movq} instruction to put the
  8013. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8014. one memory reference.
  8015. %
  8016. The second argument of the \key{movzbq} must be a register.
  8017. \begin{exercise}\normalfont
  8018. %
  8019. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8020. %
  8021. {\if\edition\racketEd
  8022. Add the following entry to the list of \code{passes} in
  8023. \code{run-tests.rkt} and then run this script to test your compiler.
  8024. \begin{lstlisting}
  8025. (list "patch_instructions" patch_instructions interp-x86-1)
  8026. \end{lstlisting}
  8027. \fi}
  8028. \end{exercise}
  8029. {\if\edition\pythonEd
  8030. \section{Prelude and Conclusion}
  8031. \label{sec:prelude-conclusion-cond}
  8032. The generation of the \code{main} function with its prelude and
  8033. conclusion must change to accomodate how the program now consists of
  8034. one or more basic blocks. After the prelude in \code{main}, jump to
  8035. the \code{start} block. Place the conclusion in a basic block labelled
  8036. with \code{conclusion}.
  8037. \fi}
  8038. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8039. \LangIf{} translated to x86, showing the results of
  8040. \code{explicate\_control}, \code{select\_instructions}, and the final
  8041. x86 assembly.
  8042. \begin{figure}[tbp]
  8043. {\if\edition\racketEd
  8044. \begin{tabular}{lll}
  8045. \begin{minipage}{0.4\textwidth}
  8046. % cond_test_20.rkt, eq_input.py
  8047. \begin{lstlisting}
  8048. (if (eq? (read) 1) 42 0)
  8049. \end{lstlisting}
  8050. $\Downarrow$
  8051. \begin{lstlisting}
  8052. start:
  8053. tmp7951 = (read);
  8054. if (eq? tmp7951 1)
  8055. goto block7952;
  8056. else
  8057. goto block7953;
  8058. block7952:
  8059. return 42;
  8060. block7953:
  8061. return 0;
  8062. \end{lstlisting}
  8063. $\Downarrow$
  8064. \begin{lstlisting}
  8065. start:
  8066. callq read_int
  8067. movq %rax, tmp7951
  8068. cmpq $1, tmp7951
  8069. je block7952
  8070. jmp block7953
  8071. block7953:
  8072. movq $0, %rax
  8073. jmp conclusion
  8074. block7952:
  8075. movq $42, %rax
  8076. jmp conclusion
  8077. \end{lstlisting}
  8078. \end{minipage}
  8079. &
  8080. $\Rightarrow\qquad$
  8081. \begin{minipage}{0.4\textwidth}
  8082. \begin{lstlisting}
  8083. start:
  8084. callq read_int
  8085. movq %rax, %rcx
  8086. cmpq $1, %rcx
  8087. je block7952
  8088. jmp block7953
  8089. block7953:
  8090. movq $0, %rax
  8091. jmp conclusion
  8092. block7952:
  8093. movq $42, %rax
  8094. jmp conclusion
  8095. .globl main
  8096. main:
  8097. pushq %rbp
  8098. movq %rsp, %rbp
  8099. pushq %r13
  8100. pushq %r12
  8101. pushq %rbx
  8102. pushq %r14
  8103. subq $0, %rsp
  8104. jmp start
  8105. conclusion:
  8106. addq $0, %rsp
  8107. popq %r14
  8108. popq %rbx
  8109. popq %r12
  8110. popq %r13
  8111. popq %rbp
  8112. retq
  8113. \end{lstlisting}
  8114. \end{minipage}
  8115. \end{tabular}
  8116. \fi}
  8117. {\if\edition\pythonEd
  8118. \begin{tabular}{lll}
  8119. \begin{minipage}{0.4\textwidth}
  8120. % cond_test_20.rkt, eq_input.py
  8121. \begin{lstlisting}
  8122. print(42 if input_int() == 1 else 0)
  8123. \end{lstlisting}
  8124. $\Downarrow$
  8125. \begin{lstlisting}
  8126. start:
  8127. tmp_0 = input_int()
  8128. if tmp_0 == 1:
  8129. goto block_3
  8130. else:
  8131. goto block_4
  8132. block_3:
  8133. tmp_1 = 42
  8134. goto block_2
  8135. block_4:
  8136. tmp_1 = 0
  8137. goto block_2
  8138. block_2:
  8139. print(tmp_1)
  8140. return 0
  8141. \end{lstlisting}
  8142. $\Downarrow$
  8143. \begin{lstlisting}
  8144. start:
  8145. callq read_int
  8146. movq %rax, tmp_0
  8147. cmpq 1, tmp_0
  8148. je block_3
  8149. jmp block_4
  8150. block_3:
  8151. movq 42, tmp_1
  8152. jmp block_2
  8153. block_4:
  8154. movq 0, tmp_1
  8155. jmp block_2
  8156. block_2:
  8157. movq tmp_1, %rdi
  8158. callq print_int
  8159. movq 0, %rax
  8160. jmp conclusion
  8161. \end{lstlisting}
  8162. \end{minipage}
  8163. &
  8164. $\Rightarrow\qquad$
  8165. \begin{minipage}{0.4\textwidth}
  8166. \begin{lstlisting}
  8167. .globl main
  8168. main:
  8169. pushq %rbp
  8170. movq %rsp, %rbp
  8171. subq $0, %rsp
  8172. jmp start
  8173. start:
  8174. callq read_int
  8175. movq %rax, %rcx
  8176. cmpq $1, %rcx
  8177. je block_3
  8178. jmp block_4
  8179. block_3:
  8180. movq $42, %rcx
  8181. jmp block_2
  8182. block_4:
  8183. movq $0, %rcx
  8184. jmp block_2
  8185. block_2:
  8186. movq %rcx, %rdi
  8187. callq print_int
  8188. movq $0, %rax
  8189. jmp conclusion
  8190. conclusion:
  8191. addq $0, %rsp
  8192. popq %rbp
  8193. retq
  8194. \end{lstlisting}
  8195. \end{minipage}
  8196. \end{tabular}
  8197. \fi}
  8198. \caption{Example compilation of an \key{if} expression to x86, showing
  8199. the results of \code{explicate\_control},
  8200. \code{select\_instructions}, and the final x86 assembly code. }
  8201. \label{fig:if-example-x86}
  8202. \end{figure}
  8203. \begin{figure}[tbp]
  8204. {\if\edition\racketEd
  8205. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8206. \node (Lif) at (0,2) {\large \LangIf{}};
  8207. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8208. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8209. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8210. \node (Lif-5) at (12,2) {\large \LangIfANF{}};
  8211. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8212. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8213. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8214. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8215. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8216. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8217. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8218. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8219. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8220. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8221. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8222. \path[->,bend left=15] (Lif-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8223. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  8224. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8225. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8226. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8227. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8228. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8229. \end{tikzpicture}
  8230. \fi}
  8231. {\if\edition\pythonEd
  8232. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8233. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8234. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8235. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8236. \node (C-1) at (3,0) {\large \LangCIf{}};
  8237. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8238. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8239. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8240. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8241. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8242. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8243. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8244. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8245. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8246. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8247. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8248. \end{tikzpicture}
  8249. \fi}
  8250. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8251. \label{fig:Lif-passes}
  8252. \end{figure}
  8253. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8254. compilation of \LangIf{}.
  8255. \section{Challenge: Optimize Blocks and Remove Jumps}
  8256. \label{sec:opt-jumps}
  8257. We discuss two optional challenges that involve optimizing the
  8258. control-flow of the program.
  8259. \subsection{Optimize Blocks}
  8260. The algorithm for \code{explicate\_control} that we discussed in
  8261. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8262. blocks. It does so in two different ways.
  8263. %
  8264. First, recall how in Figure~\ref{fig:explicate-control-s1-38},
  8265. \code{block\_4} consists of just a jump to \code{block\_2}. We created
  8266. a new basic block from a single \code{goto} statement, whereas we
  8267. could have simply returned the \code{goto} statement. We can solve
  8268. this problem by modifying the \code{create\_block} function to
  8269. recognize this situation.
  8270. Second, \code{explicate\_control} creates a basic block whenever a
  8271. continuation \emph{might} get used more than once (wheneven a
  8272. continuation is passed into two or more recursive calls). However,
  8273. just because a continuation might get used more than once, doesn't
  8274. mean it will. In fact, some continuation parameters may not be used
  8275. at all because we sometimes ignore them. For example, consider the
  8276. case for the constant \TRUE{} in \code{explicate\_pred}, where we
  8277. discard the \code{els} branch. So the question is how can we decide
  8278. whether to create a basic block?
  8279. The solution to this conundrum is to use \emph{lazy
  8280. evaluation}\index{subject}{lazy evaluation}~\citep{Friedman:1976aa}
  8281. to delay creating a basic block until the point in time where we know
  8282. it will be used.
  8283. %
  8284. {\if\edition\racketEd
  8285. %
  8286. Racket provides support for
  8287. lazy evaluation with the
  8288. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8289. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8290. \index{subject}{delay} creates a
  8291. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8292. expressions is postponed. When \key{(force}
  8293. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8294. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8295. result of $e_n$ is cached in the promise and returned. If \code{force}
  8296. is applied again to the same promise, then the cached result is
  8297. returned. If \code{force} is applied to an argument that is not a
  8298. promise, \code{force} simply returns the argument.
  8299. %
  8300. \fi}
  8301. %
  8302. {\if\edition\pythonEd
  8303. %
  8304. While Python does not provide direct support for lazy evaluation, it
  8305. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8306. by wrapping it inside a function with no parameters. We can
  8307. \emph{force} its evaluation by calling the function. However, in some
  8308. cases of \code{explicate\_pred}, etc., we will return a list of
  8309. statements and in other cases we will return a function that computes
  8310. a list of statements. We use the term \emph{promise} to refer to a
  8311. value that may or may not be delayed. To uniformly deal with
  8312. promises, we define the following \code{force} function that checks
  8313. whether its input is delayed (i.e. whether it is a function) and then
  8314. either 1) calls the function, or 2) returns the input.
  8315. \begin{lstlisting}
  8316. def force(promise):
  8317. if isinstance(promise, types.FunctionType):
  8318. return promise()
  8319. else:
  8320. return promise
  8321. \end{lstlisting}
  8322. %
  8323. \fi}
  8324. We use promises for the input and output of the functions
  8325. \code{explicate\_pred}, \code{explicate\_assign},
  8326. %
  8327. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8328. %
  8329. So instead of taking and returning lists of statments, they take and
  8330. return promises. Furthermore, when we come to a situation in which a
  8331. continuation might be used more than once, as in the case for
  8332. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8333. that creates a basic block for each continuation (if there is not
  8334. already one) and then returns a \code{goto} statement to that basic
  8335. block.
  8336. %
  8337. {\if\edition\racketEd
  8338. %
  8339. The following auxiliary function named \code{create\_block} accomplishes
  8340. this task. It begins with \code{delay} to create a promise. When
  8341. forced, this promise will force the original promise. If that returns
  8342. a \code{goto} (because the block was already added to the control-flow
  8343. graph), then we return the \code{goto}. Otherwise we add the block to
  8344. the control-flow graph with another auxiliary function named
  8345. \code{add-node}. That function returns the label for the new block,
  8346. which we use to create a \code{goto}.
  8347. \begin{lstlisting}
  8348. (define (create_block tail)
  8349. (delay
  8350. (define t (force tail))
  8351. (match t
  8352. [(Goto label) (Goto label)]
  8353. [else (Goto (add-node t))])))
  8354. \end{lstlisting}
  8355. \fi}
  8356. {\if\edition\pythonEd
  8357. %
  8358. Here's the new version of the \code{create\_block} auxiliary function
  8359. that works on promises and that checks whether the block consists of a
  8360. solitary \code{goto} statement.\\
  8361. \begin{minipage}{\textwidth}
  8362. \begin{lstlisting}
  8363. def create_block(promise, basic_blocks):
  8364. stmts = force(promise)
  8365. match stmts:
  8366. case [Goto(l)]:
  8367. return Goto(l)
  8368. case _:
  8369. label = label_name(generate_name('block'))
  8370. basic_blocks[label] = stmts
  8371. return Goto(label)
  8372. \end{lstlisting}
  8373. \end{minipage}
  8374. \fi}
  8375. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8376. \code{explicate\_control} on the example of the nested \code{if}
  8377. expressions with the two improvements discussed above. As you can
  8378. see, the number of basic blocks has been reduced from 10 blocks (see
  8379. Figure~\ref{fig:explicate-control-s1-38}) down to 6 blocks.
  8380. \begin{figure}[tbp]
  8381. {\if\edition\racketEd
  8382. \begin{tabular}{lll}
  8383. \begin{minipage}{0.4\textwidth}
  8384. % cond_test_41.rkt
  8385. \begin{lstlisting}
  8386. (let ([x (read)])
  8387. (let ([y (read)])
  8388. (if (if (< x 1)
  8389. (eq? x 0)
  8390. (eq? x 2))
  8391. (+ y 2)
  8392. (+ y 10))))
  8393. \end{lstlisting}
  8394. \end{minipage}
  8395. &
  8396. $\Rightarrow$
  8397. &
  8398. \begin{minipage}{0.55\textwidth}
  8399. \begin{lstlisting}
  8400. start:
  8401. x = (read);
  8402. y = (read);
  8403. if (< x 1) goto block40;
  8404. else goto block41;
  8405. block40:
  8406. if (eq? x 0) goto block38;
  8407. else goto block39;
  8408. block41:
  8409. if (eq? x 2) goto block38;
  8410. else goto block39;
  8411. block38:
  8412. return (+ y 2);
  8413. block39:
  8414. return (+ y 10);
  8415. \end{lstlisting}
  8416. \end{minipage}
  8417. \end{tabular}
  8418. \fi}
  8419. {\if\edition\pythonEd
  8420. \begin{tabular}{lll}
  8421. \begin{minipage}{0.4\textwidth}
  8422. % cond_test_41.rkt
  8423. \begin{lstlisting}
  8424. x = input_int()
  8425. y = input_int()
  8426. print(y + 2 \
  8427. if (x == 0 \
  8428. if x < 1 \
  8429. else x == 2) \
  8430. else y + 10)
  8431. \end{lstlisting}
  8432. \end{minipage}
  8433. &
  8434. $\Rightarrow$
  8435. &
  8436. \begin{minipage}{0.55\textwidth}
  8437. \begin{lstlisting}
  8438. start:
  8439. x = input_int()
  8440. y = input_int()
  8441. if x < 1:
  8442. goto block_4
  8443. else:
  8444. goto block_5
  8445. block_4:
  8446. if x == 0:
  8447. goto block_2
  8448. else:
  8449. goto block_3
  8450. block_5:
  8451. if x == 2:
  8452. goto block_2
  8453. else:
  8454. goto block_3
  8455. block_2:
  8456. tmp_0 = y + 2
  8457. goto block_1
  8458. block_3:
  8459. tmp_0 = y + 10
  8460. goto block_1
  8461. block_1:
  8462. print(tmp_0)
  8463. return 0
  8464. \end{lstlisting}
  8465. \end{minipage}
  8466. \end{tabular}
  8467. \fi}
  8468. \caption{Translation from \LangIf{} to \LangCIf{}
  8469. via the improved \code{explicate\_control}.}
  8470. \label{fig:explicate-control-challenge}
  8471. \end{figure}
  8472. %% Recall that in the example output of \code{explicate\_control} in
  8473. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8474. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8475. %% block. The first goal of this challenge assignment is to remove those
  8476. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8477. %% \code{explicate\_control} on the left and shows the result of bypassing
  8478. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8479. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8480. %% \code{block55}. The optimized code on the right of
  8481. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8482. %% \code{then} branch jumping directly to \code{block55}. The story is
  8483. %% similar for the \code{else} branch, as well as for the two branches in
  8484. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8485. %% have been optimized in this way, there are no longer any jumps to
  8486. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8487. %% \begin{figure}[tbp]
  8488. %% \begin{tabular}{lll}
  8489. %% \begin{minipage}{0.4\textwidth}
  8490. %% \begin{lstlisting}
  8491. %% block62:
  8492. %% tmp54 = (read);
  8493. %% if (eq? tmp54 2) then
  8494. %% goto block59;
  8495. %% else
  8496. %% goto block60;
  8497. %% block61:
  8498. %% tmp53 = (read);
  8499. %% if (eq? tmp53 0) then
  8500. %% goto block57;
  8501. %% else
  8502. %% goto block58;
  8503. %% block60:
  8504. %% goto block56;
  8505. %% block59:
  8506. %% goto block55;
  8507. %% block58:
  8508. %% goto block56;
  8509. %% block57:
  8510. %% goto block55;
  8511. %% block56:
  8512. %% return (+ 700 77);
  8513. %% block55:
  8514. %% return (+ 10 32);
  8515. %% start:
  8516. %% tmp52 = (read);
  8517. %% if (eq? tmp52 1) then
  8518. %% goto block61;
  8519. %% else
  8520. %% goto block62;
  8521. %% \end{lstlisting}
  8522. %% \end{minipage}
  8523. %% &
  8524. %% $\Rightarrow$
  8525. %% &
  8526. %% \begin{minipage}{0.55\textwidth}
  8527. %% \begin{lstlisting}
  8528. %% block62:
  8529. %% tmp54 = (read);
  8530. %% if (eq? tmp54 2) then
  8531. %% goto block55;
  8532. %% else
  8533. %% goto block56;
  8534. %% block61:
  8535. %% tmp53 = (read);
  8536. %% if (eq? tmp53 0) then
  8537. %% goto block55;
  8538. %% else
  8539. %% goto block56;
  8540. %% block56:
  8541. %% return (+ 700 77);
  8542. %% block55:
  8543. %% return (+ 10 32);
  8544. %% start:
  8545. %% tmp52 = (read);
  8546. %% if (eq? tmp52 1) then
  8547. %% goto block61;
  8548. %% else
  8549. %% goto block62;
  8550. %% \end{lstlisting}
  8551. %% \end{minipage}
  8552. %% \end{tabular}
  8553. %% \caption{Optimize jumps by removing trivial blocks.}
  8554. %% \label{fig:optimize-jumps}
  8555. %% \end{figure}
  8556. %% The name of this pass is \code{optimize-jumps}. We recommend
  8557. %% implementing this pass in two phases. The first phrase builds a hash
  8558. %% table that maps labels to possibly improved labels. The second phase
  8559. %% changes the target of each \code{goto} to use the improved label. If
  8560. %% the label is for a trivial block, then the hash table should map the
  8561. %% label to the first non-trivial block that can be reached from this
  8562. %% label by jumping through trivial blocks. If the label is for a
  8563. %% non-trivial block, then the hash table should map the label to itself;
  8564. %% we do not want to change jumps to non-trivial blocks.
  8565. %% The first phase can be accomplished by constructing an empty hash
  8566. %% table, call it \code{short-cut}, and then iterating over the control
  8567. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8568. %% then update the hash table, mapping the block's source to the target
  8569. %% of the \code{goto}. Also, the hash table may already have mapped some
  8570. %% labels to the block's source, to you must iterate through the hash
  8571. %% table and update all of those so that they instead map to the target
  8572. %% of the \code{goto}.
  8573. %% For the second phase, we recommend iterating through the $\Tail$ of
  8574. %% each block in the program, updating the target of every \code{goto}
  8575. %% according to the mapping in \code{short-cut}.
  8576. \begin{exercise}\normalfont
  8577. Implement the improvements to the \code{explicate\_control} pass.
  8578. Check that it removes trivial blocks in a few example programs. Then
  8579. check that your compiler still passes all of your tests.
  8580. \end{exercise}
  8581. \subsection{Remove Jumps}
  8582. There is an opportunity for removing jumps that is apparent in the
  8583. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8584. ends with a jump to \code{block\_4} and there are no other jumps to
  8585. \code{block\_4} in the rest of the program. In this situation we can
  8586. avoid the runtime overhead of this jump by merging \code{block\_4}
  8587. into the preceding block, in this case the \code{start} block.
  8588. Figure~\ref{fig:remove-jumps} shows the output of
  8589. \code{select\_instructions} on the left and the result of this
  8590. optimization on the right.
  8591. \begin{figure}[tbp]
  8592. {\if\edition\racketEd
  8593. \begin{tabular}{lll}
  8594. \begin{minipage}{0.5\textwidth}
  8595. % cond_test_20.rkt
  8596. \begin{lstlisting}
  8597. start:
  8598. callq read_int
  8599. movq %rax, tmp7951
  8600. cmpq $1, tmp7951
  8601. je block7952
  8602. jmp block7953
  8603. block7953:
  8604. movq $0, %rax
  8605. jmp conclusion
  8606. block7952:
  8607. movq $42, %rax
  8608. jmp conclusion
  8609. \end{lstlisting}
  8610. \end{minipage}
  8611. &
  8612. $\Rightarrow\qquad$
  8613. \begin{minipage}{0.4\textwidth}
  8614. \begin{lstlisting}
  8615. start:
  8616. callq read_int
  8617. movq %rax, tmp7951
  8618. cmpq $1, tmp7951
  8619. je block7952
  8620. movq $0, %rax
  8621. jmp conclusion
  8622. block7952:
  8623. movq $42, %rax
  8624. jmp conclusion
  8625. \end{lstlisting}
  8626. \end{minipage}
  8627. \end{tabular}
  8628. \fi}
  8629. {\if\edition\pythonEd
  8630. \begin{tabular}{lll}
  8631. \begin{minipage}{0.5\textwidth}
  8632. % cond_test_20.rkt
  8633. \begin{lstlisting}
  8634. start:
  8635. callq read_int
  8636. movq %rax, tmp_0
  8637. cmpq 1, tmp_0
  8638. je block_3
  8639. jmp block_4
  8640. block_3:
  8641. movq 42, tmp_1
  8642. jmp block_2
  8643. block_4:
  8644. movq 0, tmp_1
  8645. jmp block_2
  8646. block_2:
  8647. movq tmp_1, %rdi
  8648. callq print_int
  8649. movq 0, %rax
  8650. jmp conclusion
  8651. \end{lstlisting}
  8652. \end{minipage}
  8653. &
  8654. $\Rightarrow\qquad$
  8655. \begin{minipage}{0.4\textwidth}
  8656. \begin{lstlisting}
  8657. start:
  8658. callq read_int
  8659. movq %rax, tmp_0
  8660. cmpq 1, tmp_0
  8661. je block_3
  8662. movq 0, tmp_1
  8663. jmp block_2
  8664. block_3:
  8665. movq 42, tmp_1
  8666. jmp block_2
  8667. block_2:
  8668. movq tmp_1, %rdi
  8669. callq print_int
  8670. movq 0, %rax
  8671. jmp conclusion
  8672. \end{lstlisting}
  8673. \end{minipage}
  8674. \end{tabular}
  8675. \fi}
  8676. \caption{Merging basic blocks by removing unnecessary jumps.}
  8677. \label{fig:remove-jumps}
  8678. \end{figure}
  8679. \begin{exercise}\normalfont
  8680. %
  8681. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8682. into their preceding basic block, when there is only one preceding
  8683. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8684. %
  8685. {\if\edition\racketEd
  8686. In the \code{run-tests.rkt} script, add the following entry to the
  8687. list of \code{passes} between \code{allocate\_registers}
  8688. and \code{patch\_instructions}.
  8689. \begin{lstlisting}
  8690. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8691. \end{lstlisting}
  8692. \fi}
  8693. %
  8694. Run the script to test your compiler.
  8695. %
  8696. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8697. blocks on several test programs.
  8698. \end{exercise}
  8699. \section{Further Reading}
  8700. \label{sec:cond-further-reading}
  8701. The algorithm for the \code{explicate\_control} pass is based on the
  8702. the \code{explose-basic-blocks} pass in the course notes of
  8703. \citet{Dybvig:2010aa}.
  8704. %
  8705. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  8706. \citet{Appel:2003fk}, and is related to translations into continuation
  8707. passing
  8708. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  8709. %
  8710. The treatment of conditionals in the \code{explicate\_control} pass is
  8711. similar to short-cut boolean
  8712. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  8713. and the case-of-case transformation of \citet{PeytonJones:1998}.
  8714. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8715. \chapter{Loops and Dataflow Analysis}
  8716. \label{ch:Lwhile}
  8717. % TODO: define R'_8
  8718. % TODO: multi-graph
  8719. {\if\edition\racketEd
  8720. %
  8721. In this chapter we study two features that are the hallmarks of
  8722. imperative programming languages: loops and assignments to local
  8723. variables. The following example demonstrates these new features by
  8724. computing the sum of the first five positive integers.
  8725. % similar to loop_test_1.rkt
  8726. \begin{lstlisting}
  8727. (let ([sum 0])
  8728. (let ([i 5])
  8729. (begin
  8730. (while (> i 0)
  8731. (begin
  8732. (set! sum (+ sum i))
  8733. (set! i (- i 1))))
  8734. sum)))
  8735. \end{lstlisting}
  8736. The \code{while} loop consists of a condition and a
  8737. body\footnote{The \code{while} loop in particular is not a built-in
  8738. feature of the Racket language, but Racket includes many looping
  8739. constructs and it is straightforward to define \code{while} as a
  8740. macro.}. The body is evaluated repeatedly so long as the condition
  8741. remains true.
  8742. %
  8743. The \code{set!} consists of a variable and a right-hand-side
  8744. expression. The \code{set!} updates value of the variable to the
  8745. value of the right-hand-side.
  8746. %
  8747. The primary purpose of both the \code{while} loop and \code{set!} is
  8748. to cause side effects, so they do not have a meaningful result
  8749. value. Instead their result is the \code{\#<void>} value. The
  8750. expression \code{(void)} is an explicit way to create the
  8751. \code{\#<void>} value and it has type \code{Void}. The
  8752. \code{\#<void>} value can be passed around just like other values
  8753. inside an \LangLoop{} program and a \code{\#<void>} value can be
  8754. compared for equality with another \code{\#<void>} value. However,
  8755. there are no other operations specific to the the \code{\#<void>}
  8756. value in \LangLoop{}. In contrast, Racket defines the \code{void?}
  8757. predicate that returns \code{\#t} when applied to \code{\#<void>} and
  8758. \code{\#f} otherwise.
  8759. %
  8760. \footnote{Racket's \code{Void} type corresponds to what is called the
  8761. \code{Unit} type in the programming languages literature. Racket's
  8762. \code{Void} type is inhabited by a single value \code{\#<void>}
  8763. which corresponds to \code{unit} or \code{()} in the
  8764. literature~\citep{Pierce:2002hj}.}.
  8765. %
  8766. With the addition of side-effecting features such as \code{while} loop
  8767. and \code{set!}, it is helpful to also include in a language feature
  8768. for sequencing side effects: the \code{begin} expression. It consists
  8769. of one or more subexpressions that are evaluated left-to-right.
  8770. %
  8771. \fi}
  8772. {\if\edition\pythonEd
  8773. %
  8774. In this chapter we study loops, one of the hallmarks of imperative
  8775. programming languages. The following example demonstrates the
  8776. \code{while} loop by computing the sum of the first five positive
  8777. integers.
  8778. \begin{lstlisting}
  8779. sum = 0
  8780. i = 5
  8781. while i > 0:
  8782. sum = sum + i
  8783. i = i - 1
  8784. print(sum)
  8785. \end{lstlisting}
  8786. The \code{while} loop consists of a condition expression and a body (a
  8787. sequence of statements). The body is evaluated repeatedly so long as
  8788. the condition remains true.
  8789. %
  8790. \fi}
  8791. \section{The \LangLoop{} Language}
  8792. \newcommand{\LwhileGrammarRacket}{
  8793. \begin{array}{lcl}
  8794. \Type &::=& \key{Void}\\
  8795. \Exp &::=& \CSETBANG{\Var}{\Exp}
  8796. \MID \CBEGIN{\Exp\ldots}{\Exp}
  8797. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  8798. \end{array}
  8799. }
  8800. \newcommand{\LwhileAST}{
  8801. \begin{array}{lcl}
  8802. \Type &::=& \key{Void}\\
  8803. \Exp &::=& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}\\
  8804. &\MID& \WHILE{\Exp}{\Exp} \MID \VOID{}
  8805. \end{array}
  8806. }
  8807. \newcommand{\LwhileGrammarPython}{
  8808. \begin{array}{rcl}
  8809. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  8810. \end{array}
  8811. }
  8812. \newcommand{\LwhileASTPython}{
  8813. \begin{array}{lcl}
  8814. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  8815. \end{array}
  8816. }
  8817. \begin{figure}[tp]
  8818. \centering
  8819. \fbox{
  8820. \begin{minipage}{0.96\textwidth}
  8821. \small
  8822. {\if\edition\racketEd
  8823. \[
  8824. \begin{array}{l}
  8825. \gray{\LintGrammarRacket{}} \\ \hline
  8826. \gray{\LvarGrammarRacket{}} \\ \hline
  8827. \gray{\LifGrammarRacket{}} \\ \hline
  8828. \LwhileGrammarRacket \\
  8829. \begin{array}{lcl}
  8830. \LangLoopM{} &::=& \Exp
  8831. \end{array}
  8832. \end{array}
  8833. \]
  8834. \fi}
  8835. {\if\edition\pythonEd
  8836. \[
  8837. \begin{array}{l}
  8838. \gray{\LintGrammarPython} \\ \hline
  8839. \gray{\LvarGrammarPython} \\ \hline
  8840. \gray{\LifGrammarPython} \\ \hline
  8841. \LwhileGrammarPython \\
  8842. \begin{array}{rcl}
  8843. \LangLoopM{} &::=& \Stmt^{*}
  8844. \end{array}
  8845. \end{array}
  8846. \]
  8847. \fi}
  8848. \end{minipage}
  8849. }
  8850. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-concrete-syntax}).}
  8851. \label{fig:Lwhile-concrete-syntax}
  8852. \end{figure}
  8853. \begin{figure}[tp]
  8854. \centering
  8855. \fbox{
  8856. \begin{minipage}{0.96\textwidth}
  8857. \small
  8858. {\if\edition\racketEd
  8859. \[
  8860. \begin{array}{l}
  8861. \gray{\LintOpAST} \\ \hline
  8862. \gray{\LvarAST{}} \\ \hline
  8863. \gray{\LifAST{}} \\ \hline
  8864. \LwhileAST{} \\
  8865. \begin{array}{lcl}
  8866. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  8867. \end{array}
  8868. \end{array}
  8869. \]
  8870. \fi}
  8871. {\if\edition\pythonEd
  8872. \[
  8873. \begin{array}{l}
  8874. \gray{\LintASTPython} \\ \hline
  8875. \gray{\LvarASTPython} \\ \hline
  8876. \gray{\LifASTPython} \\ \hline
  8877. \LwhileASTPython \\
  8878. \begin{array}{lcl}
  8879. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  8880. \end{array}
  8881. \end{array}
  8882. \]
  8883. \fi}
  8884. \end{minipage}
  8885. }
  8886. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-syntax}).}
  8887. \label{fig:Lwhile-syntax}
  8888. \end{figure}
  8889. The concrete syntax of \LangLoop{} is defined in
  8890. Figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  8891. in Figure~\ref{fig:Lwhile-syntax}.
  8892. %
  8893. The definitional interpreter for \LangLoop{} is shown in
  8894. Figure~\ref{fig:interp-Rwhile}.
  8895. %
  8896. {\if\edition\racketEd
  8897. %
  8898. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  8899. and \code{Void} and we make changes to the cases for \code{Var},
  8900. \code{Let}, and \code{Apply} regarding variables. To support
  8901. assignment to variables and to make their lifetimes indefinite (see
  8902. the second example in Section~\ref{sec:assignment-scoping}), we box
  8903. the value that is bound to each variable (in \code{Let}) and function
  8904. parameter (in \code{Apply}). The case for \code{Var} unboxes the
  8905. value.
  8906. %
  8907. Now to discuss the new cases. For \code{SetBang}, we lookup the
  8908. variable in the environment to obtain a boxed value and then we change
  8909. it using \code{set-box!} to the result of evaluating the right-hand
  8910. side. The result value of a \code{SetBang} is \code{void}.
  8911. %
  8912. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  8913. if the result is true, 2) evaluate the body.
  8914. The result value of a \code{while} loop is also \code{void}.
  8915. %
  8916. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  8917. subexpressions \itm{es} for their effects and then evaluates
  8918. and returns the result from \itm{body}.
  8919. %
  8920. The $\VOID{}$ expression produces the \code{void} value.
  8921. %
  8922. \fi}
  8923. {\if\edition\pythonEd
  8924. %
  8925. We add a new case for \code{While} in the \code{interp\_stmts}
  8926. function, where we repeatedly interpret the \code{body} so long as the
  8927. \code{test} expression remains true.
  8928. %
  8929. \fi}
  8930. \begin{figure}[tbp]
  8931. {\if\edition\racketEd
  8932. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8933. (define interp-Rwhile_class
  8934. (class interp-Rany_class
  8935. (super-new)
  8936. (define/override ((interp-exp env) e)
  8937. (define recur (interp-exp env))
  8938. (match e
  8939. [(SetBang x rhs)
  8940. (set-box! (lookup x env) (recur rhs))]
  8941. [(WhileLoop cnd body)
  8942. (define (loop)
  8943. (cond [(recur cnd) (recur body) (loop)]
  8944. [else (void)]))
  8945. (loop)]
  8946. [(Begin es body)
  8947. (for ([e es]) (recur e))
  8948. (recur body)]
  8949. [(Void) (void)]
  8950. [else ((super interp-exp env) e)]))
  8951. ))
  8952. (define (interp-Rwhile p)
  8953. (send (new interp-Rwhile_class) interp-program p))
  8954. \end{lstlisting}
  8955. \fi}
  8956. {\if\edition\pythonEd
  8957. \begin{lstlisting}
  8958. class InterpLwhile(InterpLif):
  8959. def interp_stmts(self, ss, env):
  8960. if len(ss) == 0:
  8961. return
  8962. match ss[0]:
  8963. case While(test, body, []):
  8964. while self.interp_exp(test, env):
  8965. self.interp_stmts(body, env)
  8966. return self.interp_stmts(ss[1:], env)
  8967. case _:
  8968. return super().interp_stmts(ss, env)
  8969. \end{lstlisting}
  8970. \fi}
  8971. \caption{Interpreter for \LangLoop{}.}
  8972. \label{fig:interp-Rwhile}
  8973. \end{figure}
  8974. The type checker for \LangLoop{} is defined in
  8975. Figure~\ref{fig:type-check-Rwhile}.
  8976. %
  8977. {\if\edition\racketEd
  8978. %
  8979. For \LangLoop{} we add a type named \code{Void} and the only value of
  8980. this type is the \code{void} value.
  8981. %
  8982. The type checking of the \code{SetBang} expression requires the type of
  8983. the variable and the right-hand-side to agree. The result type is
  8984. \code{Void}. For \code{while}, the condition must be a
  8985. \code{Boolean}. The result type is also \code{Void}. For
  8986. \code{Begin}, the result type is the type of its last subexpression.
  8987. %
  8988. \fi}
  8989. %
  8990. {\if\edition\pythonEd
  8991. %
  8992. A \code{while} loop is well typed if the type of the \code{test}
  8993. expression is \code{bool} and the statements in the \code{body} are
  8994. well typed.
  8995. %
  8996. \fi}
  8997. \begin{figure}[tbp]
  8998. {\if\edition\racketEd
  8999. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9000. (define type-check-Rwhile_class
  9001. (class type-check-Rany_class
  9002. (super-new)
  9003. (inherit check-type-equal?)
  9004. (define/override (type-check-exp env)
  9005. (lambda (e)
  9006. (define recur (type-check-exp env))
  9007. (match e
  9008. [(SetBang x rhs)
  9009. (define-values (rhs^ rhsT) (recur rhs))
  9010. (define varT (dict-ref env x))
  9011. (check-type-equal? rhsT varT e)
  9012. (values (SetBang x rhs^) 'Void)]
  9013. [(WhileLoop cnd body)
  9014. (define-values (cnd^ Tc) (recur cnd))
  9015. (check-type-equal? Tc 'Boolean e)
  9016. (define-values (body^ Tbody) ((type-check-exp env) body))
  9017. (values (WhileLoop cnd^ body^) 'Void)]
  9018. [(Begin es body)
  9019. (define-values (es^ ts)
  9020. (for/lists (l1 l2) ([e es]) (recur e)))
  9021. (define-values (body^ Tbody) (recur body))
  9022. (values (Begin es^ body^) Tbody)]
  9023. [else ((super type-check-exp env) e)])))
  9024. ))
  9025. (define (type-check-Rwhile p)
  9026. (send (new type-check-Rwhile_class) type-check-program p))
  9027. \end{lstlisting}
  9028. \fi}
  9029. {\if\edition\pythonEd
  9030. \begin{lstlisting}
  9031. class TypeCheckLwhile(TypeCheckLif):
  9032. def type_check_stmts(self, ss, env):
  9033. if len(ss) == 0:
  9034. return
  9035. match ss[0]:
  9036. case While(test, body, []):
  9037. test_t = self.type_check_exp(test, env)
  9038. check_type_equal(bool, test_t, test)
  9039. body_t = self.type_check_stmts(body, env)
  9040. return self.type_check_stmts(ss[1:], env)
  9041. case _:
  9042. return super().type_check_stmts(ss, env)
  9043. \end{lstlisting}
  9044. \fi}
  9045. \caption{Type checker for the \LangLoop{} language.}
  9046. \label{fig:type-check-Rwhile}
  9047. \end{figure}
  9048. {\if\edition\racketEd
  9049. %
  9050. At first glance, the translation of these language features to x86
  9051. seems straightforward because the \LangCIf{} intermediate language
  9052. already supports all of the ingredients that we need: assignment,
  9053. \code{goto}, conditional branching, and sequencing. However, there are
  9054. complications that arise which we discuss in the next section. After
  9055. that we introduce the changes necessary to the existing passes.
  9056. %
  9057. \fi}
  9058. {\if\edition\pythonEd
  9059. %
  9060. At first glance, the translation of \code{while} loops to x86 seems
  9061. straightforward because the \LangCIf{} intermediate language already
  9062. supports \code{goto} and conditional branching. However, there are
  9063. complications that arise which we discuss in the next section. After
  9064. that we introduce the changes necessary to the existing passes.
  9065. %
  9066. \fi}
  9067. \section{Cyclic Control Flow and Dataflow Analysis}
  9068. \label{sec:dataflow-analysis}
  9069. Up until this point the control-flow graphs of the programs generated
  9070. in \code{explicate\_control} were guaranteed to be acyclic. However,
  9071. each \code{while} loop introduces a cycle in the control-flow graph.
  9072. But does that matter?
  9073. %
  9074. Indeed it does. Recall that for register allocation, the compiler
  9075. performs liveness analysis to determine which variables can share the
  9076. same register. To accomplish this we analyzed the control-flow graph
  9077. in reverse topological order
  9078. (Section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9079. only well-defined for acyclic graphs.
  9080. Let us return to the example of computing the sum of the first five
  9081. positive integers. Here is the program after instruction selection but
  9082. before register allocation.
  9083. \begin{center}
  9084. {\if\edition\racketEd
  9085. \begin{minipage}{0.45\textwidth}
  9086. \begin{lstlisting}
  9087. (define (main) : Integer
  9088. mainstart:
  9089. movq $0, sum
  9090. movq $5, i
  9091. jmp block5
  9092. block5:
  9093. movq i, tmp3
  9094. cmpq tmp3, $0
  9095. jl block7
  9096. jmp block8
  9097. \end{lstlisting}
  9098. \end{minipage}
  9099. \begin{minipage}{0.45\textwidth}
  9100. \begin{lstlisting}
  9101. block7:
  9102. addq i, sum
  9103. movq $1, tmp4
  9104. negq tmp4
  9105. addq tmp4, i
  9106. jmp block5
  9107. block8:
  9108. movq $27, %rax
  9109. addq sum, %rax
  9110. jmp mainconclusion
  9111. )
  9112. \end{lstlisting}
  9113. \end{minipage}
  9114. \fi}
  9115. {\if\edition\pythonEd
  9116. \begin{minipage}{0.45\textwidth}
  9117. \begin{lstlisting}
  9118. mainstart:
  9119. movq $0, sum
  9120. movq $5, i
  9121. jmp block5
  9122. block5:
  9123. cmpq $0, i
  9124. jg block7
  9125. jmp block8
  9126. \end{lstlisting}
  9127. \end{minipage}
  9128. \begin{minipage}{0.45\textwidth}
  9129. \begin{lstlisting}
  9130. block7:
  9131. addq i, sum
  9132. subq $1, i
  9133. jmp block5
  9134. block8:
  9135. movq sum, %rdi
  9136. callq print_int
  9137. movq $0, %rax
  9138. jmp mainconclusion
  9139. \end{lstlisting}
  9140. \end{minipage}
  9141. \fi}
  9142. \end{center}
  9143. Recall that liveness analysis works backwards, starting at the end
  9144. of each function. For this example we could start with \code{block8}
  9145. because we know what is live at the beginning of the conclusion,
  9146. just \code{rax} and \code{rsp}. So the live-before set
  9147. for \code{block8} is $\{\ttm{rsp},\ttm{sum}\}$.
  9148. %
  9149. Next we might try to analyze \code{block5} or \code{block7}, but
  9150. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9151. we are stuck.
  9152. The way out of this impasse is to realize that we can compute an
  9153. under-approximation of the live-before set by starting with empty
  9154. live-after sets. By \emph{under-approximation}, we mean that the set
  9155. only contains variables that are live for some execution of the
  9156. program, but the set may be missing some variables. Next, the
  9157. under-approximations for each block can be improved by 1) updating the
  9158. live-after set for each block using the approximate live-before sets
  9159. from the other blocks and 2) perform liveness analysis again on each
  9160. block. In fact, by iterating this process, the under-approximations
  9161. eventually become the correct solutions!
  9162. %
  9163. This approach of iteratively analyzing a control-flow graph is
  9164. applicable to many static analysis problems and goes by the name
  9165. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9166. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9167. Washington.
  9168. Let us apply this approach to the above example. We use the empty set
  9169. for the initial live-before set for each block. Let $m_0$ be the
  9170. following mapping from label names to sets of locations (variables and
  9171. registers).
  9172. \begin{center}
  9173. \begin{lstlisting}
  9174. mainstart: {}, block5: {}, block7: {}, block8: {}
  9175. \end{lstlisting}
  9176. \end{center}
  9177. Using the above live-before approximations, we determine the
  9178. live-after for each block and then apply liveness analysis to each
  9179. block. This produces our next approximation $m_1$ of the live-before
  9180. sets.
  9181. \begin{center}
  9182. \begin{lstlisting}
  9183. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9184. \end{lstlisting}
  9185. \end{center}
  9186. For the second round, the live-after for \code{mainstart} is the
  9187. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9188. liveness analysis for \code{mainstart} computes the empty set. The
  9189. live-after for \code{block5} is the union of the live-before sets for
  9190. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9191. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9192. sum\}}. The live-after for \code{block7} is the live-before for
  9193. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9194. So the liveness analysis for \code{block7} remains \code{\{i,
  9195. sum\}}. Together these yield the following approximation $m_2$ of
  9196. the live-before sets.
  9197. \begin{center}
  9198. \begin{lstlisting}
  9199. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9200. \end{lstlisting}
  9201. \end{center}
  9202. In the preceding iteration, only \code{block5} changed, so we can
  9203. limit our attention to \code{mainstart} and \code{block7}, the two
  9204. blocks that jump to \code{block5}. As a result, the live-before sets
  9205. for \code{mainstart} and \code{block7} are updated to include
  9206. \code{rsp}, yielding the following approximation $m_3$.
  9207. \begin{center}
  9208. \begin{lstlisting}
  9209. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9210. \end{lstlisting}
  9211. \end{center}
  9212. Because \code{block7} changed, we analyze \code{block5} once more, but
  9213. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9214. our approximations have converged, so $m_3$ is the solution.
  9215. This iteration process is guaranteed to converge to a solution by the
  9216. Kleene Fixed-Point Theorem, a general theorem about functions on
  9217. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9218. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9219. elements, a least element $\bot$ (pronounced bottom), and a join
  9220. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9221. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9222. working with join semi-lattices.} When two elements are ordered $m_i
  9223. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9224. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9225. approximation than $m_i$. The bottom element $\bot$ represents the
  9226. complete lack of information, i.e., the worst approximation. The join
  9227. operator takes two lattice elements and combines their information,
  9228. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9229. bound}
  9230. A dataflow analysis typically involves two lattices: one lattice to
  9231. represent abstract states and another lattice that aggregates the
  9232. abstract states of all the blocks in the control-flow graph. For
  9233. liveness analysis, an abstract state is a set of locations. We form
  9234. the lattice $L$ by taking its elements to be sets of locations, the
  9235. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9236. set, and the join operator to be set union.
  9237. %
  9238. We form a second lattice $M$ by taking its elements to be mappings
  9239. from the block labels to sets of locations (elements of $L$). We
  9240. order the mappings point-wise, using the ordering of $L$. So given any
  9241. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9242. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9243. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9244. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9245. We can think of one iteration of liveness analysis applied to the
  9246. whole program as being a function $f$ on the lattice $M$. It takes a
  9247. mapping as input and computes a new mapping.
  9248. \[
  9249. f(m_i) = m_{i+1}
  9250. \]
  9251. Next let us think for a moment about what a final solution $m_s$
  9252. should look like. If we perform liveness analysis using the solution
  9253. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9254. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9255. \[
  9256. f(m_s) = m_s
  9257. \]
  9258. Furthermore, the solution should only include locations that are
  9259. forced to be there by performing liveness analysis on the program, so
  9260. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9261. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9262. monotone (better inputs produce better outputs), then the least fixed
  9263. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9264. chain} obtained by starting at $\bot$ and iterating $f$ as
  9265. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9266. \[
  9267. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9268. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9269. \]
  9270. When a lattice contains only finitely-long ascending chains, then
  9271. every Kleene chain tops out at some fixed point after some number of
  9272. iterations of $f$.
  9273. \[
  9274. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9275. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9276. \]
  9277. The liveness analysis is indeed a monotone function and the lattice
  9278. $M$ only has finitely-long ascending chains because there are only a
  9279. finite number of variables and blocks in the program. Thus we are
  9280. guaranteed that iteratively applying liveness analysis to all blocks
  9281. in the program will eventually produce the least fixed point solution.
  9282. Next let us consider dataflow analysis in general and discuss the
  9283. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9284. %
  9285. The algorithm has four parameters: the control-flow graph \code{G}, a
  9286. function \code{transfer} that applies the analysis to one block, the
  9287. \code{bottom} and \code{join} operator for the lattice of abstract
  9288. states. The algorithm begins by creating the bottom mapping,
  9289. represented by a hash table. It then pushes all of the nodes in the
  9290. control-flow graph onto the work list (a queue). The algorithm repeats
  9291. the \code{while} loop as long as there are items in the work list. In
  9292. each iteration, a node is popped from the work list and processed. The
  9293. \code{input} for the node is computed by taking the join of the
  9294. abstract states of all the predecessor nodes. The \code{transfer}
  9295. function is then applied to obtain the \code{output} abstract
  9296. state. If the output differs from the previous state for this block,
  9297. the mapping for this block is updated and its successor nodes are
  9298. pushed onto the work list.
  9299. Note that the \code{analyze\_dataflow} function is formulated as a
  9300. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9301. function come from the predecessor nodes in the control-flow
  9302. graph. However, liveness analysis is a \emph{backward} dataflow
  9303. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9304. function with the transpose of the control-flow graph.
  9305. \begin{figure}[tb]
  9306. {\if\edition\racketEd
  9307. \begin{lstlisting}
  9308. (define (analyze_dataflow G transfer bottom join)
  9309. (define mapping (make-hash))
  9310. (for ([v (in-vertices G)])
  9311. (dict-set! mapping v bottom))
  9312. (define worklist (make-queue))
  9313. (for ([v (in-vertices G)])
  9314. (enqueue! worklist v))
  9315. (define trans-G (transpose G))
  9316. (while (not (queue-empty? worklist))
  9317. (define node (dequeue! worklist))
  9318. (define input (for/fold ([state bottom])
  9319. ([pred (in-neighbors trans-G node)])
  9320. (join state (dict-ref mapping pred))))
  9321. (define output (transfer node input))
  9322. (cond [(not (equal? output (dict-ref mapping node)))
  9323. (dict-set! mapping node output)
  9324. (for ([v (in-neighbors G node)])
  9325. (enqueue! worklist v))]))
  9326. mapping)
  9327. \end{lstlisting}
  9328. \fi}
  9329. {\if\edition\pythonEd
  9330. \begin{lstlisting}
  9331. def analyze_dataflow(G, transfer, bottom, join):
  9332. trans_G = transpose(G)
  9333. mapping = {}
  9334. for v in G.vertices():
  9335. mapping[v] = bottom
  9336. worklist = deque()
  9337. for v in G.vertices():
  9338. worklist.append(v)
  9339. while worklist:
  9340. node = worklist.pop()
  9341. input = reduce(join, [mapping[v] for v in trans_G.adjacent(node)], bottom)
  9342. output = transfer(node, input)
  9343. if output != mapping[node]:
  9344. mapping[node] = output
  9345. for v in G.adjacent(node):
  9346. worklist.append(v)
  9347. \end{lstlisting}
  9348. \fi}
  9349. \caption{Generic work list algorithm for dataflow analysis}
  9350. \label{fig:generic-dataflow}
  9351. \end{figure}
  9352. {\if\edition\racketEd
  9353. \section{Mutable Variables \& Remove Complex Operands}
  9354. There is a subtle interaction between the addition of \code{set!}, the
  9355. \code{remove\_complex\_operands} pass, and the left-to-right order of
  9356. evaluation of Racket. Consider the following example.
  9357. \begin{lstlisting}
  9358. (let ([x 2])
  9359. (+ x (begin (set! x 40) x)))
  9360. \end{lstlisting}
  9361. The result of this program is \code{42} because the first read from
  9362. \code{x} produces \code{2} and the second produces \code{40}. However,
  9363. if we naively apply the \code{remove\_complex\_operands} pass to this
  9364. example we obtain the following program whose result is \code{80}!
  9365. \begin{lstlisting}
  9366. (let ([x 2])
  9367. (let ([tmp (begin (set! x 40) x)])
  9368. (+ x tmp)))
  9369. \end{lstlisting}
  9370. The problem is that, with mutable variables, the ordering between
  9371. reads and writes is important, and the
  9372. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9373. before the first read of \code{x}.
  9374. We recommend solving this problem by giving special treatment to reads
  9375. from mutable variables, that is, variables that occur on the left-hand
  9376. side of a \code{set!}. We mark each read from a mutable variable with
  9377. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9378. that the read operation is effectful in that it can produce different
  9379. results at different points in time. Let's apply this idea to the
  9380. following variation that also involves a variable that is not mutated.
  9381. % loop_test_24.rkt
  9382. \begin{lstlisting}
  9383. (let ([x 2])
  9384. (let ([y 0])
  9385. (+ y (+ x (begin (set! x 40) x)))))
  9386. \end{lstlisting}
  9387. We analyze the above program to discover that variable \code{x} is
  9388. mutable but \code{y} is not. We then transform the program as follows,
  9389. replacing each occurence of \code{x} with \code{(get! x)}.
  9390. \begin{lstlisting}
  9391. (let ([x 2])
  9392. (let ([y 0])
  9393. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9394. \end{lstlisting}
  9395. Now that we have a clear distinction between reads from mutable and
  9396. immutable variables, we can apply the \code{remove\_complex\_operands}
  9397. pass, where reads from immutable variables are still classified as
  9398. atomic expressions but reads from mutable variables are classified as
  9399. complex. Thus, \code{remove\_complex\_operands} yields the following
  9400. program.
  9401. \begin{lstlisting}
  9402. (let ([x 2])
  9403. (let ([y 0])
  9404. (+ y (let ([t1 (get! x)])
  9405. (let ([t2 (begin (set! x 40) (get! x))])
  9406. (+ t1 t2))))))
  9407. \end{lstlisting}
  9408. The temporary variable \code{t1} gets the value of \code{x} before the
  9409. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9410. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9411. do not generate a temporary variable for the occurence of \code{y}
  9412. because it's an immutable variable. We want to avoid such unnecessary
  9413. extra temporaries because they would needless increase the number of
  9414. variables, making it more likely for some of them to be spilled. The
  9415. result of this program is \code{42}, the same as the result prior to
  9416. \code{remove\_complex\_operands}.
  9417. The approach that we've sketched above requires only a small
  9418. modification to \code{remove\_complex\_operands} to handle
  9419. \code{get!}. However, it requires a new pass, called
  9420. \code{uncover-get!}, that we discuss in
  9421. Section~\ref{sec:uncover-get-bang}.
  9422. As an aside, this problematic interaction between \code{set!} and the
  9423. pass \code{remove\_complex\_operands} is particular to Racket and not
  9424. its predecessor, the Scheme language. The key difference is that
  9425. Scheme does not specify an order of evaluation for the arguments of an
  9426. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9427. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9428. would be correct results for the example program. Interestingly,
  9429. Racket is implemented on top of the Chez Scheme
  9430. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9431. presented in this section (using extra \code{let} bindings to control
  9432. the order of evaluation) is used in the translation from Racket to
  9433. Scheme~\citep{Flatt:2019tb}.
  9434. \fi} % racket
  9435. Having discussed the complications that arise from adding support for
  9436. assignment and loops, we turn to discussing the individual compilation
  9437. passes.
  9438. {\if\edition\racketEd
  9439. \section{Uncover \texttt{get!}}
  9440. \label{sec:uncover-get-bang}
  9441. The goal of this pass it to mark uses of mutable variables so that
  9442. \code{remove\_complex\_operands} can treat them as complex expressions
  9443. and thereby preserve their ordering relative to the side-effects in
  9444. other operands. So the first step is to collect all the mutable
  9445. variables. We recommend creating an auxilliary function for this,
  9446. named \code{collect-set!}, that recursively traverses expressions,
  9447. returning a set of all variables that occur on the left-hand side of a
  9448. \code{set!}. Here's an exerpt of its implementation.
  9449. \begin{center}
  9450. \begin{minipage}{\textwidth}
  9451. \begin{lstlisting}
  9452. (define (collect-set! e)
  9453. (match e
  9454. [(Var x) (set)]
  9455. [(Int n) (set)]
  9456. [(Let x rhs body)
  9457. (set-union (collect-set! rhs) (collect-set! body))]
  9458. [(SetBang var rhs)
  9459. (set-union (set var) (collect-set! rhs))]
  9460. ...))
  9461. \end{lstlisting}
  9462. \end{minipage}
  9463. \end{center}
  9464. By placing this pass after \code{uniquify}, we need not worry about
  9465. variable shadowing and our logic for \code{let} can remain simple, as
  9466. in the exerpt above.
  9467. The second step is to mark the occurences of the mutable variables
  9468. with the new \code{GetBang} AST node (\code{get!} in concrete
  9469. syntax). The following is an exerpt of the \code{uncover-get!-exp}
  9470. function, which takes two parameters: the set of mutable varaibles
  9471. \code{set!-vars}, and the expression \code{e} to be processed. The
  9472. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9473. mutable variable or leaves it alone if not.
  9474. \begin{center}
  9475. \begin{minipage}{\textwidth}
  9476. \begin{lstlisting}
  9477. (define ((uncover-get!-exp set!-vars) e)
  9478. (match e
  9479. [(Var x)
  9480. (if (set-member? set!-vars x)
  9481. (GetBang x)
  9482. (Var x))]
  9483. ...))
  9484. \end{lstlisting}
  9485. \end{minipage}
  9486. \end{center}
  9487. To wrap things up, define the \code{uncover-get!} function for
  9488. processing a whole program, using \code{collect-set!} to obtain the
  9489. set of mutable variables and then \code{uncover-get!-exp} to replace
  9490. their occurences with \code{GetBang}.
  9491. \fi}
  9492. \section{Remove Complex Operands}
  9493. \label{sec:rco-loop}
  9494. {\if\edition\racketEd
  9495. %
  9496. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9497. \code{while} are all complex expressions. The subexpressions of
  9498. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9499. %
  9500. \fi}
  9501. {\if\edition\pythonEd
  9502. %
  9503. The change needed for this pass is to add a case for the \code{while}
  9504. statement. The condition of a \code{while} loop is allowed to be a
  9505. complex expression, just like the condition of the \code{if}
  9506. statement.
  9507. %
  9508. \fi}
  9509. %
  9510. Figure~\ref{fig:Rwhile-anf-syntax} defines the output language
  9511. \LangLoopANF{} of this pass.
  9512. \begin{figure}[tp]
  9513. \centering
  9514. \fbox{
  9515. \begin{minipage}{0.96\textwidth}
  9516. \small
  9517. {\if\edition\racketEd
  9518. \[
  9519. \begin{array}{rcl}
  9520. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  9521. \MID \VOID{} } \\
  9522. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9523. &\MID& \GETBANG{\Var}
  9524. \MID \SETBANG{\Var}{\Exp} \\
  9525. &\MID& \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9526. \MID \WHILE{\Exp}{\Exp} \\
  9527. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9528. \LangLoopANF &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9529. \end{array}
  9530. \]
  9531. \fi}
  9532. {\if\edition\pythonEd
  9533. \[
  9534. \begin{array}{rcl}
  9535. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9536. \Exp &::=& \Atm \MID \READ{} \\
  9537. &\MID& \BINOP{\itm{binaryop}}{\Atm}{\Atm} \MID \UNIOP{\key{unaryop}}{\Atm} \\
  9538. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9539. % &\MID& \LET{\Var}{\Exp}{\Exp}\\
  9540. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9541. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9542. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9543. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9544. \end{array}
  9545. \]
  9546. \fi}
  9547. \end{minipage}
  9548. }
  9549. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9550. \label{fig:Rwhile-anf-syntax}
  9551. \end{figure}
  9552. {\if\edition\racketEd
  9553. As usual, when a complex expression appears in a grammar position that
  9554. needs to be atomic, such as the argument of a primitive operator, we
  9555. must introduce a temporary variable and bind it to the complex
  9556. expression. This approach applies, unchanged, to handle the new
  9557. language forms. For example, in the following code there are two
  9558. \code{begin} expressions appearing as arguments to \code{+}. The
  9559. output of \code{rco\_exp} is shown below, in which the \code{begin}
  9560. expressions have been bound to temporary variables. Recall that
  9561. \code{let} expressions in \LangLoopANF{} are allowed to have
  9562. arbitrary expressions in their right-hand-side expression, so it is
  9563. fine to place \code{begin} there.
  9564. \begin{center}
  9565. \begin{minipage}{\textwidth}
  9566. \begin{lstlisting}
  9567. (let ([x0 10])
  9568. (let ([y1 0])
  9569. (+ (+ (begin (set! y1 (read)) x0)
  9570. (begin (set! x0 (read)) y1))
  9571. x0)))
  9572. |$\Rightarrow$|
  9573. (let ([x0 10])
  9574. (let ([y1 0])
  9575. (let ([tmp2 (begin (set! y1 (read)) x0)])
  9576. (let ([tmp3 (begin (set! x0 (read)) y1)])
  9577. (let ([tmp4 (+ tmp2 tmp3)])
  9578. (+ tmp4 x0))))))
  9579. \end{lstlisting}
  9580. \end{minipage}
  9581. \end{center}
  9582. \fi}
  9583. \section{Explicate Control \racket{and \LangCLoop{}}}
  9584. \label{sec:explicate-loop}
  9585. {\if\edition\racketEd
  9586. Recall that in the \code{explicate\_control} pass we define one helper
  9587. function for each kind of position in the program. For the \LangVar{}
  9588. language of integers and variables we needed kinds of positions:
  9589. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  9590. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  9591. yet another kind of position: effect position. Except for the last
  9592. subexpression, the subexpressions inside a \code{begin} are evaluated
  9593. only for their effect. Their result values are discarded. We can
  9594. generate better code by taking this fact into account.
  9595. The output language of \code{explicate\_control} is \LangCLoop{}
  9596. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9597. \LangCLam{}. The only syntactic difference is that \code{Call} and
  9598. \code{read} may also appear as statements. The most significant
  9599. difference between \LangCLam{} and \LangCLoop{} is that the
  9600. control-flow graphs of the later may contain cycles.
  9601. \begin{figure}[tp]
  9602. \fbox{
  9603. \begin{minipage}{0.96\textwidth}
  9604. \small
  9605. \[
  9606. \begin{array}{lcl}
  9607. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9608. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  9609. &\MID& \CALL{\Atm}{\LP\Atm\ldots\RP} \MID \READ{}\\
  9610. % &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  9611. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  9612. \LangCLoopM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  9613. \end{array}
  9614. \]
  9615. \end{minipage}
  9616. }
  9617. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9618. \label{fig:c7-syntax}
  9619. \end{figure}
  9620. The new auxiliary function \code{explicate\_effect} takes an
  9621. expression (in an effect position) and a continuation. The function
  9622. returns a $\Tail$ that includes the generated code for the input
  9623. expression followed by the continuation. If the expression is
  9624. obviously pure, that is, never causes side effects, then the
  9625. expression can be removed, so the result is just the continuation.
  9626. %
  9627. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9628. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9629. the loop. Recursively process the \itm{body} (in effect position)
  9630. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9631. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9632. \itm{body'} as the then-branch and the continuation block as the
  9633. else-branch. The result should be added to the control-flow graph with
  9634. the label \itm{loop}. The result for the whole \code{while} loop is a
  9635. \code{goto} to the \itm{loop} label.
  9636. The auxiliary functions for tail, assignment, and predicate positions
  9637. need to be updated. The three new language forms, \code{while},
  9638. \code{set!}, and \code{begin}, can appear in assignment and tail
  9639. positions. Only \code{begin} may appear in predicate positions; the
  9640. other two have result type \code{Void}.
  9641. \fi}
  9642. %
  9643. {\if\edition\pythonEd
  9644. %
  9645. The output of this pass is the language \LangCIf{}. No new language
  9646. features are needed in the output because a \code{while} loop can be
  9647. expressed in terms of \code{goto} and \code{if} statements, which are
  9648. already in \LangCIf{}.
  9649. %
  9650. Add a case for the \code{while} statement to the
  9651. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  9652. the condition expression.
  9653. %
  9654. \fi}
  9655. {\if\edition\racketEd
  9656. \section{Select Instructions}
  9657. \label{sec:select-instructions-loop}
  9658. Only three small additions are needed in the
  9659. \code{select\_instructions} pass to handle the changes to
  9660. \LangCLoop{}. That is, a \code{Call} to \code{read} may now appear as a
  9661. stand-alone statement instead of only appearing on the right-hand
  9662. side of an assignment statement. The code generation is nearly
  9663. identical; just leave off the instruction for moving the result into
  9664. the left-hand side.
  9665. \fi}
  9666. \section{Register Allocation}
  9667. \label{sec:register-allocation-loop}
  9668. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9669. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9670. which complicates the liveness analysis needed for register
  9671. allocation.
  9672. \subsection{Liveness Analysis}
  9673. \label{sec:liveness-analysis-r8}
  9674. We recommend using the generic \code{analyze\_dataflow} function that
  9675. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9676. perform liveness analysis, replacing the code in
  9677. \code{uncover\_live} that processed the basic blocks in topological
  9678. order (Section~\ref{sec:liveness-analysis-Lif}).
  9679. The \code{analyze\_dataflow} function has four parameters.
  9680. \begin{enumerate}
  9681. \item The first parameter \code{G} should be a directed graph from the
  9682. \racket{
  9683. \code{racket/graph} package (see the sidebar in
  9684. Section~\ref{sec:build-interference})}
  9685. \python{\code{graph.py} file in the support code}
  9686. that represents the
  9687. control-flow graph.
  9688. \item The second parameter \code{transfer} is a function that applies
  9689. liveness analysis to a basic block. It takes two parameters: the
  9690. label for the block to analyze and the live-after set for that
  9691. block. The transfer function should return the live-before set for
  9692. the block.
  9693. %
  9694. \racket{Also, as a side-effect, it should update the block's
  9695. $\itm{info}$ with the liveness information for each instruction.}
  9696. %
  9697. \python{Also, as a side-effect, it should update the live-before and
  9698. live-after sets for each instruction.}
  9699. %
  9700. To implement the \code{transfer} function, you should be able to
  9701. reuse the code you already have for analyzing basic blocks.
  9702. \item The third and fourth parameters of \code{analyze\_dataflow} are
  9703. \code{bottom} and \code{join} for the lattice of abstract states,
  9704. i.e. sets of locations. The bottom of the lattice is the empty set
  9705. and the join operator is set union.
  9706. \end{enumerate}
  9707. \begin{figure}[p]
  9708. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9709. \node (Rfun) at (0,2) {\large \LangLoop{}};
  9710. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  9711. %\node (Rfun-3) at (6,2) {\large \LangLoop{}};
  9712. %\node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  9713. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  9714. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  9715. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  9716. \node (F1-4) at (6,2) {\large \LangLoop{}};
  9717. \node (F1-5) at (9,2) {\large \LangLoopANF{}};
  9718. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  9719. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  9720. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  9721. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  9722. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  9723. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  9724. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  9725. %% \path[->,bend left=15] (Rfun) edge [above] node
  9726. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  9727. \path[->,bend left=15] (Rfun) edge [above] node
  9728. {\ttfamily\footnotesize shrink} (Rfun-2);
  9729. \path[->,bend left=15] (Rfun-2) edge [above] node
  9730. {\ttfamily\footnotesize uniquify} (F1-4);
  9731. %% \path[->,bend left=15] (Rfun-3) edge [above] node
  9732. %% {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  9733. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9734. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  9735. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9736. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  9737. %% \path[->,bend right=15] (F1-2) edge [above] node
  9738. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  9739. %% \path[->,bend right=15] (F1-3) edge [above] node
  9740. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9741. \path[->,bend left=15] (F1-4) edge [above] node
  9742. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  9743. \path[->,bend left=15] (F1-5) edge [right] node
  9744. {\ttfamily\footnotesize explicate\_control} (C3-2);
  9745. \path[->,bend left=15] (C3-2) edge [left] node
  9746. {\ttfamily\footnotesize select\_instr.} (x86-2);
  9747. \path[->,bend right=15] (x86-2) edge [left] node
  9748. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9749. \path[->,bend right=15] (x86-2-1) edge [below] node
  9750. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  9751. \path[->,bend right=15] (x86-2-2) edge [left] node
  9752. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  9753. \path[->,bend left=15] (x86-3) edge [above] node
  9754. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  9755. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  9756. \end{tikzpicture}
  9757. \caption{Diagram of the passes for \LangLoop{}.}
  9758. \label{fig:Rwhile-passes}
  9759. \end{figure}
  9760. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  9761. for the compilation of \LangLoop{}.
  9762. % Further Reading: dataflow analysis
  9763. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9764. \chapter{Tuples and Garbage Collection}
  9765. \label{ch:Lvec}
  9766. \index{subject}{tuple}
  9767. \index{subject}{vector}
  9768. \index{subject}{allocate}
  9769. \index{subject}{heap allocate}
  9770. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  9771. %% all the IR grammars are spelled out! \\ --Jeremy}
  9772. %% \margincomment{\scriptsize Be more explicit about how to deal with
  9773. %% the root stack. \\ --Jeremy}
  9774. In this chapter we study the implementation of
  9775. tuples\racket{, called vectors in Racket}.
  9776. %
  9777. This language feature is the first of ours to use the computer's
  9778. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  9779. indefinite, that is, a tuple lives forever from the programmer's
  9780. viewpoint. Of course, from an implementer's viewpoint, it is important
  9781. to reclaim the space associated with a tuple when it is no longer
  9782. needed, which is why we also study \emph{garbage collection}
  9783. \index{garbage collection} techniques in this chapter.
  9784. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  9785. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  9786. language of Chapter~\ref{ch:Lwhile} with tuples.
  9787. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  9788. copying live objects back and forth between two halves of the
  9789. heap. The garbage collector requires coordination with the compiler so
  9790. that it can see all of the \emph{root} pointers, that is, pointers in
  9791. registers or on the procedure call stack.
  9792. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  9793. discuss all the necessary changes and additions to the compiler
  9794. passes, including a new compiler pass named \code{expose\_allocation}.
  9795. \section{The \LangVec{} Language}
  9796. \label{sec:r3}
  9797. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  9798. \LangVec{} and Figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  9799. %
  9800. \racket{The \LangVec{} language includes the forms: \code{vector} for
  9801. creating a tuple, \code{vector-ref} for reading an element of a
  9802. tuple, \code{vector-set!} for writing to an element of a tuple, and
  9803. \code{vector-length} for obtaining the number of elements of a
  9804. tuple.}
  9805. %
  9806. \python{The \LangVec{} language adds 1) tuple creation via a
  9807. comma-separated list of expressions, 2) accessing an element of a
  9808. tuple with the square bracket notation, i.e., \code{t[n]} returns
  9809. the nth element of the tuple \code{t}, 3) the \code{is} comparison
  9810. operator, and 4) obtaining the number of elements (the length) of a
  9811. tuple.}
  9812. %
  9813. The program below shows an example use of tuples. It creates a 3-tuple
  9814. \code{t} and a 1-tuple that is stored at index $2$ of the 3-tuple,
  9815. demonstrating that tuples are first-class values. The element at
  9816. index $1$ of \code{t} is \racket{\code{\#t}}\python{\code{True}}, so the
  9817. ``then'' branch of the \key{if} is taken. The element at index $0$ of
  9818. \code{t} is \code{40}, to which we add \code{2}, the element at index
  9819. $0$ of the 1-tuple. So the result of the program is \code{42}.
  9820. %
  9821. {\if\edition\racketEd
  9822. \begin{lstlisting}
  9823. (let ([t (vector 40 #t (vector 2))])
  9824. (if (vector-ref t 1)
  9825. (+ (vector-ref t 0)
  9826. (vector-ref (vector-ref t 2) 0))
  9827. 44))
  9828. \end{lstlisting}
  9829. \fi}
  9830. {\if\edition\pythonEd
  9831. \begin{lstlisting}
  9832. t = 40, True, (2,)
  9833. print( t[0] + t[2][0] if t[1] else 44 )
  9834. \end{lstlisting}
  9835. \fi}
  9836. \newcommand{\LtupGrammarRacket}{
  9837. \begin{array}{lcl}
  9838. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  9839. \Exp &::=& \LP\key{vector}\;\Exp\ldots\RP
  9840. \MID \LP\key{vector-length}\;\Exp\RP \\
  9841. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  9842. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  9843. \end{array}
  9844. }
  9845. \newcommand{\LtupASTRacket}{
  9846. \begin{array}{lcl}
  9847. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  9848. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  9849. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  9850. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  9851. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  9852. \end{array}
  9853. }
  9854. \newcommand{\LtupGrammarPython}{
  9855. \begin{array}{rcl}
  9856. \itm{cmp} &::= & \key{is} \\
  9857. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp} \MID \CLEN{\Exp}
  9858. \end{array}
  9859. }
  9860. \newcommand{\LtupASTPython}{
  9861. \begin{array}{lcl}
  9862. \itm{cmp} &::= & \code{Is()} \\
  9863. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  9864. &\MID& \LEN{\Exp}
  9865. \end{array}
  9866. }
  9867. \begin{figure}[tbp]
  9868. \centering
  9869. \fbox{
  9870. \begin{minipage}{0.96\textwidth}
  9871. {\if\edition\racketEd
  9872. \[
  9873. \begin{array}{l}
  9874. \gray{\LintGrammarRacket{}} \\ \hline
  9875. \gray{\LvarGrammarRacket{}} \\ \hline
  9876. \gray{\LifGrammarRacket{}} \\ \hline
  9877. \gray{\LwhileGrammarRacket} \\ \hline
  9878. \LtupGrammarRacket \\
  9879. \begin{array}{lcl}
  9880. \LangVecM{} &::=& \Exp
  9881. \end{array}
  9882. \end{array}
  9883. \]
  9884. \fi}
  9885. {\if\edition\pythonEd
  9886. \[
  9887. \begin{array}{l}
  9888. \gray{\LintGrammarPython{}} \\ \hline
  9889. \gray{\LvarGrammarPython{}} \\ \hline
  9890. \gray{\LifGrammarPython{}} \\ \hline
  9891. \gray{\LwhileGrammarPython} \\ \hline
  9892. \LtupGrammarPython \\
  9893. \begin{array}{rcl}
  9894. \LangVecM{} &::=& \Stmt^{*}
  9895. \end{array}
  9896. \end{array}
  9897. \]
  9898. \fi}
  9899. \end{minipage}
  9900. }
  9901. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  9902. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  9903. \label{fig:Lvec-concrete-syntax}
  9904. \end{figure}
  9905. \begin{figure}[tp]
  9906. \centering
  9907. \fbox{
  9908. \begin{minipage}{0.96\textwidth}
  9909. {\if\edition\racketEd
  9910. \[
  9911. \begin{array}{l}
  9912. \gray{\LintOpAST} \\ \hline
  9913. \gray{\LvarAST{}} \\ \hline
  9914. \gray{\LifAST{}} \\ \hline
  9915. \gray{\LwhileAST{}} \\ \hline
  9916. \LtupASTRacket{} \\
  9917. \begin{array}{lcl}
  9918. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  9919. \end{array}
  9920. \end{array}
  9921. \]
  9922. \fi}
  9923. {\if\edition\pythonEd
  9924. \[
  9925. \begin{array}{l}
  9926. \gray{\LintASTPython} \\ \hline
  9927. \gray{\LvarASTPython} \\ \hline
  9928. \gray{\LifASTPython} \\ \hline
  9929. \gray{\LwhileASTPython} \\ \hline
  9930. \LtupASTPython \\
  9931. \begin{array}{lcl}
  9932. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9933. \end{array}
  9934. \end{array}
  9935. \]
  9936. \fi}
  9937. \end{minipage}
  9938. }
  9939. \caption{The abstract syntax of \LangVec{}.}
  9940. \label{fig:Lvec-syntax}
  9941. \end{figure}
  9942. Tuples raises several interesting new issues. First, variable binding
  9943. performs a shallow-copy when dealing with tuples, which means that
  9944. different variables can refer to the same tuple, that is, two
  9945. variables can be \emph{aliases}\index{subject}{alias} for the same
  9946. entity. Consider the following example in which both \code{t1} and
  9947. \code{t2} refer to the same tuple value but \code{t3} refers to a
  9948. different tuple value but with equal elements. The result of the
  9949. program is \code{42}.
  9950. \begin{center}
  9951. \begin{minipage}{0.96\textwidth}
  9952. {\if\edition\racketEd
  9953. \begin{lstlisting}
  9954. (let ([t1 (vector 3 7)])
  9955. (let ([t2 t1])
  9956. (let ([t3 (vector 3 7)])
  9957. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  9958. 42
  9959. 0))))
  9960. \end{lstlisting}
  9961. \fi}
  9962. {\if\edition\pythonEd
  9963. \begin{lstlisting}
  9964. t1 = 3, 7
  9965. t2 = t1
  9966. t3 = 3, 7
  9967. print( 42 if (t1 is t2) and not (t1 is t3) else 0)
  9968. \end{lstlisting}
  9969. \fi}
  9970. \end{minipage}
  9971. \end{center}
  9972. {\if\edition\racketEd
  9973. Whether two variables are aliased or not affects what happens
  9974. when the underlying tuple is mutated\index{subject}{mutation}.
  9975. Consider the following example in which \code{t1} and \code{t2}
  9976. again refer to the same tuple value.
  9977. \begin{center}
  9978. \begin{minipage}{0.96\textwidth}
  9979. \begin{lstlisting}
  9980. (let ([t1 (vector 3 7)])
  9981. (let ([t2 t1])
  9982. (let ([_ (vector-set! t2 0 42)])
  9983. (vector-ref t1 0))))
  9984. \end{lstlisting}
  9985. \end{minipage}
  9986. \end{center}
  9987. The mutation through \code{t2} is visible when referencing the tuple
  9988. from \code{t1}, so the result of this program is \code{42}.
  9989. \fi}
  9990. The next issue concerns the lifetime of tuples. When does their
  9991. lifetime end? Notice that \LangVec{} does not include an operation
  9992. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  9993. to any notion of static scoping.
  9994. %
  9995. {\if\edition\racketEd
  9996. %
  9997. For example, the following program returns \code{42} even though the
  9998. variable \code{w} goes out of scope prior to the \code{vector-ref}
  9999. that reads from the vector it was bound to.
  10000. \begin{center}
  10001. \begin{minipage}{0.96\textwidth}
  10002. \begin{lstlisting}
  10003. (let ([v (vector (vector 44))])
  10004. (let ([x (let ([w (vector 42)])
  10005. (let ([_ (vector-set! v 0 w)])
  10006. 0))])
  10007. (+ x (vector-ref (vector-ref v 0) 0))))
  10008. \end{lstlisting}
  10009. \end{minipage}
  10010. \end{center}
  10011. \fi}
  10012. %
  10013. {\if\edition\pythonEd
  10014. %
  10015. For example, the following program returns \code{42} even though the
  10016. variable \code{x} goes out of scope when the function returns, prior
  10017. to reading the tuple element at index zero. (We study the compilation
  10018. of functions in Chapter~\ref{ch:Rfun}.)
  10019. %
  10020. \begin{center}
  10021. \begin{minipage}{0.96\textwidth}
  10022. \begin{lstlisting}
  10023. def f():
  10024. x = 42, 43
  10025. return x
  10026. t = f()
  10027. print( t[0] )
  10028. \end{lstlisting}
  10029. \end{minipage}
  10030. \end{center}
  10031. \fi}
  10032. %
  10033. From the perspective of programmer-observable behavior, tuples live
  10034. forever. Of course, if they really lived forever then many programs
  10035. would run out of memory. The language's runtime system must therefore
  10036. perform automatic garbage collection.
  10037. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10038. \LangVec{} language.
  10039. %
  10040. \racket{We define the \code{vector}, \code{vector-ref},
  10041. \code{vector-set!}, and \code{vector-length} operations for
  10042. \LangVec{} in terms of the corresponding operations in Racket. One
  10043. subtle point is that the \code{vector-set!} operation returns the
  10044. \code{\#<void>} value.}
  10045. %
  10046. \python{We define tuple creation, element access, and the \code{len}
  10047. operator for \LangVec{} in terms of the corresponding operations in
  10048. Python.}
  10049. \begin{figure}[tbp]
  10050. {\if\edition\racketEd
  10051. \begin{lstlisting}
  10052. (define interp-Lvec_class
  10053. (class interp-Lif_class
  10054. (super-new)
  10055. (define/override (interp-op op)
  10056. (match op
  10057. ['eq? (lambda (v1 v2)
  10058. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10059. (and (boolean? v1) (boolean? v2))
  10060. (and (vector? v1) (vector? v2))
  10061. (and (void? v1) (void? v2)))
  10062. (eq? v1 v2)]))]
  10063. ['vector vector]
  10064. ['vector-length vector-length]
  10065. ['vector-ref vector-ref]
  10066. ['vector-set! vector-set!]
  10067. [else (super interp-op op)]
  10068. ))
  10069. (define/override ((interp-exp env) e)
  10070. (define recur (interp-exp env))
  10071. (match e
  10072. [(HasType e t) (recur e)]
  10073. [(Void) (void)]
  10074. [else ((super interp-exp env) e)]
  10075. ))
  10076. ))
  10077. (define (interp-Lvec p)
  10078. (send (new interp-Lvec_class) interp-program p))
  10079. \end{lstlisting}
  10080. \fi}
  10081. %
  10082. {\if\edition\pythonEd
  10083. \begin{lstlisting}
  10084. class InterpLtup(InterpLwhile):
  10085. def interp_cmp(self, cmp):
  10086. match cmp:
  10087. case Is():
  10088. return lambda x, y: x is y
  10089. case _:
  10090. return super().interp_cmp(cmp)
  10091. def interp_exp(self, e, env):
  10092. match e:
  10093. case Tuple(es, Load()):
  10094. return tuple([self.interp_exp(e, env) for e in es])
  10095. case Subscript(tup, index, Load()):
  10096. t = self.interp_exp(tup, env)
  10097. n = self.interp_exp(index, env)
  10098. return t[n]
  10099. case _:
  10100. return super().interp_exp(e, env)
  10101. \end{lstlisting}
  10102. \fi}
  10103. \caption{Interpreter for the \LangVec{} language.}
  10104. \label{fig:interp-Lvec}
  10105. \end{figure}
  10106. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10107. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10108. we need to know which elements of the tuple are pointers (i.e. are
  10109. also tuple) for garbage collection purposes. We can obtain this
  10110. information during type checking. The type checker in
  10111. Figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10112. expression, it also
  10113. %
  10114. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10115. where $T$ is the vector's type.
  10116. To create the s-expression for the \code{Vector} type in
  10117. Figure~\ref{fig:type-check-Lvec}, we use the
  10118. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10119. operator} \code{,@} to insert the list \code{t*} without its usual
  10120. start and end parentheses. \index{subject}{unquote-slicing}}
  10121. %
  10122. \python{records the type of each tuple expression in a new field
  10123. named \code{has\_type}.}
  10124. \begin{figure}[tp]
  10125. {\if\edition\racketEd
  10126. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10127. (define type-check-Lvec_class
  10128. (class type-check-Lif_class
  10129. (super-new)
  10130. (inherit check-type-equal?)
  10131. (define/override (type-check-exp env)
  10132. (lambda (e)
  10133. (define recur (type-check-exp env))
  10134. (match e
  10135. [(Void) (values (Void) 'Void)]
  10136. [(Prim 'vector es)
  10137. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10138. (define t `(Vector ,@t*))
  10139. (values (HasType (Prim 'vector e*) t) t)]
  10140. [(Prim 'vector-ref (list e1 (Int i)))
  10141. (define-values (e1^ t) (recur e1))
  10142. (match t
  10143. [`(Vector ,ts ...)
  10144. (unless (and (0 . <= . i) (i . < . (length ts)))
  10145. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10146. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10147. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10148. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10149. (define-values (e-vec t-vec) (recur e1))
  10150. (define-values (e-arg^ t-arg) (recur arg))
  10151. (match t-vec
  10152. [`(Vector ,ts ...)
  10153. (unless (and (0 . <= . i) (i . < . (length ts)))
  10154. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10155. (check-type-equal? (list-ref ts i) t-arg e)
  10156. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10157. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10158. [(Prim 'vector-length (list e))
  10159. (define-values (e^ t) (recur e))
  10160. (match t
  10161. [`(Vector ,ts ...)
  10162. (values (Prim 'vector-length (list e^)) 'Integer)]
  10163. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10164. [(Prim 'eq? (list arg1 arg2))
  10165. (define-values (e1 t1) (recur arg1))
  10166. (define-values (e2 t2) (recur arg2))
  10167. (match* (t1 t2)
  10168. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10169. [(other wise) (check-type-equal? t1 t2 e)])
  10170. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10171. [(HasType (Prim 'vector es) t)
  10172. ((type-check-exp env) (Prim 'vector es))]
  10173. [(HasType e1 t)
  10174. (define-values (e1^ t^) (recur e1))
  10175. (check-type-equal? t t^ e)
  10176. (values (HasType e1^ t) t)]
  10177. [else ((super type-check-exp env) e)]
  10178. )))
  10179. ))
  10180. (define (type-check-Lvec p)
  10181. (send (new type-check-Lvec_class) type-check-program p))
  10182. \end{lstlisting}
  10183. \fi}
  10184. {\if\edition\pythonEd
  10185. \begin{lstlisting}
  10186. class TypeCheckLtup(TypeCheckLwhile):
  10187. def type_check_exp(self, e, env):
  10188. match e:
  10189. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10190. l = self.type_check_exp(left, env)
  10191. r = self.type_check_exp(right, env)
  10192. check_type_equal(l, r, e)
  10193. return bool
  10194. case Tuple(es, Load()):
  10195. ts = [self.type_check_exp(e, env) for e in es]
  10196. e.has_type = tuple(ts)
  10197. return e.has_type
  10198. case Subscript(tup, Constant(index), Load()):
  10199. tup_ty = self.type_check_exp(tup, env)
  10200. index_ty = self.type_check_exp(Constant(index), env)
  10201. check_type_equal(index_ty, int, index)
  10202. match tup_ty:
  10203. case tuple(ts):
  10204. return ts[index]
  10205. case _:
  10206. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10207. case _:
  10208. return super().type_check_exp(e, env)
  10209. \end{lstlisting}
  10210. \fi}
  10211. \caption{Type checker for the \LangVec{} language.}
  10212. \label{fig:type-check-Lvec}
  10213. \end{figure}
  10214. \section{Garbage Collection}
  10215. \label{sec:GC}
  10216. Here we study a relatively simple algorithm for garbage collection
  10217. that is the basis of state-of-the-art garbage
  10218. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10219. particular, we describe a two-space copying
  10220. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10221. perform the
  10222. copy~\citep{Cheney:1970aa}.
  10223. \index{subject}{copying collector}
  10224. \index{subject}{two-space copying collector}
  10225. Figure~\ref{fig:copying-collector} gives a
  10226. coarse-grained depiction of what happens in a two-space collector,
  10227. showing two time steps, prior to garbage collection (on the top) and
  10228. after garbage collection (on the bottom). In a two-space collector,
  10229. the heap is divided into two parts named the FromSpace and the
  10230. ToSpace. Initially, all allocations go to the FromSpace until there is
  10231. not enough room for the next allocation request. At that point, the
  10232. garbage collector goes to work to make more room.
  10233. \index{subject}{ToSpace}
  10234. \index{subject}{FromSpace}
  10235. The garbage collector must be careful not to reclaim tuples that will
  10236. be used by the program in the future. Of course, it is impossible in
  10237. general to predict what a program will do, but we can over approximate
  10238. the will-be-used tuples by preserving all tuples that could be
  10239. accessed by \emph{any} program given the current computer state. A
  10240. program could access any tuple whose address is in a register or on
  10241. the procedure call stack. These addresses are called the \emph{root
  10242. set}\index{subject}{root set}. In addition, a program could access any tuple that is
  10243. transitively reachable from the root set. Thus, it is safe for the
  10244. garbage collector to reclaim the tuples that are not reachable in this
  10245. way.
  10246. So the goal of the garbage collector is twofold:
  10247. \begin{enumerate}
  10248. \item preserve all tuple that are reachable from the root set via a
  10249. path of pointers, that is, the \emph{live} tuples, and
  10250. \item reclaim the memory of everything else, that is, the
  10251. \emph{garbage}.
  10252. \end{enumerate}
  10253. A copying collector accomplishes this by copying all of the live
  10254. objects from the FromSpace into the ToSpace and then performs a sleight
  10255. of hand, treating the ToSpace as the new FromSpace and the old
  10256. FromSpace as the new ToSpace. In the example of
  10257. Figure~\ref{fig:copying-collector}, there are three pointers in the
  10258. root set, one in a register and two on the stack. All of the live
  10259. objects have been copied to the ToSpace (the right-hand side of
  10260. Figure~\ref{fig:copying-collector}) in a way that preserves the
  10261. pointer relationships. For example, the pointer in the register still
  10262. points to a 2-tuple whose first element is a 3-tuple and whose second
  10263. element is a 2-tuple. There are four tuples that are not reachable
  10264. from the root set and therefore do not get copied into the ToSpace.
  10265. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  10266. created by a well-typed program in \LangVec{} because it contains a
  10267. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  10268. We design the garbage collector to deal with cycles to begin with so
  10269. we will not need to revisit this issue.
  10270. \begin{figure}[tbp]
  10271. \centering
  10272. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  10273. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  10274. \caption{A copying collector in action.}
  10275. \label{fig:copying-collector}
  10276. \end{figure}
  10277. There are many alternatives to copying collectors (and their bigger
  10278. siblings, the generational collectors) when its comes to garbage
  10279. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  10280. reference counting~\citep{Collins:1960aa}. The strengths of copying
  10281. collectors are that allocation is fast (just a comparison and pointer
  10282. increment), there is no fragmentation, cyclic garbage is collected,
  10283. and the time complexity of collection only depends on the amount of
  10284. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  10285. main disadvantages of a two-space copying collector is that it uses a
  10286. lot of space and takes a long time to perform the copy, though these
  10287. problems are ameliorated in generational collectors. Racket and
  10288. Scheme programs tend to allocate many small objects and generate a lot
  10289. of garbage, so copying and generational collectors are a good fit.
  10290. Garbage collection is an active research topic, especially concurrent
  10291. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  10292. developing new techniques and revisiting old
  10293. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  10294. meet every year at the International Symposium on Memory Management to
  10295. present these findings.
  10296. \subsection{Graph Copying via Cheney's Algorithm}
  10297. \label{sec:cheney}
  10298. \index{subject}{Cheney's algorithm}
  10299. Let us take a closer look at the copying of the live objects. The
  10300. allocated objects and pointers can be viewed as a graph and we need to
  10301. copy the part of the graph that is reachable from the root set. To
  10302. make sure we copy all of the reachable vertices in the graph, we need
  10303. an exhaustive graph traversal algorithm, such as depth-first search or
  10304. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10305. such algorithms take into account the possibility of cycles by marking
  10306. which vertices have already been visited, so as to ensure termination
  10307. of the algorithm. These search algorithms also use a data structure
  10308. such as a stack or queue as a to-do list to keep track of the vertices
  10309. that need to be visited. We use breadth-first search and a trick
  10310. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10311. and copying tuples into the ToSpace.
  10312. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10313. copy progresses. The queue is represented by a chunk of contiguous
  10314. memory at the beginning of the ToSpace, using two pointers to track
  10315. the front and the back of the queue. The algorithm starts by copying
  10316. all tuples that are immediately reachable from the root set into the
  10317. ToSpace to form the initial queue. When we copy a tuple, we mark the
  10318. old tuple to indicate that it has been visited. We discuss how this
  10319. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  10320. pointers inside the copied tuples in the queue still point back to the
  10321. FromSpace. Once the initial queue has been created, the algorithm
  10322. enters a loop in which it repeatedly processes the tuple at the front
  10323. of the queue and pops it off the queue. To process a tuple, the
  10324. algorithm copies all the tuple that are directly reachable from it to
  10325. the ToSpace, placing them at the back of the queue. The algorithm then
  10326. updates the pointers in the popped tuple so they point to the newly
  10327. copied tuples.
  10328. \begin{figure}[tbp]
  10329. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  10330. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10331. \label{fig:cheney}
  10332. \end{figure}
  10333. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  10334. tuple whose second element is $42$ to the back of the queue. The other
  10335. pointer goes to a tuple that has already been copied, so we do not
  10336. need to copy it again, but we do need to update the pointer to the new
  10337. location. This can be accomplished by storing a \emph{forwarding
  10338. pointer} to the new location in the old tuple, back when we initially
  10339. copied the tuple into the ToSpace. This completes one step of the
  10340. algorithm. The algorithm continues in this way until the front of the
  10341. queue is empty, that is, until the front catches up with the back.
  10342. \subsection{Data Representation}
  10343. \label{sec:data-rep-gc}
  10344. The garbage collector places some requirements on the data
  10345. representations used by our compiler. First, the garbage collector
  10346. needs to distinguish between pointers and other kinds of data. There
  10347. are several ways to accomplish this.
  10348. \begin{enumerate}
  10349. \item Attached a tag to each object that identifies what type of
  10350. object it is~\citep{McCarthy:1960dz}.
  10351. \item Store different types of objects in different
  10352. regions~\citep{Steele:1977ab}.
  10353. \item Use type information from the program to either generate
  10354. type-specific code for collecting or to generate tables that can
  10355. guide the
  10356. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10357. \end{enumerate}
  10358. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10359. need to tag objects anyways, so option 1 is a natural choice for those
  10360. languages. However, \LangVec{} is a statically typed language, so it
  10361. would be unfortunate to require tags on every object, especially small
  10362. and pervasive objects like integers and Booleans. Option 3 is the
  10363. best-performing choice for statically typed languages, but comes with
  10364. a relatively high implementation complexity. To keep this chapter
  10365. within a 2-week time budget, we recommend a combination of options 1
  10366. and 2, using separate strategies for the stack and the heap.
  10367. Regarding the stack, we recommend using a separate stack for pointers,
  10368. which we call a \emph{root stack}\index{subject}{root stack}
  10369. (a.k.a. ``shadow
  10370. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10371. is, when a local variable needs to be spilled and is of type
  10372. \racket{\code{Vector}}\python{\code{TupleType}}, then we put it on the
  10373. root stack instead of the normal procedure call stack. Furthermore, we
  10374. always spill tuple-typed variables if they are live during a call to
  10375. the collector, thereby ensuring that no pointers are in registers
  10376. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  10377. example from Figure~\ref{fig:copying-collector} and contrasts it with
  10378. the data layout using a root stack. The root stack contains the two
  10379. pointers from the regular stack and also the pointer in the second
  10380. register.
  10381. \begin{figure}[tbp]
  10382. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  10383. \caption{Maintaining a root stack to facilitate garbage collection.}
  10384. \label{fig:shadow-stack}
  10385. \end{figure}
  10386. The problem of distinguishing between pointers and other kinds of data
  10387. also arises inside of each tuple on the heap. We solve this problem by
  10388. attaching a tag, an extra 64-bits, to each
  10389. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10390. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  10391. that we have drawn the bits in a big-endian way, from right-to-left,
  10392. with bit location 0 (the least significant bit) on the far right,
  10393. which corresponds to the direction of the x86 shifting instructions
  10394. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10395. is dedicated to specifying which elements of the tuple are pointers,
  10396. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10397. indicates there is a pointer and a 0 bit indicates some other kind of
  10398. data. The pointer mask starts at bit location 7. We have limited
  10399. tuples to a maximum size of 50 elements, so we just need 50 bits for
  10400. the pointer mask. The tag also contains two other pieces of
  10401. information. The length of the tuple (number of elements) is stored in
  10402. bits location 1 through 6. Finally, the bit at location 0 indicates
  10403. whether the tuple has yet to be copied to the ToSpace. If the bit has
  10404. value 1, then this tuple has not yet been copied. If the bit has
  10405. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  10406. of a pointer are always zero anyways because our tuples are 8-byte
  10407. aligned.)
  10408. \begin{figure}[tbp]
  10409. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10410. \caption{Representation of tuples in the heap.}
  10411. \label{fig:tuple-rep}
  10412. \end{figure}
  10413. \subsection{Implementation of the Garbage Collector}
  10414. \label{sec:organize-gz}
  10415. \index{subject}{prelude}
  10416. An implementation of the copying collector is provided in the
  10417. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10418. interface to the garbage collector that is used by the compiler. The
  10419. \code{initialize} function creates the FromSpace, ToSpace, and root
  10420. stack and should be called in the prelude of the \code{main}
  10421. function. The arguments of \code{initialize} are the root stack size
  10422. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10423. good choice for both. The \code{initialize} function puts the address
  10424. of the beginning of the FromSpace into the global variable
  10425. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10426. the address that is 1-past the last element of the FromSpace. (We use
  10427. half-open intervals to represent chunks of
  10428. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  10429. points to the first element of the root stack.
  10430. As long as there is room left in the FromSpace, your generated code
  10431. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10432. %
  10433. The amount of room left in FromSpace is the difference between the
  10434. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10435. function should be called when there is not enough room left in the
  10436. FromSpace for the next allocation. The \code{collect} function takes
  10437. a pointer to the current top of the root stack (one past the last item
  10438. that was pushed) and the number of bytes that need to be
  10439. allocated. The \code{collect} function performs the copying collection
  10440. and leaves the heap in a state such that the next allocation will
  10441. succeed.
  10442. \begin{figure}[tbp]
  10443. \begin{lstlisting}
  10444. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10445. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10446. int64_t* free_ptr;
  10447. int64_t* fromspace_begin;
  10448. int64_t* fromspace_end;
  10449. int64_t** rootstack_begin;
  10450. \end{lstlisting}
  10451. \caption{The compiler's interface to the garbage collector.}
  10452. \label{fig:gc-header}
  10453. \end{figure}
  10454. %% \begin{exercise}
  10455. %% In the file \code{runtime.c} you will find the implementation of
  10456. %% \code{initialize} and a partial implementation of \code{collect}.
  10457. %% The \code{collect} function calls another function, \code{cheney},
  10458. %% to perform the actual copy, and that function is left to the reader
  10459. %% to implement. The following is the prototype for \code{cheney}.
  10460. %% \begin{lstlisting}
  10461. %% static void cheney(int64_t** rootstack_ptr);
  10462. %% \end{lstlisting}
  10463. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10464. %% rootstack (which is an array of pointers). The \code{cheney} function
  10465. %% also communicates with \code{collect} through the global
  10466. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10467. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  10468. %% the ToSpace:
  10469. %% \begin{lstlisting}
  10470. %% static int64_t* tospace_begin;
  10471. %% static int64_t* tospace_end;
  10472. %% \end{lstlisting}
  10473. %% The job of the \code{cheney} function is to copy all the live
  10474. %% objects (reachable from the root stack) into the ToSpace, update
  10475. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10476. %% update the root stack so that it points to the objects in the
  10477. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10478. %% and ToSpace.
  10479. %% \end{exercise}
  10480. %% \section{Compiler Passes}
  10481. %% \label{sec:code-generation-gc}
  10482. The introduction of garbage collection has a non-trivial impact on our
  10483. compiler passes. We introduce a new compiler pass named
  10484. \code{expose\_allocation}. We make significant changes to
  10485. \code{select\_instructions}, \code{build\_interference},
  10486. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10487. make minor changes in several more passes. The following program will
  10488. serve as our running example. It creates two tuples, one nested
  10489. inside the other. Both tuples have length one. The program accesses
  10490. the element in the inner tuple tuple.
  10491. % tests/vectors_test_17.rkt
  10492. {\if\edition\racketEd
  10493. \begin{lstlisting}
  10494. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10495. \end{lstlisting}
  10496. \fi}
  10497. {\if\edition\pythonEd
  10498. \begin{lstlisting}
  10499. print( ((42,),)[0][0] )
  10500. \end{lstlisting}
  10501. \fi}
  10502. {\if\edition\racketEd
  10503. \section{Shrink}
  10504. \label{sec:shrink-Lvec}
  10505. Recall that the \code{shrink} pass translates the primitives operators
  10506. into a smaller set of primitives.
  10507. %
  10508. This pass comes after type checking and the type checker adds a
  10509. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10510. need to add a case for \code{HasType} to the \code{shrink} pass.
  10511. \fi}
  10512. \section{Expose Allocation}
  10513. \label{sec:expose-allocation}
  10514. The pass \code{expose\_allocation} lowers tuple creation into a
  10515. conditional call to the collector followed by allocating the
  10516. appropriate amount of memory and initializing it. We choose to place
  10517. the \code{expose\_allocation} pass before
  10518. \code{remove\_complex\_operands} because the code generated by
  10519. \code{expose\_allocation} contains complex operands.
  10520. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10521. that extends \LangVec{} with new forms that we use in the translation
  10522. of tuple creation.
  10523. %
  10524. {\if\edition\racketEd
  10525. \[
  10526. \begin{array}{lcl}
  10527. \Exp &::=& \cdots
  10528. \MID (\key{collect} \,\itm{int})
  10529. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10530. \MID (\key{global-value} \,\itm{name})
  10531. \end{array}
  10532. \]
  10533. \fi}
  10534. {\if\edition\pythonEd
  10535. \[
  10536. \begin{array}{lcl}
  10537. \Exp &::=& \cdots\\
  10538. &\MID& \key{collect}(\itm{int})
  10539. \MID \key{allocate}(\itm{int},\itm{type})
  10540. \MID \key{global\_value}(\itm{name}) \\
  10541. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp
  10542. \end{array}
  10543. \]
  10544. \fi}
  10545. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10546. make sure that there are $n$ bytes ready to be allocated. During
  10547. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10548. the \code{collect} function in \code{runtime.c}.
  10549. %
  10550. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10551. space at the front for the 64 bit tag), but the elements are not
  10552. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10553. of the tuple:
  10554. %
  10555. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10556. %
  10557. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10558. \CGLOBAL{\itm{name}} form reads the value of a global variable, such
  10559. as \code{free\_ptr}.
  10560. %
  10561. \python{The \code{begin} form is an expression that executes a
  10562. sequence of statements and then produces the value of the expression
  10563. at the end.}
  10564. The following shows the transformation of tuple creation into 1) a
  10565. sequence of temporary variables bindings for the initializing
  10566. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10567. \code{allocate}, and 4) the initialization of the tuple. The
  10568. \itm{len} placeholder refers to the length of the tuple and
  10569. \itm{bytes} is how many total bytes need to be allocated for the
  10570. tuple, which is 8 for the tag plus \itm{len} times 8.
  10571. %
  10572. \python{The \itm{type} needed for the second argument of the
  10573. \code{allocate} form can be obtained from the \code{has\_type} field
  10574. of the tuple AST node, which is stored there by running the type
  10575. checker for \LangVec{} immediately before this pass.}
  10576. %
  10577. {\if\edition\racketEd
  10578. \begin{lstlisting}
  10579. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10580. |$\Longrightarrow$|
  10581. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10582. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10583. (global-value fromspace_end))
  10584. (void)
  10585. (collect |\itm{bytes}|))])
  10586. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  10587. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  10588. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  10589. |$v$|) ... )))) ...)
  10590. \end{lstlisting}
  10591. \fi}
  10592. {\if\edition\pythonEd
  10593. \begin{lstlisting}
  10594. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  10595. |$\Longrightarrow$|
  10596. begin:
  10597. |$x_0$| = |$e_0$|
  10598. |$\vdots$|
  10599. |$x_{n-1}$| = |$e_{n-1}$|
  10600. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  10601. 0
  10602. else:
  10603. collect(|\itm{bytes}|)
  10604. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  10605. |$v$|[0] = |$x_0$|
  10606. |$\vdots$|
  10607. |$v$|[|$n-1$|] = |$x_{n-1}$|
  10608. |$v$|
  10609. \end{lstlisting}
  10610. \fi}
  10611. %
  10612. \noindent The sequencing of the initializing expressions
  10613. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  10614. they may trigger garbage collection and we cannot have an allocated
  10615. but uninitialized tuple on the heap during a collection.
  10616. Figure~\ref{fig:expose-alloc-output} shows the output of the
  10617. \code{expose\_allocation} pass on our running example.
  10618. \begin{figure}[tbp]
  10619. % tests/s2_17.rkt
  10620. {\if\edition\racketEd
  10621. \begin{lstlisting}
  10622. (vector-ref
  10623. (vector-ref
  10624. (let ([vecinit7976
  10625. (let ([vecinit7972 42])
  10626. (let ([collectret7974
  10627. (if (< (+ (global-value free_ptr) 16)
  10628. (global-value fromspace_end))
  10629. (void)
  10630. (collect 16)
  10631. )])
  10632. (let ([alloc7971 (allocate 1 (Vector Integer))])
  10633. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  10634. alloc7971))))])
  10635. (let ([collectret7978
  10636. (if (< (+ (global-value free_ptr) 16)
  10637. (global-value fromspace_end))
  10638. (void)
  10639. (collect 16)
  10640. )])
  10641. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  10642. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  10643. alloc7975))))
  10644. 0)
  10645. 0)
  10646. \end{lstlisting}
  10647. \fi}
  10648. {\if\edition\pythonEd
  10649. \begin{lstlisting}
  10650. print( |$T_1$|[0][0] )
  10651. \end{lstlisting}
  10652. where $T_1$ is
  10653. \begin{lstlisting}
  10654. begin:
  10655. tmp.1 = |$T_2$|
  10656. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10657. 0
  10658. else:
  10659. collect(16)
  10660. tmp.2 = allocate(1, TupleType(TupleType([int])))
  10661. tmp.2[0] = tmp.1
  10662. tmp.2
  10663. \end{lstlisting}
  10664. and $T_2$ is
  10665. \begin{lstlisting}
  10666. begin:
  10667. tmp.3 = 42
  10668. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10669. 0
  10670. else:
  10671. collect(16)
  10672. tmp.4 = allocate(1, TupleType([int]))
  10673. tmp.4[0] = tmp.3
  10674. tmp.4
  10675. \end{lstlisting}
  10676. \fi}
  10677. \caption{Output of the \code{expose\_allocation} pass.}
  10678. \label{fig:expose-alloc-output}
  10679. \end{figure}
  10680. \section{Remove Complex Operands}
  10681. \label{sec:remove-complex-opera-Lvec}
  10682. {\if\edition\racketEd
  10683. %
  10684. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  10685. should be treated as complex operands.
  10686. %
  10687. \fi}
  10688. %
  10689. {\if\edition\pythonEd
  10690. %
  10691. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  10692. and tuple access should be treated as complex operands. The
  10693. sub-expressions of tuple access must be atomic.
  10694. %
  10695. \fi}
  10696. %% A new case for
  10697. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  10698. %% handled carefully to prevent the \code{Prim} node from being separated
  10699. %% from its enclosing \code{HasType}.
  10700. Figure~\ref{fig:Lvec-anf-syntax}
  10701. shows the grammar for the output language \LangVecANF{} of this
  10702. pass, which is \LangVec{} in monadic normal form.
  10703. \begin{figure}[tp]
  10704. \centering
  10705. \fbox{
  10706. \begin{minipage}{0.96\textwidth}
  10707. \small
  10708. {\if\edition\racketEd
  10709. \[
  10710. \begin{array}{rcl}
  10711. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  10712. \MID \VOID{} } \\
  10713. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  10714. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  10715. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10716. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  10717. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  10718. &\MID& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  10719. \MID \GLOBALVALUE{\Var}\\
  10720. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  10721. \LangVecANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10722. \end{array}
  10723. \]
  10724. \fi}
  10725. {\if\edition\pythonEd
  10726. \[
  10727. \begin{array}{lcl}
  10728. \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  10729. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  10730. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \MID \code{Is()} \\
  10731. \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  10732. \itm{bool} &::=& \code{True} \MID \code{False} \\
  10733. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  10734. \Exp &::=& \Atm \MID \READ{} \MID \\
  10735. &\MID& \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  10736. \MID \UNIOP{\itm{unaryop}}{\Exp}\\
  10737. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp}
  10738. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  10739. &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  10740. &\MID& \GET{\Atm}{\Atm} \\
  10741. &\MID& \LEN{\Exp}\\
  10742. &\MID& \ALLOCATE{\Int}{\Type}
  10743. \MID \GLOBALVALUE{\Var}\RP\\
  10744. &\MID& \BEGIN{\Stmt^{*}}{\Exp} \\
  10745. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  10746. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  10747. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Exp} \\
  10748. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10749. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}
  10750. \MID \COLLECT{\Int} \\
  10751. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10752. \end{array}
  10753. \]
  10754. \fi}
  10755. \end{minipage}
  10756. }
  10757. \caption{\LangVecANF{} is \LangVec{} in monadic normal form.}
  10758. \label{fig:Lvec-anf-syntax}
  10759. \end{figure}
  10760. \section{Explicate Control and the \LangCVec{} language}
  10761. \label{sec:explicate-control-r3}
  10762. \begin{figure}[tp]
  10763. \fbox{
  10764. \begin{minipage}{0.96\textwidth}
  10765. \small
  10766. {\if\edition\racketEd
  10767. \[
  10768. \begin{array}{lcl}
  10769. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  10770. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  10771. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  10772. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  10773. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  10774. &\MID& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  10775. &\MID& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  10776. &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  10777. &\MID& \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP\\
  10778. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  10779. \MID \LP\key{Collect} \,\itm{int}\RP \\
  10780. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  10781. \MID \GOTO{\itm{label}} } \\
  10782. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  10783. \LangCVecM{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  10784. \end{array}
  10785. \]
  10786. \fi}
  10787. {\if\edition\pythonEd
  10788. \[
  10789. \begin{array}{lcl}
  10790. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  10791. \Exp &::= & \Atm \MID \READ{} \\
  10792. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  10793. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  10794. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm}
  10795. \MID \BOOLOP{\itm{boolop}}{\Atm}{\Atm} \\
  10796. &\MID& \GET{\Atm}{\Atm}
  10797. \MID \ALLOCATE{\Int}{\Type} \MID \GLOBALVALUE{\Var}\RP\\
  10798. &\MID& \LEN{\Atm} \\
  10799. \Stmt &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  10800. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  10801. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  10802. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS} \\
  10803. &\MID& \COLLECT{\Int} \\
  10804. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  10805. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\,\key{:}\,\Stmt^{*}, \ldots \RC}
  10806. \end{array}
  10807. \]
  10808. \fi}
  10809. \end{minipage}
  10810. }
  10811. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  10812. (Figure~\ref{fig:c1-syntax}).}
  10813. \label{fig:c2-syntax}
  10814. \end{figure}
  10815. The output of \code{explicate\_control} is a program in the
  10816. intermediate language \LangCVec{}, whose abstract syntax is defined in
  10817. Figure~\ref{fig:c2-syntax}. \racket{(The concrete syntax is defined
  10818. in Figure~\ref{fig:c2-concrete-syntax} of the Appendix.)} The new
  10819. expressions of \LangCVec{} include \key{allocate},
  10820. %
  10821. \racket{\key{vector-ref}, and \key{vector-set!},}
  10822. %
  10823. \python{accessing tuple elements,}
  10824. %
  10825. and \key{global\_value}.
  10826. %
  10827. \python{\LangCVec{} also includes the \code{collect} statement and
  10828. assignment to a tuple element.}
  10829. %
  10830. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  10831. %
  10832. The \code{explicate\_control} pass can treat these new forms much like
  10833. the other forms that we've already encoutered.
  10834. \section{Select Instructions and the \LangXGlobal{} Language}
  10835. \label{sec:select-instructions-gc}
  10836. \index{subject}{instruction selection}
  10837. %% void (rep as zero)
  10838. %% allocate
  10839. %% collect (callq collect)
  10840. %% vector-ref
  10841. %% vector-set!
  10842. %% global (postpone)
  10843. In this pass we generate x86 code for most of the new operations that
  10844. were needed to compile tuples, including \code{Allocate},
  10845. \code{Collect}, and accessing tuple elements.
  10846. %
  10847. We compile \code{GlobalValue} to \code{Global} because the later has a
  10848. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  10849. \ref{fig:x86-2}). \index{subject}{x86}
  10850. The tuple read and write forms translate into \code{movq}
  10851. instructions. (The plus one in the offset is to get past the tag at
  10852. the beginning of the tuple representation.)
  10853. %
  10854. \begin{center}
  10855. \begin{minipage}{\textwidth}
  10856. {\if\edition\racketEd
  10857. \begin{lstlisting}
  10858. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  10859. |$\Longrightarrow$|
  10860. movq |$\itm{tup}'$|, %r11
  10861. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  10862. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  10863. |$\Longrightarrow$|
  10864. movq |$\itm{tup}'$|, %r11
  10865. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  10866. movq $0, |$\itm{lhs'}$|
  10867. \end{lstlisting}
  10868. \fi}
  10869. {\if\edition\pythonEd
  10870. \begin{lstlisting}
  10871. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  10872. |$\Longrightarrow$|
  10873. movq |$\itm{tup}'$|, %r11
  10874. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  10875. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  10876. |$\Longrightarrow$|
  10877. movq |$\itm{tup}'$|, %r11
  10878. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  10879. movq $0, |$\itm{lhs'}$|
  10880. \end{lstlisting}
  10881. \fi}
  10882. \end{minipage}
  10883. \end{center}
  10884. The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$ are obtained by
  10885. translating $\itm{tup}$ and $\itm{rhs}$ to x86. The move of $\itm{tup}'$ to
  10886. register \code{r11} ensures that offset expression
  10887. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  10888. removing \code{r11} from consideration by the register allocating.
  10889. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  10890. \code{rax}. Then the generated code for tuple assignment would be
  10891. \begin{lstlisting}
  10892. movq |$\itm{tup}'$|, %rax
  10893. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  10894. movq $0, |$\itm{lhs}'$|
  10895. \end{lstlisting}
  10896. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  10897. \code{patch\_instructions} would insert a move through \code{rax}
  10898. as follows.
  10899. \begin{lstlisting}
  10900. movq |$\itm{tup}'$|, %rax
  10901. movq |$\itm{rhs}'$|, %rax
  10902. movq %rax, |$8(n+1)$|(%rax)
  10903. movq $0, |$\itm{lhs}'$|
  10904. \end{lstlisting}
  10905. But the above sequence of instructions does not work because we're
  10906. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  10907. $\itm{rhs}'$) at the same time!
  10908. We compile the \code{allocate} form to operations on the
  10909. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  10910. is the next free address in the FromSpace, so we copy it into
  10911. \code{r11} and then move it forward by enough space for the tuple
  10912. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  10913. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  10914. initialize the \itm{tag} and finally copy the address in \code{r11} to
  10915. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  10916. tag is organized.
  10917. %
  10918. \racket{We recommend using the Racket operations
  10919. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  10920. during compilation.}
  10921. %
  10922. The type annotation in the \code{allocate} form is used to determine
  10923. the pointer mask region of the tag.
  10924. %
  10925. {\if\edition\racketEd
  10926. \begin{lstlisting}
  10927. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  10928. |$\Longrightarrow$|
  10929. movq free_ptr(%rip), %r11
  10930. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  10931. movq $|$\itm{tag}$|, 0(%r11)
  10932. movq %r11, |$\itm{lhs}'$|
  10933. \end{lstlisting}
  10934. \fi}
  10935. {\if\edition\pythonEd
  10936. \begin{lstlisting}
  10937. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  10938. |$\Longrightarrow$|
  10939. movq free_ptr(%rip), %r11
  10940. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  10941. movq $|$\itm{tag}$|, 0(%r11)
  10942. movq %r11, |$\itm{lhs}'$|
  10943. \end{lstlisting}
  10944. \fi}
  10945. The \code{collect} form is compiled to a call to the \code{collect}
  10946. function in the runtime. The arguments to \code{collect} are 1) the
  10947. top of the root stack and 2) the number of bytes that need to be
  10948. allocated. We use another dedicated register, \code{r15}, to
  10949. store the pointer to the top of the root stack. So \code{r15} is not
  10950. available for use by the register allocator.
  10951. {\if\edition\racketEd
  10952. \begin{lstlisting}
  10953. (collect |$\itm{bytes}$|)
  10954. |$\Longrightarrow$|
  10955. movq %r15, %rdi
  10956. movq $|\itm{bytes}|, %rsi
  10957. callq collect
  10958. \end{lstlisting}
  10959. \fi}
  10960. {\if\edition\pythonEd
  10961. \begin{lstlisting}
  10962. collect(|$\itm{bytes}$|)
  10963. |$\Longrightarrow$|
  10964. movq %r15, %rdi
  10965. movq $|\itm{bytes}|, %rsi
  10966. callq collect
  10967. \end{lstlisting}
  10968. \fi}
  10969. \begin{figure}[tp]
  10970. \fbox{
  10971. \begin{minipage}{0.96\textwidth}
  10972. \[
  10973. \begin{array}{lcl}
  10974. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  10975. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  10976. & & \gray{ \key{main:} \; \Instr\ldots }
  10977. \end{array}
  10978. \]
  10979. \end{minipage}
  10980. }
  10981. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  10982. \label{fig:x86-2-concrete}
  10983. \end{figure}
  10984. \begin{figure}[tp]
  10985. \fbox{
  10986. \begin{minipage}{0.96\textwidth}
  10987. \small
  10988. \[
  10989. \begin{array}{lcl}
  10990. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  10991. \MID \BYTEREG{\Reg}} \\
  10992. &\MID& \GLOBAL{\Var} \\
  10993. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  10994. \end{array}
  10995. \]
  10996. \end{minipage}
  10997. }
  10998. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  10999. \label{fig:x86-2}
  11000. \end{figure}
  11001. The concrete and abstract syntax of the \LangXGlobal{} language is
  11002. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  11003. differs from \LangXIf{} just in the addition of global variables.
  11004. %
  11005. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11006. \code{select\_instructions} pass on the running example.
  11007. \begin{figure}[tbp]
  11008. \centering
  11009. % tests/s2_17.rkt
  11010. \begin{minipage}[t]{0.5\textwidth}
  11011. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11012. block35:
  11013. movq free_ptr(%rip), alloc9024
  11014. addq $16, free_ptr(%rip)
  11015. movq alloc9024, %r11
  11016. movq $131, 0(%r11)
  11017. movq alloc9024, %r11
  11018. movq vecinit9025, 8(%r11)
  11019. movq $0, initret9026
  11020. movq alloc9024, %r11
  11021. movq 8(%r11), tmp9034
  11022. movq tmp9034, %r11
  11023. movq 8(%r11), %rax
  11024. jmp conclusion
  11025. block36:
  11026. movq $0, collectret9027
  11027. jmp block35
  11028. block38:
  11029. movq free_ptr(%rip), alloc9020
  11030. addq $16, free_ptr(%rip)
  11031. movq alloc9020, %r11
  11032. movq $3, 0(%r11)
  11033. movq alloc9020, %r11
  11034. movq vecinit9021, 8(%r11)
  11035. movq $0, initret9022
  11036. movq alloc9020, vecinit9025
  11037. movq free_ptr(%rip), tmp9031
  11038. movq tmp9031, tmp9032
  11039. addq $16, tmp9032
  11040. movq fromspace_end(%rip), tmp9033
  11041. cmpq tmp9033, tmp9032
  11042. jl block36
  11043. jmp block37
  11044. block37:
  11045. movq %r15, %rdi
  11046. movq $16, %rsi
  11047. callq 'collect
  11048. jmp block35
  11049. block39:
  11050. movq $0, collectret9023
  11051. jmp block38
  11052. \end{lstlisting}
  11053. \end{minipage}
  11054. \begin{minipage}[t]{0.45\textwidth}
  11055. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11056. start:
  11057. movq $42, vecinit9021
  11058. movq free_ptr(%rip), tmp9028
  11059. movq tmp9028, tmp9029
  11060. addq $16, tmp9029
  11061. movq fromspace_end(%rip), tmp9030
  11062. cmpq tmp9030, tmp9029
  11063. jl block39
  11064. jmp block40
  11065. block40:
  11066. movq %r15, %rdi
  11067. movq $16, %rsi
  11068. callq 'collect
  11069. jmp block38
  11070. \end{lstlisting}
  11071. \end{minipage}
  11072. \caption{Output of the \code{select\_instructions} pass.}
  11073. \label{fig:select-instr-output-gc}
  11074. \end{figure}
  11075. \clearpage
  11076. \section{Register Allocation}
  11077. \label{sec:reg-alloc-gc}
  11078. \index{subject}{register allocation}
  11079. As discussed earlier in this chapter, the garbage collector needs to
  11080. access all the pointers in the root set, that is, all variables that
  11081. are tuples. It will be the responsibility of the register allocator
  11082. to make sure that:
  11083. \begin{enumerate}
  11084. \item the root stack is used for spilling tuple-typed variables, and
  11085. \item if a tuple-typed variable is live during a call to the
  11086. collector, it must be spilled to ensure it is visible to the
  11087. collector.
  11088. \end{enumerate}
  11089. The later responsibility can be handled during construction of the
  11090. interference graph, by adding interference edges between the call-live
  11091. tuple-typed variables and all the callee-saved registers. (They
  11092. already interfere with the caller-saved registers.)
  11093. %
  11094. \racket{The type information for variables is in the \code{Program}
  11095. form, so we recommend adding another parameter to the
  11096. \code{build\_interference} function to communicate this alist.}
  11097. %
  11098. \python{The type information for variables is generated by the type
  11099. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11100. the \code{CProgram} AST mode. You'll need to propagate that
  11101. information so that it is available in this pass.}
  11102. The spilling of tuple-typed variables to the root stack can be handled
  11103. after graph coloring, when choosing how to assign the colors
  11104. (integers) to registers and stack locations. The
  11105. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11106. changes to also record the number of spills to the root stack.
  11107. % build-interference
  11108. %
  11109. % callq
  11110. % extra parameter for var->type assoc. list
  11111. % update 'program' and 'if'
  11112. % allocate-registers
  11113. % allocate spilled vectors to the rootstack
  11114. % don't change color-graph
  11115. \section{Prelude and Conclusion}
  11116. \label{sec:print-x86-gc}
  11117. \label{sec:prelude-conclusion-x86-gc}
  11118. \index{subject}{prelude}\index{subject}{conclusion}
  11119. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11120. \code{prelude\_and\_conclusion} pass on the running example. In the
  11121. prelude and conclusion of the \code{main} function, we treat the root
  11122. stack very much like the regular stack in that we move the root stack
  11123. pointer (\code{r15}) to make room for the spills to the root stack,
  11124. except that the root stack grows up instead of down. For the running
  11125. example, there was just one spill so we increment \code{r15} by 8
  11126. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  11127. One issue that deserves special care is that there may be a call to
  11128. \code{collect} prior to the initializing assignments for all the
  11129. variables in the root stack. We do not want the garbage collector to
  11130. accidentally think that some uninitialized variable is a pointer that
  11131. needs to be followed. Thus, we zero-out all locations on the root
  11132. stack in the prelude of \code{main}. In
  11133. Figure~\ref{fig:print-x86-output-gc}, the instruction
  11134. %
  11135. \lstinline{movq $0, (%r15)}
  11136. %
  11137. accomplishes this task. The garbage collector tests each root to see
  11138. if it is null prior to dereferencing it.
  11139. \begin{figure}[htbp]
  11140. % TODO: Python Version -Jeremy
  11141. \begin{minipage}[t]{0.5\textwidth}
  11142. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11143. block35:
  11144. movq free_ptr(%rip), %rcx
  11145. addq $16, free_ptr(%rip)
  11146. movq %rcx, %r11
  11147. movq $131, 0(%r11)
  11148. movq %rcx, %r11
  11149. movq -8(%r15), %rax
  11150. movq %rax, 8(%r11)
  11151. movq $0, %rdx
  11152. movq %rcx, %r11
  11153. movq 8(%r11), %rcx
  11154. movq %rcx, %r11
  11155. movq 8(%r11), %rax
  11156. jmp conclusion
  11157. block36:
  11158. movq $0, %rcx
  11159. jmp block35
  11160. block38:
  11161. movq free_ptr(%rip), %rcx
  11162. addq $16, free_ptr(%rip)
  11163. movq %rcx, %r11
  11164. movq $3, 0(%r11)
  11165. movq %rcx, %r11
  11166. movq %rbx, 8(%r11)
  11167. movq $0, %rdx
  11168. movq %rcx, -8(%r15)
  11169. movq free_ptr(%rip), %rcx
  11170. addq $16, %rcx
  11171. movq fromspace_end(%rip), %rdx
  11172. cmpq %rdx, %rcx
  11173. jl block36
  11174. movq %r15, %rdi
  11175. movq $16, %rsi
  11176. callq collect
  11177. jmp block35
  11178. block39:
  11179. movq $0, %rcx
  11180. jmp block38
  11181. \end{lstlisting}
  11182. \end{minipage}
  11183. \begin{minipage}[t]{0.45\textwidth}
  11184. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11185. start:
  11186. movq $42, %rbx
  11187. movq free_ptr(%rip), %rdx
  11188. addq $16, %rdx
  11189. movq fromspace_end(%rip), %rcx
  11190. cmpq %rcx, %rdx
  11191. jl block39
  11192. movq %r15, %rdi
  11193. movq $16, %rsi
  11194. callq collect
  11195. jmp block38
  11196. .globl main
  11197. main:
  11198. pushq %rbp
  11199. movq %rsp, %rbp
  11200. pushq %r13
  11201. pushq %r12
  11202. pushq %rbx
  11203. pushq %r14
  11204. subq $0, %rsp
  11205. movq $16384, %rdi
  11206. movq $16384, %rsi
  11207. callq initialize
  11208. movq rootstack_begin(%rip), %r15
  11209. movq $0, (%r15)
  11210. addq $8, %r15
  11211. jmp start
  11212. conclusion:
  11213. subq $8, %r15
  11214. addq $0, %rsp
  11215. popq %r14
  11216. popq %rbx
  11217. popq %r12
  11218. popq %r13
  11219. popq %rbp
  11220. retq
  11221. \end{lstlisting}
  11222. \end{minipage}
  11223. \caption{Output of the \code{prelude\_and\_conclusion} pass.}
  11224. \label{fig:print-x86-output-gc}
  11225. \end{figure}
  11226. \begin{figure}[p]
  11227. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11228. \node (Lvec) at (0,2) {\large \LangVec{}};
  11229. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11230. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11231. \node (Lvec-4) at (9,2) {\large \LangVec{}};
  11232. \node (Lvec-5) at (12,2) {\large \LangAllocANF{}};
  11233. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11234. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11235. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11236. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11237. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11238. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11239. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11240. %\path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize type-check} (Lvec-2);
  11241. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11242. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11243. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11244. \path[->,bend left=15] (Lvec-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvec-5);
  11245. \path[->,bend left=20] (Lvec-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11246. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11247. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11248. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11249. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11250. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11251. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  11252. \end{tikzpicture}
  11253. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11254. \label{fig:Lvec-passes}
  11255. \end{figure}
  11256. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11257. for the compilation of \LangVec{}.
  11258. {\if\edition\racketEd
  11259. \section{Challenge: Simple Structures}
  11260. \label{sec:simple-structures}
  11261. \index{subject}{struct}
  11262. \index{subject}{structure}
  11263. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  11264. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  11265. Recall that a \code{struct} in Typed Racket is a user-defined data
  11266. type that contains named fields and that is heap allocated, similar to
  11267. a vector. The following is an example of a structure definition, in
  11268. this case the definition of a \code{point} type.
  11269. \begin{lstlisting}
  11270. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11271. \end{lstlisting}
  11272. \begin{figure}[tbp]
  11273. \centering
  11274. \fbox{
  11275. \begin{minipage}{0.96\textwidth}
  11276. \[
  11277. \begin{array}{lcl}
  11278. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  11279. \MID (\key{Vector}\;\Type \ldots) \MID \key{Void} } \MID \Var \\
  11280. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  11281. \Exp &::=& \gray{ \Int \MID (\key{read}) \MID (\key{-}\;\Exp) \MID (\key{+} \; \Exp\;\Exp) \MID (\key{-}\;\Exp\;\Exp) } \\
  11282. &\MID& \gray{ \Var \MID (\key{let}~([\Var~\Exp])~\Exp) }\\
  11283. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  11284. \MID (\key{and}\;\Exp\;\Exp)
  11285. \MID (\key{or}\;\Exp\;\Exp)
  11286. \MID (\key{not}\;\Exp) } \\
  11287. &\MID& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  11288. \MID (\key{if}~\Exp~\Exp~\Exp) } \\
  11289. &\MID& \gray{ (\key{vector}\;\Exp \ldots)
  11290. \MID (\key{vector-ref}\;\Exp\;\Int) } \\
  11291. &\MID& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  11292. &\MID& \gray{ (\key{void}) } \MID (\Var\;\Exp \ldots)\\
  11293. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11294. \LangStruct{} &::=& \Def \ldots \; \Exp
  11295. \end{array}
  11296. \]
  11297. \end{minipage}
  11298. }
  11299. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11300. (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11301. \label{fig:r3s-concrete-syntax}
  11302. \end{figure}
  11303. An instance of a structure is created using function call syntax, with
  11304. the name of the structure in the function position:
  11305. \begin{lstlisting}
  11306. (point 7 12)
  11307. \end{lstlisting}
  11308. Function-call syntax is also used to read the value in a field of a
  11309. structure. The function name is formed by the structure name, a dash,
  11310. and the field name. The following example uses \code{point-x} and
  11311. \code{point-y} to access the \code{x} and \code{y} fields of two point
  11312. instances.
  11313. \begin{center}
  11314. \begin{lstlisting}
  11315. (let ([pt1 (point 7 12)])
  11316. (let ([pt2 (point 4 3)])
  11317. (+ (- (point-x pt1) (point-x pt2))
  11318. (- (point-y pt1) (point-y pt2)))))
  11319. \end{lstlisting}
  11320. \end{center}
  11321. Similarly, to write to a field of a structure, use its set function,
  11322. whose name starts with \code{set-}, followed by the structure name,
  11323. then a dash, then the field name, and concluded with an exclamation
  11324. mark. The following example uses \code{set-point-x!} to change the
  11325. \code{x} field from \code{7} to \code{42}.
  11326. \begin{center}
  11327. \begin{lstlisting}
  11328. (let ([pt (point 7 12)])
  11329. (let ([_ (set-point-x! pt 42)])
  11330. (point-x pt)))
  11331. \end{lstlisting}
  11332. \end{center}
  11333. \begin{exercise}\normalfont
  11334. Extend your compiler with support for simple structures, compiling
  11335. \LangStruct{} to x86 assembly code. Create five new test cases that use
  11336. structures and test your compiler.
  11337. \end{exercise}
  11338. \section{Challenge: Arrays}
  11339. \label{sec:arrays}
  11340. In Chapter~\ref{ch:Lvec} we studied tuples, that is, sequences of
  11341. elements whose length is determined at compile-time and where each
  11342. element of a tuple may have a different type (they are
  11343. heterogeous). This challenge is also about sequences, but this time
  11344. the length is determined at run-time and all the elements have the same
  11345. type (they are homogeneous). We use the term ``array'' for this later
  11346. kind of sequence.
  11347. The Racket language does not distinguish between tuples and arrays,
  11348. they are both represented by vectors. However, Typed Racket
  11349. distinguishes between tuples and arrays: the \code{Vector} type is for
  11350. tuples and the \code{Vectorof} type is for arrays.
  11351. %
  11352. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11353. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  11354. and the \code{make-vector} primitive operator for creating an array,
  11355. whose arguments are the length of the array and an initial value for
  11356. all the elements in the array. The \code{vector-length},
  11357. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11358. for tuples become overloaded for use with arrays.
  11359. %
  11360. We also include integer multiplication in \LangArray{}, as it is
  11361. useful in many examples involving arrays such as computing the
  11362. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  11363. \begin{figure}[tp]
  11364. \centering
  11365. \fbox{
  11366. \begin{minipage}{0.96\textwidth}
  11367. \small
  11368. \[
  11369. \begin{array}{lcl}
  11370. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  11371. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11372. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  11373. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11374. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11375. \MID \LP\key{and}\;\Exp\;\Exp\RP
  11376. \MID \LP\key{or}\;\Exp\;\Exp\RP
  11377. \MID \LP\key{not}\;\Exp\RP } \\
  11378. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11379. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  11380. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  11381. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  11382. \MID \LP\Exp \; \Exp\ldots\RP } \\
  11383. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11384. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11385. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  11386. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11387. \MID \CWHILE{\Exp}{\Exp} } \\
  11388. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  11389. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11390. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  11391. \end{array}
  11392. \]
  11393. \end{minipage}
  11394. }
  11395. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  11396. \label{fig:Lvecof-concrete-syntax}
  11397. \end{figure}
  11398. \begin{figure}[tp]
  11399. \begin{lstlisting}
  11400. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11401. [n : Integer]) : Integer
  11402. (let ([i 0])
  11403. (let ([prod 0])
  11404. (begin
  11405. (while (< i n)
  11406. (begin
  11407. (set! prod (+ prod (* (vector-ref A i)
  11408. (vector-ref B i))))
  11409. (set! i (+ i 1))
  11410. ))
  11411. prod))))
  11412. (let ([A (make-vector 2 2)])
  11413. (let ([B (make-vector 2 3)])
  11414. (+ (inner-product A B 2)
  11415. 30)))
  11416. \end{lstlisting}
  11417. \caption{Example program that computes the inner-product.}
  11418. \label{fig:inner-product}
  11419. \end{figure}
  11420. The type checker for \LangArray{} is define in
  11421. Figure~\ref{fig:type-check-Lvecof}. The result type of
  11422. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11423. of the intializing expression. The length expression is required to
  11424. have type \code{Integer}. The type checking of the operators
  11425. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11426. updated to handle the situation where the vector has type
  11427. \code{Vectorof}. In these cases we translate the operators to their
  11428. \code{vectorof} form so that later passes can easily distinguish
  11429. between operations on tuples versus arrays. We override the
  11430. \code{operator-types} method to provide the type signature for
  11431. multiplication: it takes two integers and returns an integer. To
  11432. support injection and projection of arrays to the \code{Any} type
  11433. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  11434. predicate.
  11435. \begin{figure}[tbp]
  11436. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11437. (define type-check-Lvecof_class
  11438. (class type-check-Rwhile_class
  11439. (super-new)
  11440. (inherit check-type-equal?)
  11441. (define/override (flat-ty? ty)
  11442. (match ty
  11443. ['(Vectorof Any) #t]
  11444. [else (super flat-ty? ty)]))
  11445. (define/override (operator-types)
  11446. (append '((* . ((Integer Integer) . Integer)))
  11447. (super operator-types)))
  11448. (define/override (type-check-exp env)
  11449. (lambda (e)
  11450. (define recur (type-check-exp env))
  11451. (match e
  11452. [(Prim 'make-vector (list e1 e2))
  11453. (define-values (e1^ t1) (recur e1))
  11454. (define-values (e2^ elt-type) (recur e2))
  11455. (define vec-type `(Vectorof ,elt-type))
  11456. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  11457. vec-type)]
  11458. [(Prim 'vector-ref (list e1 e2))
  11459. (define-values (e1^ t1) (recur e1))
  11460. (define-values (e2^ t2) (recur e2))
  11461. (match* (t1 t2)
  11462. [(`(Vectorof ,elt-type) 'Integer)
  11463. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  11464. [(other wise) ((super type-check-exp env) e)])]
  11465. [(Prim 'vector-set! (list e1 e2 e3) )
  11466. (define-values (e-vec t-vec) (recur e1))
  11467. (define-values (e2^ t2) (recur e2))
  11468. (define-values (e-arg^ t-arg) (recur e3))
  11469. (match t-vec
  11470. [`(Vectorof ,elt-type)
  11471. (check-type-equal? elt-type t-arg e)
  11472. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  11473. [else ((super type-check-exp env) e)])]
  11474. [(Prim 'vector-length (list e1))
  11475. (define-values (e1^ t1) (recur e1))
  11476. (match t1
  11477. [`(Vectorof ,t)
  11478. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  11479. [else ((super type-check-exp env) e)])]
  11480. [else ((super type-check-exp env) e)])))
  11481. ))
  11482. (define (type-check-Lvecof p)
  11483. (send (new type-check-Lvecof_class) type-check-program p))
  11484. \end{lstlisting}
  11485. \caption{Type checker for the \LangArray{} language.}
  11486. \label{fig:type-check-Lvecof}
  11487. \end{figure}
  11488. The interpreter for \LangArray{} is defined in
  11489. Figure~\ref{fig:interp-Lvecof}. The \code{make-vector} operator is
  11490. implemented with Racket's \code{make-vector} function and
  11491. multiplication is \code{fx*}, multiplication for \code{fixnum}
  11492. integers.
  11493. \begin{figure}[tbp]
  11494. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11495. (define interp-Lvecof_class
  11496. (class interp-Rwhile_class
  11497. (super-new)
  11498. (define/override (interp-op op)
  11499. (verbose "Lvecof/interp-op" op)
  11500. (match op
  11501. ['make-vector make-vector]
  11502. ['* fx*]
  11503. [else (super interp-op op)]))
  11504. ))
  11505. (define (interp-Lvecof p)
  11506. (send (new interp-Lvecof_class) interp-program p))
  11507. \end{lstlisting}
  11508. \caption{Interpreter for \LangArray{}.}
  11509. \label{fig:interp-Lvecof}
  11510. \end{figure}
  11511. \subsection{Data Representation}
  11512. \label{sec:array-rep}
  11513. Just like tuples, we store arrays on the heap which means that the
  11514. garbage collector will need to inspect arrays. An immediate thought is
  11515. to use the same representation for arrays that we use for tuples.
  11516. However, we limit tuples to a length of $50$ so that their length and
  11517. pointer mask can fit into the 64-bit tag at the beginning of each
  11518. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  11519. millions of elements, so we need more bits to store the length.
  11520. However, because arrays are homogeneous, we only need $1$ bit for the
  11521. pointer mask instead of one bit per array elements. Finally, the
  11522. garbage collector will need to be able to distinguish between tuples
  11523. and arrays, so we need to reserve $1$ bit for that purpose. So we
  11524. arrive at the following layout for the 64-bit tag at the beginning of
  11525. an array:
  11526. \begin{itemize}
  11527. \item The right-most bit is the forwarding bit, just like in a tuple.
  11528. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  11529. it is not.
  11530. \item The next bit to the left is the pointer mask. A $0$ indicates
  11531. that none of the elements are pointers to the heap and a $1$
  11532. indicates that all of the elements are pointers.
  11533. \item The next $61$ bits store the length of the array.
  11534. \item The left-most bit distinguishes between a tuple ($0$) versus an
  11535. array ($1$).
  11536. \end{itemize}
  11537. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  11538. differentiate the kinds of values that have been injected into the
  11539. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  11540. to indicate that the value is an array.
  11541. In the following subsections we provide hints regarding how to update
  11542. the passes to handle arrays.
  11543. \subsection{Reveal Casts}
  11544. The array-access operators \code{vectorof-ref} and
  11545. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  11546. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  11547. that the type checker cannot tell whether the index will be in bounds,
  11548. so the bounds check must be performed at run time. Recall that the
  11549. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  11550. an \code{If} arround a vector reference for update to check whether
  11551. the index is less than the length. You should do the same for
  11552. \code{vectorof-ref} and \code{vectorof-set!} .
  11553. In addition, the handling of the \code{any-vector} operators in
  11554. \code{reveal-casts} needs to be updated to account for arrays that are
  11555. injected to \code{Any}. For the \code{any-vector-length} operator, the
  11556. generated code should test whether the tag is for tuples (\code{010})
  11557. or arrays (\code{110}) and then dispatch to either
  11558. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  11559. we add a case in \code{select\_instructions} to generate the
  11560. appropriate instructions for accessing the array length from the
  11561. header of an array.
  11562. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  11563. the generated code needs to check that the index is less than the
  11564. vector length, so like the code for \code{any-vector-length}, check
  11565. the tag to determine whether to use \code{any-vector-length} or
  11566. \code{any-vectorof-length} for this purpose. Once the bounds checking
  11567. is complete, the generated code can use \code{any-vector-ref} and
  11568. \code{any-vector-set!} for both tuples and arrays because the
  11569. instructions used for those operators do not look at the tag at the
  11570. front of the tuple or array.
  11571. \subsection{Expose Allocation}
  11572. This pass should translate the \code{make-vector} operator into
  11573. lower-level operations. In particular, the new AST node
  11574. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  11575. length specified by the $\Exp$, but does not initialize the elements
  11576. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  11577. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  11578. element type for the array. Regarding the initialization of the array,
  11579. we recommend generated a \code{while} loop that uses
  11580. \code{vector-set!} to put the initializing value into every element of
  11581. the array.
  11582. \subsection{Remove Complex Operands}
  11583. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  11584. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  11585. complex and its subexpression must be atomic.
  11586. \subsection{Explicate Control}
  11587. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  11588. \code{explicate\_assign}.
  11589. \subsection{Select Instructions}
  11590. Generate instructions for \code{AllocateArray} similar to those for
  11591. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  11592. that the tag at the front of the array should instead use the
  11593. representation discussed in Section~\ref{sec:array-rep}.
  11594. Regarding \code{vectorof-length}, extract the length from the tag
  11595. according to the representation discussed in
  11596. Section~\ref{sec:array-rep}.
  11597. The instructions generated for \code{vectorof-ref} differ from those
  11598. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  11599. that the index is not a constant so the offset must be computed at
  11600. runtime, similar to the instructions generated for
  11601. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  11602. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  11603. appear in an assignment and as a stand-alone statement, so make sure
  11604. to handle both situations in this pass.
  11605. Finally, the instructions for \code{any-vectorof-length} should be
  11606. similar to those for \code{vectorof-length}, except that one must
  11607. first project the array by writing zeroes into the $3$-bit tag
  11608. \begin{exercise}\normalfont
  11609. Implement a compiler for the \LangArray{} language by extending your
  11610. compiler for \LangLoop{}. Test your compiler on a half dozen new
  11611. programs, including the one in Figure~\ref{fig:inner-product} and also
  11612. a program that multiplies two matrices. Note that matrices are
  11613. 2-dimensional arrays, but those can be encoded into 1-dimensional
  11614. arrays by laying out each row in the array, one after the next.
  11615. \end{exercise}
  11616. \section{Challenge: Generational Collection}
  11617. The copying collector described in Section~\ref{sec:GC} can incur
  11618. significant runtime overhead because the call to \code{collect} takes
  11619. time proportional to all of the live data. One way to reduce this
  11620. overhead is to reduce how much data is inspected in each call to
  11621. \code{collect}. In particular, researchers have observed that recently
  11622. allocated data is more likely to become garbage then data that has
  11623. survived one or more previous calls to \code{collect}. This insight
  11624. motivated the creation of \emph{generational garbage collectors}
  11625. \index{subject}{generational garbage collector} that
  11626. 1) segregates data according to its age into two or more generations,
  11627. 2) allocates less space for younger generations, so collecting them is
  11628. faster, and more space for the older generations, and 3) performs
  11629. collection on the younger generations more frequently then for older
  11630. generations~\citep{Wilson:1992fk}.
  11631. For this challenge assignment, the goal is to adapt the copying
  11632. collector implemented in \code{runtime.c} to use two generations, one
  11633. for young data and one for old data. Each generation consists of a
  11634. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  11635. \code{collect} function to use the two generations.
  11636. \begin{enumerate}
  11637. \item Copy the young generation's FromSpace to its ToSpace then switch
  11638. the role of the ToSpace and FromSpace
  11639. \item If there is enough space for the requested number of bytes in
  11640. the young FromSpace, then return from \code{collect}.
  11641. \item If there is not enough space in the young FromSpace for the
  11642. requested bytes, then move the data from the young generation to the
  11643. old one with the following steps:
  11644. \begin{enumerate}
  11645. \item If there is enough room in the old FromSpace, copy the young
  11646. FromSpace to the old FromSpace and then return.
  11647. \item If there is not enough room in the old FromSpace, then collect
  11648. the old generation by copying the old FromSpace to the old ToSpace
  11649. and swap the roles of the old FromSpace and ToSpace.
  11650. \item If there is enough room now, copy the young FromSpace to the
  11651. old FromSpace and return. Otherwise, allocate a larger FromSpace
  11652. and ToSpace for the old generation. Copy the young FromSpace and
  11653. the old FromSpace into the larger FromSpace for the old
  11654. generation and then return.
  11655. \end{enumerate}
  11656. \end{enumerate}
  11657. We recommend that you generalize the \code{cheney} function so that it
  11658. can be used for all the copies mentioned above: between the young
  11659. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  11660. between the young FromSpace and old FromSpace. This can be
  11661. accomplished by adding parameters to \code{cheney} that replace its
  11662. use of the global variables \code{fromspace\_begin},
  11663. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  11664. Note that the collection of the young generation does not traverse the
  11665. old generation. This introduces a potential problem: there may be
  11666. young data that is only reachable through pointers in the old
  11667. generation. If these pointers are not taken into account, the
  11668. collector could throw away young data that is live! One solution,
  11669. called \emph{pointer recording}, is to maintain a set of all the
  11670. pointers from the old generation into the new generation and consider
  11671. this set as part of the root set. To maintain this set, the compiler
  11672. must insert extra instructions around every \code{vector-set!}. If the
  11673. vector being modified is in the old generation, and if the value being
  11674. written is a pointer into the new generation, than that pointer must
  11675. be added to the set. Also, if the value being overwritten was a
  11676. pointer into the new generation, then that pointer should be removed
  11677. from the set.
  11678. \begin{exercise}\normalfont
  11679. Adapt the \code{collect} function in \code{runtime.c} to implement
  11680. generational garbage collection, as outlined in this section.
  11681. Update the code generation for \code{vector-set!} to implement
  11682. pointer recording. Make sure that your new compiler and runtime
  11683. passes your test suite.
  11684. \end{exercise}
  11685. \fi}
  11686. % Further Reading
  11687. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11688. \chapter{Functions}
  11689. \label{ch:Rfun}
  11690. \index{subject}{function}
  11691. \if\edition\racketEd
  11692. This chapter studies the compilation of functions similar to those
  11693. found in the C language. This corresponds to a subset of Typed Racket
  11694. in which only top-level function definitions are allowed. This kind of
  11695. function is an important stepping stone to implementing
  11696. lexically-scoped functions, that is, \key{lambda} abstractions, which
  11697. is the topic of Chapter~\ref{ch:Rlam}.
  11698. \section{The \LangFun{} Language}
  11699. The concrete and abstract syntax for function definitions and function
  11700. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  11701. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  11702. \LangFun{} begin with zero or more function definitions. The function
  11703. names from these definitions are in-scope for the entire program,
  11704. including all other function definitions (so the ordering of function
  11705. definitions does not matter). The concrete syntax for function
  11706. application\index{subject}{function application} is $(\Exp \; \Exp \ldots)$
  11707. where the first expression must
  11708. evaluate to a function and the rest are the arguments.
  11709. The abstract syntax for function application is
  11710. $\APPLY{\Exp}{\Exp\ldots}$.
  11711. %% The syntax for function application does not include an explicit
  11712. %% keyword, which is error prone when using \code{match}. To alleviate
  11713. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  11714. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  11715. Functions are first-class in the sense that a function pointer
  11716. \index{subject}{function pointer} is data and can be stored in memory or passed
  11717. as a parameter to another function. Thus, we introduce a function
  11718. type, written
  11719. \begin{lstlisting}
  11720. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  11721. \end{lstlisting}
  11722. for a function whose $n$ parameters have the types $\Type_1$ through
  11723. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  11724. these functions (with respect to Racket functions) is that they are
  11725. not lexically scoped. That is, the only external entities that can be
  11726. referenced from inside a function body are other globally-defined
  11727. functions. The syntax of \LangFun{} prevents functions from being nested
  11728. inside each other.
  11729. \newcommand{\LfunGrammarRacket}{
  11730. \begin{array}{lcl}
  11731. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  11732. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  11733. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  11734. \end{array}
  11735. }
  11736. \newcommand{\LfunASTRacket}{
  11737. \begin{array}{lcl}
  11738. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  11739. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  11740. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  11741. \end{array}
  11742. }
  11743. \begin{figure}[tp]
  11744. \centering
  11745. \fbox{
  11746. \begin{minipage}{0.96\textwidth}
  11747. \small
  11748. \[
  11749. \begin{array}{l}
  11750. \gray{\LintGrammarRacket{}} \\ \hline
  11751. \gray{\LvarGrammarRacket{}} \\ \hline
  11752. \gray{\LifGrammarRacket{}} \\ \hline
  11753. \gray{\LwhileGrammarRacket} \\ \hline
  11754. \gray{\LtupGrammarRacket} \\ \hline
  11755. \LfunGrammarRacket \\
  11756. \begin{array}{lcl}
  11757. %% \Type &::=& \gray{ \key{Integer} \MID \key{Boolean}
  11758. %% \MID (\key{Vector}\;\Type\ldots) \MID \key{Void} } \MID (\Type \ldots \; \key{->}\; \Type) \\
  11759. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  11760. %% \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  11761. %% &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11762. %% &\MID& \gray{ \key{\#t} \MID \key{\#f}
  11763. %% \MID (\key{and}\;\Exp\;\Exp)
  11764. %% \MID (\key{or}\;\Exp\;\Exp)
  11765. %% \MID (\key{not}\;\Exp)} \\
  11766. %% &\MID& \gray{(\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11767. %% &\MID& \gray{(\key{vector}\;\Exp\ldots) \MID
  11768. %% (\key{vector-ref}\;\Exp\;\Int)} \\
  11769. %% &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  11770. %% \MID \LP\key{has-type}~\Exp~\Type\RP } \\
  11771. %% &\MID& \LP\Exp \; \Exp \ldots\RP \\
  11772. %% \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  11773. \LangFunM{} &::=& \Def \ldots \; \Exp
  11774. \end{array}
  11775. \end{array}
  11776. \]
  11777. \end{minipage}
  11778. }
  11779. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11780. \label{fig:Rfun-concrete-syntax}
  11781. \end{figure}
  11782. \begin{figure}[tp]
  11783. \centering
  11784. \fbox{
  11785. \begin{minipage}{0.96\textwidth}
  11786. \small
  11787. \[
  11788. \begin{array}{l}
  11789. \gray{\LintOpAST} \\ \hline
  11790. \gray{\LvarAST{}} \\ \hline
  11791. \gray{\LifAST{}} \\ \hline
  11792. \gray{\LwhileAST{}} \\ \hline
  11793. \gray{\LtupASTRacket{}} \\ \hline
  11794. \LfunASTRacket \\
  11795. \begin{array}{lcl}
  11796. %% \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  11797. %% &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  11798. %% &\MID& \gray{ \BOOL{\itm{bool}}
  11799. %% \MID \IF{\Exp}{\Exp}{\Exp} } \\
  11800. %% &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP }
  11801. %% \MID \APPLY{\Exp}{\Exp\ldots}\\
  11802. %% \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  11803. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11804. \end{array}
  11805. \end{array}
  11806. \]
  11807. \end{minipage}
  11808. }
  11809. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  11810. \label{fig:Rfun-syntax}
  11811. \end{figure}
  11812. The program in Figure~\ref{fig:Rfun-function-example} is a
  11813. representative example of defining and using functions in \LangFun{}. We
  11814. define a function \code{map-vec} that applies some other function
  11815. \code{f} to both elements of a vector and returns a new
  11816. vector containing the results. We also define a function \code{add1}.
  11817. The program applies
  11818. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  11819. \code{(vector 1 42)}, from which we return the \code{42}.
  11820. \begin{figure}[tbp]
  11821. \begin{lstlisting}
  11822. (define (map-vec [f : (Integer -> Integer)]
  11823. [v : (Vector Integer Integer)])
  11824. : (Vector Integer Integer)
  11825. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11826. (define (add1 [x : Integer]) : Integer
  11827. (+ x 1))
  11828. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11829. \end{lstlisting}
  11830. \caption{Example of using functions in \LangFun{}.}
  11831. \label{fig:Rfun-function-example}
  11832. \end{figure}
  11833. The definitional interpreter for \LangFun{} is in
  11834. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  11835. responsible for setting up the mutual recursion between the top-level
  11836. function definitions. We use the classic back-patching \index{subject}{back-patching}
  11837. approach that uses mutable variables and makes two passes over the function
  11838. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  11839. top-level environment using a mutable cons cell for each function
  11840. definition. Note that the \code{lambda} value for each function is
  11841. incomplete; it does not yet include the environment. Once the
  11842. top-level environment is constructed, we then iterate over it and
  11843. update the \code{lambda} values to use the top-level environment.
  11844. \begin{figure}[tp]
  11845. \begin{lstlisting}
  11846. (define interp-Rfun_class
  11847. (class interp-Lvec_class
  11848. (super-new)
  11849. (define/override ((interp-exp env) e)
  11850. (define recur (interp-exp env))
  11851. (match e
  11852. [(Var x) (unbox (dict-ref env x))]
  11853. [(Let x e body)
  11854. (define new-env (dict-set env x (box (recur e))))
  11855. ((interp-exp new-env) body)]
  11856. [(Apply fun args)
  11857. (define fun-val (recur fun))
  11858. (define arg-vals (for/list ([e args]) (recur e)))
  11859. (match fun-val
  11860. [`(function (,xs ...) ,body ,fun-env)
  11861. (define params-args (for/list ([x xs] [arg arg-vals])
  11862. (cons x (box arg))))
  11863. (define new-env (append params-args fun-env))
  11864. ((interp-exp new-env) body)]
  11865. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  11866. [else ((super interp-exp env) e)]
  11867. ))
  11868. (define/public (interp-def d)
  11869. (match d
  11870. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  11871. (cons f (box `(function ,xs ,body ())))]))
  11872. (define/override (interp-program p)
  11873. (match p
  11874. [(ProgramDefsExp info ds body)
  11875. (let ([top-level (for/list ([d ds]) (interp-def d))])
  11876. (for/list ([f (in-dict-values top-level)])
  11877. (set-box! f (match (unbox f)
  11878. [`(function ,xs ,body ())
  11879. `(function ,xs ,body ,top-level)])))
  11880. ((interp-exp top-level) body))]))
  11881. ))
  11882. (define (interp-Rfun p)
  11883. (send (new interp-Rfun_class) interp-program p))
  11884. \end{lstlisting}
  11885. \caption{Interpreter for the \LangFun{} language.}
  11886. \label{fig:interp-Rfun}
  11887. \end{figure}
  11888. %\margincomment{TODO: explain type checker}
  11889. The type checker for \LangFun{} is in Figure~\ref{fig:type-check-Rfun}.
  11890. \begin{figure}[tp]
  11891. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11892. (define type-check-Rfun_class
  11893. (class type-check-Lvec_class
  11894. (super-new)
  11895. (inherit check-type-equal?)
  11896. (define/public (type-check-apply env e es)
  11897. (define-values (e^ ty) ((type-check-exp env) e))
  11898. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  11899. ((type-check-exp env) e)))
  11900. (match ty
  11901. [`(,ty^* ... -> ,rt)
  11902. (for ([arg-ty ty*] [param-ty ty^*])
  11903. (check-type-equal? arg-ty param-ty (Apply e es)))
  11904. (values e^ e* rt)]))
  11905. (define/override (type-check-exp env)
  11906. (lambda (e)
  11907. (match e
  11908. [(FunRef f)
  11909. (values (FunRef f) (dict-ref env f))]
  11910. [(Apply e es)
  11911. (define-values (e^ es^ rt) (type-check-apply env e es))
  11912. (values (Apply e^ es^) rt)]
  11913. [(Call e es)
  11914. (define-values (e^ es^ rt) (type-check-apply env e es))
  11915. (values (Call e^ es^) rt)]
  11916. [else ((super type-check-exp env) e)])))
  11917. (define/public (type-check-def env)
  11918. (lambda (e)
  11919. (match e
  11920. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  11921. (define new-env (append (map cons xs ps) env))
  11922. (define-values (body^ ty^) ((type-check-exp new-env) body))
  11923. (check-type-equal? ty^ rt body)
  11924. (Def f p:t* rt info body^)])))
  11925. (define/public (fun-def-type d)
  11926. (match d
  11927. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  11928. (define/override (type-check-program e)
  11929. (match e
  11930. [(ProgramDefsExp info ds body)
  11931. (define new-env (for/list ([d ds])
  11932. (cons (Def-name d) (fun-def-type d))))
  11933. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  11934. (define-values (body^ ty) ((type-check-exp new-env) body))
  11935. (check-type-equal? ty 'Integer body)
  11936. (ProgramDefsExp info ds^ body^)]))))
  11937. (define (type-check-Rfun p)
  11938. (send (new type-check-Rfun_class) type-check-program p))
  11939. \end{lstlisting}
  11940. \caption{Type checker for the \LangFun{} language.}
  11941. \label{fig:type-check-Rfun}
  11942. \end{figure}
  11943. \section{Functions in x86}
  11944. \label{sec:fun-x86}
  11945. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  11946. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  11947. %% \margincomment{\tiny Talk about the return address on the
  11948. %% stack and what callq and retq does.\\ --Jeremy }
  11949. The x86 architecture provides a few features to support the
  11950. implementation of functions. We have already seen that x86 provides
  11951. labels so that one can refer to the location of an instruction, as is
  11952. needed for jump instructions. Labels can also be used to mark the
  11953. beginning of the instructions for a function. Going further, we can
  11954. obtain the address of a label by using the \key{leaq} instruction and
  11955. PC-relative addressing. For example, the following puts the
  11956. address of the \code{add1} label into the \code{rbx} register.
  11957. \begin{lstlisting}
  11958. leaq add1(%rip), %rbx
  11959. \end{lstlisting}
  11960. The instruction pointer register \key{rip} (aka. the program counter
  11961. \index{subject}{program counter}) always points to the next instruction to be
  11962. executed. When combined with an label, as in \code{add1(\%rip)}, the
  11963. linker computes the distance $d$ between the address of \code{add1}
  11964. and where the \code{rip} would be at that moment and then changes
  11965. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  11966. the address of \code{add1}.
  11967. In Section~\ref{sec:x86} we used the \code{callq} instruction to jump
  11968. to functions whose locations were given by a label, such as
  11969. \code{read\_int}. To support function calls in this chapter we instead
  11970. will be jumping to functions whose location are given by an address in
  11971. a register, that is, we need to make an \emph{indirect function
  11972. call}. The x86 syntax for this is a \code{callq} instruction but with
  11973. an asterisk before the register name.\index{subject}{indirect function
  11974. call}
  11975. \begin{lstlisting}
  11976. callq *%rbx
  11977. \end{lstlisting}
  11978. \subsection{Calling Conventions}
  11979. \index{subject}{calling conventions}
  11980. The \code{callq} instruction provides partial support for implementing
  11981. functions: it pushes the return address on the stack and it jumps to
  11982. the target. However, \code{callq} does not handle
  11983. \begin{enumerate}
  11984. \item parameter passing,
  11985. \item pushing frames on the procedure call stack and popping them off,
  11986. or
  11987. \item determining how registers are shared by different functions.
  11988. \end{enumerate}
  11989. Regarding (1) parameter passing, recall that the following six
  11990. registers are used to pass arguments to a function, in this order.
  11991. \begin{lstlisting}
  11992. rdi rsi rdx rcx r8 r9
  11993. \end{lstlisting}
  11994. If there are
  11995. more than six arguments, then the convention is to use space on the
  11996. frame of the caller for the rest of the arguments. However, to ease
  11997. the implementation of efficient tail calls
  11998. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  11999. arguments.
  12000. %
  12001. Also recall that the register \code{rax} is for the return value of
  12002. the function.
  12003. \index{subject}{prelude}\index{subject}{conclusion}
  12004. Regarding (2) frames \index{subject}{frame} and the procedure call
  12005. stack, \index{subject}{procedure call stack} recall from
  12006. Section~\ref{sec:x86} that the stack grows down and each function call
  12007. uses a chunk of space on the stack called a frame. The caller sets the
  12008. stack pointer, register \code{rsp}, to the last data item in its
  12009. frame. The callee must not change anything in the caller's frame, that
  12010. is, anything that is at or above the stack pointer. The callee is free
  12011. to use locations that are below the stack pointer.
  12012. Recall that we are storing variables of tuple type on the root stack.
  12013. So the prelude needs to move the root stack pointer \code{r15} up and
  12014. the conclusion needs to move the root stack pointer back down. Also,
  12015. the prelude must initialize to \code{0} this frame's slots in the root
  12016. stack to signal to the garbage collector that those slots do not yet
  12017. contain a pointer to a vector. Otherwise the garbage collector will
  12018. interpret the garbage bits in those slots as memory addresses and try
  12019. to traverse them, causing serious mayhem!
  12020. Regarding (3) the sharing of registers between different functions,
  12021. recall from Section~\ref{sec:calling-conventions} that the registers
  12022. are divided into two groups, the caller-saved registers and the
  12023. callee-saved registers. The caller should assume that all the
  12024. caller-saved registers get overwritten with arbitrary values by the
  12025. callee. That is why we recommend in
  12026. Section~\ref{sec:calling-conventions} that variables that are live
  12027. during a function call should not be assigned to caller-saved
  12028. registers.
  12029. On the flip side, if the callee wants to use a callee-saved register,
  12030. the callee must save the contents of those registers on their stack
  12031. frame and then put them back prior to returning to the caller. That
  12032. is why we recommended in Section~\ref{sec:calling-conventions} that if
  12033. the register allocator assigns a variable to a callee-saved register,
  12034. then the prelude of the \code{main} function must save that register
  12035. to the stack and the conclusion of \code{main} must restore it. This
  12036. recommendation now generalizes to all functions.
  12037. Recall that the base pointer, register \code{rbp}, is used as a
  12038. point-of-reference within a frame, so that each local variable can be
  12039. accessed at a fixed offset from the base pointer
  12040. (Section~\ref{sec:x86}).
  12041. %
  12042. Figure~\ref{fig:call-frames} shows the general layout of the caller
  12043. and callee frames.
  12044. \begin{figure}[tbp]
  12045. \centering
  12046. \begin{tabular}{r|r|l|l} \hline
  12047. Caller View & Callee View & Contents & Frame \\ \hline
  12048. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  12049. 0(\key{\%rbp}) & & old \key{rbp} \\
  12050. -8(\key{\%rbp}) & & callee-saved $1$ \\
  12051. \ldots & & \ldots \\
  12052. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  12053. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  12054. \ldots & & \ldots \\
  12055. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  12056. %% & & \\
  12057. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  12058. %% & \ldots & \ldots \\
  12059. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  12060. \hline
  12061. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  12062. & 0(\key{\%rbp}) & old \key{rbp} \\
  12063. & -8(\key{\%rbp}) & callee-saved $1$ \\
  12064. & \ldots & \ldots \\
  12065. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  12066. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  12067. & \ldots & \ldots \\
  12068. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  12069. \end{tabular}
  12070. \caption{Memory layout of caller and callee frames.}
  12071. \label{fig:call-frames}
  12072. \end{figure}
  12073. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  12074. %% local variables and for storing the values of callee-saved registers
  12075. %% (we shall refer to all of these collectively as ``locals''), and that
  12076. %% at the beginning of a function we move the stack pointer \code{rsp}
  12077. %% down to make room for them.
  12078. %% We recommend storing the local variables
  12079. %% first and then the callee-saved registers, so that the local variables
  12080. %% can be accessed using \code{rbp} the same as before the addition of
  12081. %% functions.
  12082. %% To make additional room for passing arguments, we shall
  12083. %% move the stack pointer even further down. We count how many stack
  12084. %% arguments are needed for each function call that occurs inside the
  12085. %% body of the function and find their maximum. Adding this number to the
  12086. %% number of locals gives us how much the \code{rsp} should be moved at
  12087. %% the beginning of the function. In preparation for a function call, we
  12088. %% offset from \code{rsp} to set up the stack arguments. We put the first
  12089. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  12090. %% so on.
  12091. %% Upon calling the function, the stack arguments are retrieved by the
  12092. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  12093. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  12094. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  12095. %% the layout of the caller and callee frames. Notice how important it is
  12096. %% that we correctly compute the maximum number of arguments needed for
  12097. %% function calls; if that number is too small then the arguments and
  12098. %% local variables will smash into each other!
  12099. \subsection{Efficient Tail Calls}
  12100. \label{sec:tail-call}
  12101. In general, the amount of stack space used by a program is determined
  12102. by the longest chain of nested function calls. That is, if function
  12103. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  12104. $f_n$, then the amount of stack space is linear in $n$. The depth $n$
  12105. can grow quite large in the case of recursive or mutually recursive
  12106. functions. However, in some cases we can arrange to use only a
  12107. constant amount of space for a long chain of nested function calls.
  12108. If a function call is the last action in a function body, then that
  12109. call is said to be a \emph{tail call}\index{subject}{tail call}.
  12110. For example, in the following
  12111. program, the recursive call to \code{tail\_sum} is a tail call.
  12112. \begin{center}
  12113. \begin{lstlisting}
  12114. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  12115. (if (eq? n 0)
  12116. r
  12117. (tail_sum (- n 1) (+ n r))))
  12118. (+ (tail_sum 5 0) 27)
  12119. \end{lstlisting}
  12120. \end{center}
  12121. At a tail call, the frame of the caller is no longer needed, so we can
  12122. pop the caller's frame before making the tail call. With this
  12123. approach, a recursive function that only makes tail calls will only
  12124. use a constant amount of stack space. Functional languages like
  12125. Racket typically rely heavily on recursive functions, so they
  12126. typically guarantee that all tail calls will be optimized in this way.
  12127. \index{subject}{frame}
  12128. Some care is needed with regards to argument passing in tail calls.
  12129. As mentioned above, for arguments beyond the sixth, the convention is
  12130. to use space in the caller's frame for passing arguments. But for a
  12131. tail call we pop the caller's frame and can no longer use it. An
  12132. alternative is to use space in the callee's frame for passing
  12133. arguments. However, this option is also problematic because the caller
  12134. and callee's frames overlap in memory. As we begin to copy the
  12135. arguments from their sources in the caller's frame, the target
  12136. locations in the callee's frame might collide with the sources for
  12137. later arguments! We solve this problem by using the heap instead of
  12138. the stack for passing more than six arguments, which we describe in
  12139. the Section~\ref{sec:limit-functions-r4}.
  12140. As mentioned above, for a tail call we pop the caller's frame prior to
  12141. making the tail call. The instructions for popping a frame are the
  12142. instructions that we usually place in the conclusion of a
  12143. function. Thus, we also need to place such code immediately before
  12144. each tail call. These instructions include restoring the callee-saved
  12145. registers, so it is fortunate that the argument passing registers are
  12146. all caller-saved registers!
  12147. One last note regarding which instruction to use to make the tail
  12148. call. When the callee is finished, it should not return to the current
  12149. function, but it should return to the function that called the current
  12150. one. Thus, the return address that is already on the stack is the
  12151. right one, and we should not use \key{callq} to make the tail call, as
  12152. that would unnecessarily overwrite the return address. Instead we can
  12153. simply use the \key{jmp} instruction. Like the indirect function call,
  12154. we write an \emph{indirect jump}\index{subject}{indirect jump} with a
  12155. register prefixed with an asterisk. We recommend using \code{rax} to
  12156. hold the jump target because the preceding conclusion can overwrite
  12157. just about everything else.
  12158. \begin{lstlisting}
  12159. jmp *%rax
  12160. \end{lstlisting}
  12161. \section{Shrink \LangFun{}}
  12162. \label{sec:shrink-r4}
  12163. The \code{shrink} pass performs a minor modification to ease the
  12164. later passes. This pass introduces an explicit \code{main} function
  12165. and changes the top \code{ProgramDefsExp} form to
  12166. \code{ProgramDefs} as follows.
  12167. \begin{lstlisting}
  12168. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  12169. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  12170. \end{lstlisting}
  12171. where $\itm{mainDef}$ is
  12172. \begin{lstlisting}
  12173. (Def 'main '() 'Integer '() |$\Exp'$|)
  12174. \end{lstlisting}
  12175. \section{Reveal Functions and the \LangFunRef{} language}
  12176. \label{sec:reveal-functions-r4}
  12177. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  12178. respect: it conflates the use of function names and local
  12179. variables. This is a problem because we need to compile the use of a
  12180. function name differently than the use of a local variable; we need to
  12181. use \code{leaq} to convert the function name (a label in x86) to an
  12182. address in a register. Thus, it is a good idea to create a new pass
  12183. that changes function references from just a symbol $f$ to
  12184. $\FUNREF{f}$. This pass is named \code{reveal\_functions} and the
  12185. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  12186. The concrete syntax for a function reference is $\CFUNREF{f}$.
  12187. \begin{figure}[tp]
  12188. \centering
  12189. \fbox{
  12190. \begin{minipage}{0.96\textwidth}
  12191. \[
  12192. \begin{array}{lcl}
  12193. \Exp &::=& \ldots \MID \FUNREF{\Var}\\
  12194. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12195. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  12196. \end{array}
  12197. \]
  12198. \end{minipage}
  12199. }
  12200. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  12201. (Figure~\ref{fig:Rfun-syntax}).}
  12202. \label{fig:f1-syntax}
  12203. \end{figure}
  12204. %% Distinguishing between calls in tail position and non-tail position
  12205. %% requires the pass to have some notion of context. We recommend using
  12206. %% two mutually recursive functions, one for processing expressions in
  12207. %% tail position and another for the rest.
  12208. Placing this pass after \code{uniquify} will make sure that there are
  12209. no local variables and functions that share the same name. On the
  12210. other hand, \code{reveal\_functions} needs to come before the
  12211. \code{remove\_complex\_operands} pass because function references
  12212. should be categorized as complex expressions.
  12213. \section{Limit Functions}
  12214. \label{sec:limit-functions-r4}
  12215. Recall that we wish to limit the number of function parameters to six
  12216. so that we do not need to use the stack for argument passing, which
  12217. makes it easier to implement efficient tail calls. However, because
  12218. the input language \LangFun{} supports arbitrary numbers of function
  12219. arguments, we have some work to do!
  12220. This pass transforms functions and function calls that involve more
  12221. than six arguments to pass the first five arguments as usual, but it
  12222. packs the rest of the arguments into a vector and passes it as the
  12223. sixth argument.
  12224. Each function definition with too many parameters is transformed as
  12225. follows.
  12226. \begin{lstlisting}
  12227. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  12228. |$\Rightarrow$|
  12229. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  12230. \end{lstlisting}
  12231. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  12232. the occurrences of the later parameters with vector references.
  12233. \begin{lstlisting}
  12234. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  12235. \end{lstlisting}
  12236. For function calls with too many arguments, the \code{limit-functions}
  12237. pass transforms them in the following way.
  12238. \begin{tabular}{lll}
  12239. \begin{minipage}{0.2\textwidth}
  12240. \begin{lstlisting}
  12241. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  12242. \end{lstlisting}
  12243. \end{minipage}
  12244. &
  12245. $\Rightarrow$
  12246. &
  12247. \begin{minipage}{0.4\textwidth}
  12248. \begin{lstlisting}
  12249. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  12250. \end{lstlisting}
  12251. \end{minipage}
  12252. \end{tabular}
  12253. \section{Remove Complex Operands}
  12254. \label{sec:rco-r4}
  12255. The primary decisions to make for this pass is whether to classify
  12256. \code{FunRef} and \code{Apply} as either atomic or complex
  12257. expressions. Recall that a simple expression will eventually end up as
  12258. just an immediate argument of an x86 instruction. Function
  12259. application will be translated to a sequence of instructions, so
  12260. \code{Apply} must be classified as complex expression.
  12261. On the other hand, the arguments of \code{Apply} should be
  12262. atomic expressions.
  12263. %
  12264. Regarding \code{FunRef}, as discussed above, the function label needs
  12265. to be converted to an address using the \code{leaq} instruction. Thus,
  12266. even though \code{FunRef} seems rather simple, it needs to be
  12267. classified as a complex expression so that we generate an assignment
  12268. statement with a left-hand side that can serve as the target of the
  12269. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  12270. output language \LangFunANF{} of this pass.
  12271. \begin{figure}[tp]
  12272. \centering
  12273. \fbox{
  12274. \begin{minipage}{0.96\textwidth}
  12275. \small
  12276. \[
  12277. \begin{array}{rcl}
  12278. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  12279. \MID \VOID{} } \\
  12280. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  12281. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  12282. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  12283. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  12284. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  12285. &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  12286. \MID \LP\key{GlobalValue}~\Var\RP }\\
  12287. &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  12288. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12289. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  12290. \end{array}
  12291. \]
  12292. \end{minipage}
  12293. }
  12294. \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  12295. \label{fig:Rfun-anf-syntax}
  12296. \end{figure}
  12297. \section{Explicate Control and the \LangCFun{} language}
  12298. \label{sec:explicate-control-r4}
  12299. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  12300. output of \code{explicate\_control}. (The concrete syntax is given in
  12301. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  12302. functions for assignment and tail contexts should be updated with
  12303. cases for \code{Apply} and \code{FunRef} and the function for
  12304. predicate context should be updated for \code{Apply} but not
  12305. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  12306. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  12307. tail position \code{Apply} becomes \code{TailCall}. We recommend
  12308. defining a new auxiliary function for processing function definitions.
  12309. This code is similar to the case for \code{Program} in \LangVec{}. The
  12310. top-level \code{explicate\_control} function that handles the
  12311. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  12312. all the function definitions.
  12313. \begin{figure}[tp]
  12314. \fbox{
  12315. \begin{minipage}{0.96\textwidth}
  12316. \small
  12317. \[
  12318. \begin{array}{lcl}
  12319. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  12320. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  12321. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  12322. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  12323. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  12324. &\MID& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  12325. &\MID& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  12326. &\MID& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  12327. &\MID& \gray{ \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP }\\
  12328. &\MID& \FUNREF{\itm{label}} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  12329. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  12330. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  12331. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  12332. \MID \GOTO{\itm{label}} } \\
  12333. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  12334. &\MID& \TAILCALL{\Atm}{\Atm\ldots} \\
  12335. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  12336. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12337. \end{array}
  12338. \]
  12339. \end{minipage}
  12340. }
  12341. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  12342. \label{fig:c3-syntax}
  12343. \end{figure}
  12344. \section{Select Instructions and the \LangXIndCall{} Language}
  12345. \label{sec:select-r4}
  12346. \index{subject}{instruction selection}
  12347. The output of select instructions is a program in the \LangXIndCall{}
  12348. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  12349. \index{subject}{x86}
  12350. \begin{figure}[tp]
  12351. \fbox{
  12352. \begin{minipage}{0.96\textwidth}
  12353. \small
  12354. \[
  12355. \begin{array}{lcl}
  12356. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)}
  12357. \MID \LP\key{fun-ref}\; \itm{label}\RP\\
  12358. \itm{cc} & ::= & \gray{ \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  12359. \Instr &::=& \ldots
  12360. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  12361. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  12362. \Block &::= & \Instr\ldots \\
  12363. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  12364. \LangXIndCallM{} &::= & \Def\ldots
  12365. \end{array}
  12366. \]
  12367. \end{minipage}
  12368. }
  12369. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  12370. \label{fig:x86-3-concrete}
  12371. \end{figure}
  12372. \begin{figure}[tp]
  12373. \fbox{
  12374. \begin{minipage}{0.96\textwidth}
  12375. \small
  12376. \[
  12377. \begin{array}{lcl}
  12378. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  12379. \MID \BYTEREG{\Reg} } \\
  12380. &\MID& \gray{ (\key{Global}~\Var) } \MID \FUNREF{\itm{label}} \\
  12381. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  12382. \MID \TAILJMP{\Arg}{\itm{int}}\\
  12383. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  12384. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  12385. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  12386. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12387. \end{array}
  12388. \]
  12389. \end{minipage}
  12390. }
  12391. \caption{The abstract syntax of \LangXIndCall{} (extends
  12392. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  12393. \label{fig:x86-3}
  12394. \end{figure}
  12395. An assignment of a function reference to a variable becomes a
  12396. load-effective-address instruction as follows, where $\itm{lhs}'$
  12397. is the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{}
  12398. to \Arg{} in \LangXIndCallVar{}. \\
  12399. \begin{tabular}{lcl}
  12400. \begin{minipage}{0.35\textwidth}
  12401. \begin{lstlisting}
  12402. |$\itm{lhs}$| = (fun-ref |$f$|);
  12403. \end{lstlisting}
  12404. \end{minipage}
  12405. &
  12406. $\Rightarrow$\qquad\qquad
  12407. &
  12408. \begin{minipage}{0.3\textwidth}
  12409. \begin{lstlisting}
  12410. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  12411. \end{lstlisting}
  12412. \end{minipage}
  12413. \end{tabular} \\
  12414. Regarding function definitions, we need to remove the parameters and
  12415. instead perform parameter passing using the conventions discussed in
  12416. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  12417. registers. We recommend turning the parameters into local variables
  12418. and generating instructions at the beginning of the function to move
  12419. from the argument passing registers to these local variables.
  12420. \begin{lstlisting}
  12421. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  12422. |$\Rightarrow$|
  12423. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  12424. \end{lstlisting}
  12425. The $G'$ control-flow graph is the same as $G$ except that the
  12426. \code{start} block is modified to add the instructions for moving from
  12427. the argument registers to the parameter variables. So the \code{start}
  12428. block of $G$ shown on the left is changed to the code on the right.
  12429. \begin{center}
  12430. \begin{minipage}{0.3\textwidth}
  12431. \begin{lstlisting}
  12432. start:
  12433. |$\itm{instr}_1$|
  12434. |$\vdots$|
  12435. |$\itm{instr}_n$|
  12436. \end{lstlisting}
  12437. \end{minipage}
  12438. $\Rightarrow$
  12439. \begin{minipage}{0.3\textwidth}
  12440. \begin{lstlisting}
  12441. start:
  12442. movq %rdi, |$x_1$|
  12443. movq %rsi, |$x_2$|
  12444. |$\vdots$|
  12445. |$\itm{instr}_1$|
  12446. |$\vdots$|
  12447. |$\itm{instr}_n$|
  12448. \end{lstlisting}
  12449. \end{minipage}
  12450. \end{center}
  12451. By changing the parameters to local variables, we are giving the
  12452. register allocator control over which registers or stack locations to
  12453. use for them. If you implemented the move-biasing challenge
  12454. (Section~\ref{sec:move-biasing}), the register allocator will try to
  12455. assign the parameter variables to the corresponding argument register,
  12456. in which case the \code{patch\_instructions} pass will remove the
  12457. \code{movq} instruction. This happens in the example translation in
  12458. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  12459. the \code{add} function.
  12460. %
  12461. Also, note that the register allocator will perform liveness analysis
  12462. on this sequence of move instructions and build the interference
  12463. graph. So, for example, $x_1$ will be marked as interfering with
  12464. \code{rsi} and that will prevent the assignment of $x_1$ to
  12465. \code{rsi}, which is good, because that would overwrite the argument
  12466. that needs to move into $x_2$.
  12467. Next, consider the compilation of function calls. In the mirror image
  12468. of handling the parameters of function definitions, the arguments need
  12469. to be moved to the argument passing registers. The function call
  12470. itself is performed with an indirect function call. The return value
  12471. from the function is stored in \code{rax}, so it needs to be moved
  12472. into the \itm{lhs}.
  12473. \begin{lstlisting}
  12474. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  12475. |$\Rightarrow$|
  12476. movq |$\itm{arg}_1$|, %rdi
  12477. movq |$\itm{arg}_2$|, %rsi
  12478. |$\vdots$|
  12479. callq *|\itm{fun}|
  12480. movq %rax, |\itm{lhs}|
  12481. \end{lstlisting}
  12482. The \code{IndirectCallq} AST node includes an integer for the arity of
  12483. the function, i.e., the number of parameters. That information is
  12484. useful in the \code{uncover-live} pass for determining which
  12485. argument-passing registers are potentially read during the call.
  12486. For tail calls, the parameter passing is the same as non-tail calls:
  12487. generate instructions to move the arguments into to the argument
  12488. passing registers. After that we need to pop the frame from the
  12489. procedure call stack. However, we do not yet know how big the frame
  12490. is; that gets determined during register allocation. So instead of
  12491. generating those instructions here, we invent a new instruction that
  12492. means ``pop the frame and then do an indirect jump'', which we name
  12493. \code{TailJmp}. The abstract syntax for this instruction includes an
  12494. argument that specifies where to jump and an integer that represents
  12495. the arity of the function being called.
  12496. Recall that in Section~\ref{sec:explicate-control-Lvar} we recommended
  12497. using the label \code{start} for the initial block of a program, and
  12498. in Section~\ref{sec:select-Lvar} we recommended labeling the conclusion
  12499. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  12500. can be compiled to an assignment to \code{rax} followed by a jump to
  12501. \code{conclusion}. With the addition of function definitions, we will
  12502. have a starting block and conclusion for each function, but their
  12503. labels need to be unique. We recommend prepending the function's name
  12504. to \code{start} and \code{conclusion}, respectively, to obtain unique
  12505. labels. (Alternatively, one could \code{gensym} labels for the start
  12506. and conclusion and store them in the $\itm{info}$ field of the
  12507. function definition.)
  12508. \section{Register Allocation}
  12509. \label{sec:register-allocation-r4}
  12510. \subsection{Liveness Analysis}
  12511. \label{sec:liveness-analysis-r4}
  12512. \index{subject}{liveness analysis}
  12513. %% The rest of the passes need only minor modifications to handle the new
  12514. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  12515. %% \code{leaq}.
  12516. The \code{IndirectCallq} instruction should be treated like
  12517. \code{Callq} regarding its written locations $W$, in that they should
  12518. include all the caller-saved registers. Recall that the reason for
  12519. that is to force call-live variables to be assigned to callee-saved
  12520. registers or to be spilled to the stack.
  12521. Regarding the set of read locations $R$ the arity field of
  12522. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  12523. argument-passing registers should be considered as read by those
  12524. instructions.
  12525. \subsection{Build Interference Graph}
  12526. \label{sec:build-interference-r4}
  12527. With the addition of function definitions, we compute an interference
  12528. graph for each function (not just one for the whole program).
  12529. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  12530. spill vector-typed variables that are live during a call to the
  12531. \code{collect}. With the addition of functions to our language, we
  12532. need to revisit this issue. Many functions perform allocation and
  12533. therefore have calls to the collector inside of them. Thus, we should
  12534. not only spill a vector-typed variable when it is live during a call
  12535. to \code{collect}, but we should spill the variable if it is live
  12536. during any function call. Thus, in the \code{build\_interference} pass,
  12537. we recommend adding interference edges between call-live vector-typed
  12538. variables and the callee-saved registers (in addition to the usual
  12539. addition of edges between call-live variables and the caller-saved
  12540. registers).
  12541. \subsection{Allocate Registers}
  12542. The primary change to the \code{allocate\_registers} pass is adding an
  12543. auxiliary function for handling definitions (the \Def{} non-terminal
  12544. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  12545. logic is the same as described in
  12546. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  12547. allocation is performed many times, once for each function definition,
  12548. instead of just once for the whole program.
  12549. \section{Patch Instructions}
  12550. In \code{patch\_instructions}, you should deal with the x86
  12551. idiosyncrasy that the destination argument of \code{leaq} must be a
  12552. register. Additionally, you should ensure that the argument of
  12553. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  12554. code generation more convenient, because we trample many registers
  12555. before the tail call (as explained in the next section).
  12556. \section{Print x86}
  12557. For the \code{print\_x86} pass, the cases for \code{FunRef} and
  12558. \code{IndirectCallq} are straightforward: output their concrete
  12559. syntax.
  12560. \begin{lstlisting}
  12561. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  12562. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  12563. \end{lstlisting}
  12564. The \code{TailJmp} node requires a bit work. A straightforward
  12565. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  12566. before the jump we need to pop the current frame. This sequence of
  12567. instructions is the same as the code for the conclusion of a function,
  12568. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  12569. Regarding function definitions, you will need to generate a prelude
  12570. and conclusion for each one. This code is similar to the prelude and
  12571. conclusion that you generated for the \code{main} function in
  12572. Chapter~\ref{ch:Lvec}. To review, the prelude of every function
  12573. should carry out the following steps.
  12574. \begin{enumerate}
  12575. \item Start with \code{.global} and \code{.align} directives followed
  12576. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  12577. example.)
  12578. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  12579. pointer.
  12580. \item Push to the stack all of the callee-saved registers that were
  12581. used for register allocation.
  12582. \item Move the stack pointer \code{rsp} down by the size of the stack
  12583. frame for this function, which depends on the number of regular
  12584. spills. (Aligned to 16 bytes.)
  12585. \item Move the root stack pointer \code{r15} up by the size of the
  12586. root-stack frame for this function, which depends on the number of
  12587. spilled vectors. \label{root-stack-init}
  12588. \item Initialize to zero all of the entries in the root-stack frame.
  12589. \item Jump to the start block.
  12590. \end{enumerate}
  12591. The prelude of the \code{main} function has one additional task: call
  12592. the \code{initialize} function to set up the garbage collector and
  12593. move the value of the global \code{rootstack\_begin} in
  12594. \code{r15}. This should happen before step \ref{root-stack-init}
  12595. above, which depends on \code{r15}.
  12596. The conclusion of every function should do the following.
  12597. \begin{enumerate}
  12598. \item Move the stack pointer back up by the size of the stack frame
  12599. for this function.
  12600. \item Restore the callee-saved registers by popping them from the
  12601. stack.
  12602. \item Move the root stack pointer back down by the size of the
  12603. root-stack frame for this function.
  12604. \item Restore \code{rbp} by popping it from the stack.
  12605. \item Return to the caller with the \code{retq} instruction.
  12606. \end{enumerate}
  12607. \begin{exercise}\normalfont
  12608. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  12609. Create 5 new programs that use functions, including examples that pass
  12610. functions and return functions from other functions, recursive
  12611. functions, functions that create vectors, and functions that make tail
  12612. calls. Test your compiler on these new programs and all of your
  12613. previously created test programs.
  12614. \end{exercise}
  12615. \begin{figure}[tbp]
  12616. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12617. \node (Rfun) at (0,2) {\large \LangFun{}};
  12618. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  12619. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  12620. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  12621. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  12622. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  12623. \node (F1-4) at (3,0) {\large \LangFunANF{}};
  12624. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  12625. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12626. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12627. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12628. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12629. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12630. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12631. \path[->,bend left=15] (Rfun) edge [above] node
  12632. {\ttfamily\footnotesize shrink} (Rfun-1);
  12633. \path[->,bend left=15] (Rfun-1) edge [above] node
  12634. {\ttfamily\footnotesize uniquify} (Rfun-2);
  12635. \path[->,bend left=15] (Rfun-2) edge [right] node
  12636. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  12637. \path[->,bend left=15] (F1-1) edge [below] node
  12638. {\ttfamily\footnotesize limit\_functions} (F1-2);
  12639. \path[->,bend right=15] (F1-2) edge [above] node
  12640. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  12641. \path[->,bend right=15] (F1-3) edge [above] node
  12642. {\ttfamily\footnotesize remove\_complex.} (F1-4);
  12643. \path[->,bend left=15] (F1-4) edge [right] node
  12644. {\ttfamily\footnotesize explicate\_control} (C3-2);
  12645. \path[->,bend right=15] (C3-2) edge [left] node
  12646. {\ttfamily\footnotesize select\_instr.} (x86-2);
  12647. \path[->,bend left=15] (x86-2) edge [left] node
  12648. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12649. \path[->,bend right=15] (x86-2-1) edge [below] node
  12650. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  12651. \path[->,bend right=15] (x86-2-2) edge [left] node
  12652. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  12653. \path[->,bend left=15] (x86-3) edge [above] node
  12654. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  12655. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  12656. \end{tikzpicture}
  12657. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  12658. \label{fig:Rfun-passes}
  12659. \end{figure}
  12660. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  12661. compiling \LangFun{} to x86.
  12662. \section{An Example Translation}
  12663. \label{sec:functions-example}
  12664. Figure~\ref{fig:add-fun} shows an example translation of a simple
  12665. function in \LangFun{} to x86. The figure also includes the results of the
  12666. \code{explicate\_control} and \code{select\_instructions} passes.
  12667. \begin{figure}[htbp]
  12668. \begin{tabular}{ll}
  12669. \begin{minipage}{0.5\textwidth}
  12670. % s3_2.rkt
  12671. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12672. (define (add [x : Integer] [y : Integer])
  12673. : Integer
  12674. (+ x y))
  12675. (add 40 2)
  12676. \end{lstlisting}
  12677. $\Downarrow$
  12678. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12679. (define (add86 [x87 : Integer]
  12680. [y88 : Integer]) : Integer
  12681. add86start:
  12682. return (+ x87 y88);
  12683. )
  12684. (define (main) : Integer ()
  12685. mainstart:
  12686. tmp89 = (fun-ref add86);
  12687. (tail-call tmp89 40 2)
  12688. )
  12689. \end{lstlisting}
  12690. \end{minipage}
  12691. &
  12692. $\Rightarrow$
  12693. \begin{minipage}{0.5\textwidth}
  12694. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12695. (define (add86) : Integer
  12696. add86start:
  12697. movq %rdi, x87
  12698. movq %rsi, y88
  12699. movq x87, %rax
  12700. addq y88, %rax
  12701. jmp add11389conclusion
  12702. )
  12703. (define (main) : Integer
  12704. mainstart:
  12705. leaq (fun-ref add86), tmp89
  12706. movq $40, %rdi
  12707. movq $2, %rsi
  12708. tail-jmp tmp89
  12709. )
  12710. \end{lstlisting}
  12711. $\Downarrow$
  12712. \end{minipage}
  12713. \end{tabular}
  12714. \begin{tabular}{ll}
  12715. \begin{minipage}{0.3\textwidth}
  12716. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12717. .globl add86
  12718. .align 16
  12719. add86:
  12720. pushq %rbp
  12721. movq %rsp, %rbp
  12722. jmp add86start
  12723. add86start:
  12724. movq %rdi, %rax
  12725. addq %rsi, %rax
  12726. jmp add86conclusion
  12727. add86conclusion:
  12728. popq %rbp
  12729. retq
  12730. \end{lstlisting}
  12731. \end{minipage}
  12732. &
  12733. \begin{minipage}{0.5\textwidth}
  12734. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12735. .globl main
  12736. .align 16
  12737. main:
  12738. pushq %rbp
  12739. movq %rsp, %rbp
  12740. movq $16384, %rdi
  12741. movq $16384, %rsi
  12742. callq initialize
  12743. movq rootstack_begin(%rip), %r15
  12744. jmp mainstart
  12745. mainstart:
  12746. leaq add86(%rip), %rcx
  12747. movq $40, %rdi
  12748. movq $2, %rsi
  12749. movq %rcx, %rax
  12750. popq %rbp
  12751. jmp *%rax
  12752. mainconclusion:
  12753. popq %rbp
  12754. retq
  12755. \end{lstlisting}
  12756. \end{minipage}
  12757. \end{tabular}
  12758. \caption{Example compilation of a simple function to x86.}
  12759. \label{fig:add-fun}
  12760. \end{figure}
  12761. % Challenge idea: inlining! (simple version)
  12762. % Further Reading
  12763. \fi % racketEd
  12764. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12765. \chapter{Lexically Scoped Functions}
  12766. \label{ch:Rlam}
  12767. \index{subject}{lambda}
  12768. \index{subject}{lexical scoping}
  12769. \if\edition\racketEd
  12770. This chapter studies lexically scoped functions as they appear in
  12771. functional languages such as Racket. By lexical scoping we mean that a
  12772. function's body may refer to variables whose binding site is outside
  12773. of the function, in an enclosing scope.
  12774. %
  12775. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  12776. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  12777. \key{lambda} form. The body of the \key{lambda}, refers to three
  12778. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  12779. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  12780. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  12781. parameter of function \code{f}. The \key{lambda} is returned from the
  12782. function \code{f}. The main expression of the program includes two
  12783. calls to \code{f} with different arguments for \code{x}, first
  12784. \code{5} then \code{3}. The functions returned from \code{f} are bound
  12785. to variables \code{g} and \code{h}. Even though these two functions
  12786. were created by the same \code{lambda}, they are really different
  12787. functions because they use different values for \code{x}. Applying
  12788. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  12789. \code{15} produces \code{22}. The result of this program is \code{42}.
  12790. \begin{figure}[btp]
  12791. % s4_6.rkt
  12792. \begin{lstlisting}
  12793. (define (f [x : Integer]) : (Integer -> Integer)
  12794. (let ([y 4])
  12795. (lambda: ([z : Integer]) : Integer
  12796. (+ x (+ y z)))))
  12797. (let ([g (f 5)])
  12798. (let ([h (f 3)])
  12799. (+ (g 11) (h 15))))
  12800. \end{lstlisting}
  12801. \caption{Example of a lexically scoped function.}
  12802. \label{fig:lexical-scoping}
  12803. \end{figure}
  12804. The approach that we take for implementing lexically scoped
  12805. functions is to compile them into top-level function definitions,
  12806. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  12807. provide special treatment for variable occurrences such as \code{x}
  12808. and \code{y} in the body of the \code{lambda} of
  12809. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  12810. refer to variables defined outside of it. To identify such variable
  12811. occurrences, we review the standard notion of free variable.
  12812. \begin{definition}
  12813. A variable is \emph{free in expression} $e$ if the variable occurs
  12814. inside $e$ but does not have an enclosing binding in $e$.\index{subject}{free
  12815. variable}
  12816. \end{definition}
  12817. For example, in the expression \code{(+ x (+ y z))} the variables
  12818. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  12819. only \code{x} and \code{y} are free in the following expression
  12820. because \code{z} is bound by the \code{lambda}.
  12821. \begin{lstlisting}
  12822. (lambda: ([z : Integer]) : Integer
  12823. (+ x (+ y z)))
  12824. \end{lstlisting}
  12825. So the free variables of a \code{lambda} are the ones that will need
  12826. special treatment. We need to arrange for some way to transport, at
  12827. runtime, the values of those variables from the point where the
  12828. \code{lambda} was created to the point where the \code{lambda} is
  12829. applied. An efficient solution to the problem, due to
  12830. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  12831. free variables together with the function pointer for the lambda's
  12832. code, an arrangement called a \emph{flat closure} (which we shorten to
  12833. just ``closure''). \index{subject}{closure}\index{subject}{flat closure} Fortunately,
  12834. we have all the ingredients to make closures, Chapter~\ref{ch:Lvec}
  12835. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  12836. pointers. The function pointer resides at index $0$ and the
  12837. values for the free variables will fill in the rest of the vector.
  12838. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  12839. how closures work. It's a three-step dance. The program first calls
  12840. function \code{f}, which creates a closure for the \code{lambda}. The
  12841. closure is a vector whose first element is a pointer to the top-level
  12842. function that we will generate for the \code{lambda}, the second
  12843. element is the value of \code{x}, which is \code{5}, and the third
  12844. element is \code{4}, the value of \code{y}. The closure does not
  12845. contain an element for \code{z} because \code{z} is not a free
  12846. variable of the \code{lambda}. Creating the closure is step 1 of the
  12847. dance. The closure is returned from \code{f} and bound to \code{g}, as
  12848. shown in Figure~\ref{fig:closures}.
  12849. %
  12850. The second call to \code{f} creates another closure, this time with
  12851. \code{3} in the second slot (for \code{x}). This closure is also
  12852. returned from \code{f} but bound to \code{h}, which is also shown in
  12853. Figure~\ref{fig:closures}.
  12854. \begin{figure}[tbp]
  12855. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  12856. \caption{Example closure representation for the \key{lambda}'s
  12857. in Figure~\ref{fig:lexical-scoping}.}
  12858. \label{fig:closures}
  12859. \end{figure}
  12860. Continuing with the example, consider the application of \code{g} to
  12861. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  12862. obtain the function pointer in the first element of the closure and
  12863. call it, passing in the closure itself and then the regular arguments,
  12864. in this case \code{11}. This technique for applying a closure is step
  12865. 2 of the dance.
  12866. %
  12867. But doesn't this \code{lambda} only take 1 argument, for parameter
  12868. \code{z}? The third and final step of the dance is generating a
  12869. top-level function for a \code{lambda}. We add an additional
  12870. parameter for the closure and we insert a \code{let} at the beginning
  12871. of the function for each free variable, to bind those variables to the
  12872. appropriate elements from the closure parameter.
  12873. %
  12874. This three-step dance is known as \emph{closure conversion}. We
  12875. discuss the details of closure conversion in
  12876. Section~\ref{sec:closure-conversion} and the code generated from the
  12877. example in Section~\ref{sec:example-lambda}. But first we define the
  12878. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  12879. \section{The \LangLam{} Language}
  12880. \label{sec:r5}
  12881. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  12882. functions and lexical scoping, is defined in
  12883. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  12884. the \key{lambda} form to the grammar for \LangFun{}, which already has
  12885. syntax for function application.
  12886. \newcommand{\LlambdaGrammarRacket}{
  12887. \begin{array}{lcl}
  12888. \Exp &::=& \LP \key{procedure-arity}~\Exp\RP \\
  12889. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp}
  12890. \end{array}
  12891. }
  12892. \newcommand{\LlambdaASTRacket}{
  12893. \begin{array}{lcl}
  12894. \itm{op} &::=& \code{procedure-arity} \\
  12895. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}
  12896. \end{array}
  12897. }
  12898. \begin{figure}[tp]
  12899. \centering
  12900. \fbox{
  12901. \begin{minipage}{0.96\textwidth}
  12902. \small
  12903. \[
  12904. \begin{array}{l}
  12905. \gray{\LintGrammarRacket{}} \\ \hline
  12906. \gray{\LvarGrammarRacket{}} \\ \hline
  12907. \gray{\LifGrammarRacket{}} \\ \hline
  12908. \gray{\LwhileGrammarRacket} \\ \hline
  12909. \gray{\LtupGrammarRacket} \\ \hline
  12910. \gray{\LfunGrammarRacket} \\ \hline
  12911. \LlambdaGrammarRacket \\
  12912. \begin{array}{lcl}
  12913. %% \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  12914. %% \MID (\key{Vector}\;\Type\ldots) \MID \key{Void}
  12915. %% \MID (\Type\ldots \; \key{->}\; \Type)} \\
  12916. %% \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  12917. %% \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  12918. %% &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  12919. %% &\MID& \gray{\key{\#t} \MID \key{\#f}
  12920. %% \MID (\key{and}\;\Exp\;\Exp)
  12921. %% \MID (\key{or}\;\Exp\;\Exp)
  12922. %% \MID (\key{not}\;\Exp) } \\
  12923. %% &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  12924. %% &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  12925. %% (\key{vector-ref}\;\Exp\;\Int)} \\
  12926. %% &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  12927. %% \MID (\Exp \; \Exp\ldots) } \\
  12928. %% &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  12929. %% &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  12930. %% \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  12931. \LangLamM{} &::=& \Def\ldots \; \Exp
  12932. \end{array}
  12933. \end{array}
  12934. \]
  12935. \end{minipage}
  12936. }
  12937. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  12938. with \key{lambda}.}
  12939. \label{fig:Rlam-concrete-syntax}
  12940. \end{figure}
  12941. \begin{figure}[tp]
  12942. \centering
  12943. \fbox{
  12944. \begin{minipage}{0.96\textwidth}
  12945. \small
  12946. \[
  12947. \begin{array}{l}
  12948. \gray{\LintOpAST} \\ \hline
  12949. \gray{\LvarAST{}} \\ \hline
  12950. \gray{\LifAST{}} \\ \hline
  12951. \gray{\LwhileAST{}} \\ \hline
  12952. \gray{\LtupASTRacket{}} \\ \hline
  12953. \gray{\LfunASTRacket} \\ \hline
  12954. \LlambdaASTRacket \\
  12955. \begin{array}{lcl}
  12956. %% \itm{op} &::=& \ldots \MID \code{procedure-arity} \\
  12957. %% \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  12958. %% &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  12959. %% &\MID& \gray{ \BOOL{\itm{bool}}
  12960. %% \MID \IF{\Exp}{\Exp}{\Exp} } \\
  12961. %% &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  12962. %% \MID \APPLY{\Exp}{\Exp\ldots} }\\
  12963. %% &\MID& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  12964. %% \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  12965. \LangLamM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12966. \end{array}
  12967. \end{array}
  12968. \]
  12969. \end{minipage}
  12970. }
  12971. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  12972. \label{fig:Rlam-syntax}
  12973. \end{figure}
  12974. \index{subject}{interpreter}
  12975. \label{sec:interp-Rlambda}
  12976. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  12977. \LangLam{}. The case for \key{lambda} saves the current environment
  12978. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  12979. the environment from the \key{lambda}, the \code{lam-env}, when
  12980. interpreting the body of the \key{lambda}. The \code{lam-env}
  12981. environment is extended with the mapping of parameters to argument
  12982. values.
  12983. \begin{figure}[tbp]
  12984. \begin{lstlisting}
  12985. (define interp-Rlambda_class
  12986. (class interp-Rfun_class
  12987. (super-new)
  12988. (define/override (interp-op op)
  12989. (match op
  12990. ['procedure-arity
  12991. (lambda (v)
  12992. (match v
  12993. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  12994. [else (error 'interp-op "expected a function, not ~a" v)]))]
  12995. [else (super interp-op op)]))
  12996. (define/override ((interp-exp env) e)
  12997. (define recur (interp-exp env))
  12998. (match e
  12999. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  13000. `(function ,xs ,body ,env)]
  13001. [else ((super interp-exp env) e)]))
  13002. ))
  13003. (define (interp-Rlambda p)
  13004. (send (new interp-Rlambda_class) interp-program p))
  13005. \end{lstlisting}
  13006. \caption{Interpreter for \LangLam{}.}
  13007. \label{fig:interp-Rlambda}
  13008. \end{figure}
  13009. \label{sec:type-check-r5}
  13010. \index{subject}{type checking}
  13011. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  13012. \key{lambda} form. The body of the \key{lambda} is checked in an
  13013. environment that includes the current environment (because it is
  13014. lexically scoped) and also includes the \key{lambda}'s parameters. We
  13015. require the body's type to match the declared return type.
  13016. \begin{figure}[tbp]
  13017. \begin{lstlisting}
  13018. (define (type-check-Rlambda env)
  13019. (lambda (e)
  13020. (match e
  13021. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  13022. (define-values (new-body bodyT)
  13023. ((type-check-exp (append (map cons xs Ts) env)) body))
  13024. (define ty `(,@Ts -> ,rT))
  13025. (cond
  13026. [(equal? rT bodyT)
  13027. (values (HasType (Lambda params rT new-body) ty) ty)]
  13028. [else
  13029. (error "mismatch in return type" bodyT rT)])]
  13030. ...
  13031. )))
  13032. \end{lstlisting}
  13033. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  13034. \label{fig:type-check-Rlambda}
  13035. \end{figure}
  13036. \section{Assignment and Lexically Scoped Functions}
  13037. \label{sec:assignment-scoping}
  13038. [UNDER CONSTRUCTION: This section was just moved into this location
  13039. and may need to be updated. -Jeremy]
  13040. The combination of lexically-scoped functions and assignment
  13041. (i.e. \code{set!}) raises a challenge with our approach to
  13042. implementing lexically-scoped functions. Consider the following
  13043. example in which function \code{f} has a free variable \code{x} that
  13044. is changed after \code{f} is created but before the call to \code{f}.
  13045. % loop_test_11.rkt
  13046. \begin{lstlisting}
  13047. (let ([x 0])
  13048. (let ([y 0])
  13049. (let ([z 20])
  13050. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  13051. (begin
  13052. (set! x 10)
  13053. (set! y 12)
  13054. (f y))))))
  13055. \end{lstlisting}
  13056. The correct output for this example is \code{42} because the call to
  13057. \code{f} is required to use the current value of \code{x} (which is
  13058. \code{10}). Unfortunately, the closure conversion pass
  13059. (Section~\ref{sec:closure-conversion}) generates code for the
  13060. \code{lambda} that copies the old value of \code{x} into a
  13061. closure. Thus, if we naively add support for assignment to our current
  13062. compiler, the output of this program would be \code{32}.
  13063. A first attempt at solving this problem would be to save a pointer to
  13064. \code{x} in the closure and change the occurrences of \code{x} inside
  13065. the lambda to dereference the pointer. Of course, this would require
  13066. assigning \code{x} to the stack and not to a register. However, the
  13067. problem goes a bit deeper. Consider the following example in which we
  13068. create a counter abstraction by creating a pair of functions that
  13069. share the free variable \code{x}.
  13070. % similar to loop_test_10.rkt
  13071. \begin{lstlisting}
  13072. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  13073. (vector
  13074. (lambda: () : Integer x)
  13075. (lambda: () : Void (set! x (+ 1 x)))))
  13076. (let ([counter (f 0)])
  13077. (let ([get (vector-ref counter 0)])
  13078. (let ([inc (vector-ref counter 1)])
  13079. (begin
  13080. (inc)
  13081. (get)))))
  13082. \end{lstlisting}
  13083. In this example, the lifetime of \code{x} extends beyond the lifetime
  13084. of the call to \code{f}. Thus, if we were to store \code{x} on the
  13085. stack frame for the call to \code{f}, it would be gone by the time we
  13086. call \code{inc} and \code{get}, leaving us with dangling pointers for
  13087. \code{x}. This example demonstrates that when a variable occurs free
  13088. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  13089. value of the variable needs to live on the heap. The verb ``box'' is
  13090. often used for allocating a single value on the heap, producing a
  13091. pointer, and ``unbox'' for dereferencing the pointer.
  13092. We recommend solving these problems by ``boxing'' the local variables
  13093. that are in the intersection of 1) variables that appear on the
  13094. left-hand-side of a \code{set!} and 2) variables that occur free
  13095. inside a \code{lambda}. We shall introduce a new pass named
  13096. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  13097. perform this translation. But before diving into the compiler passes,
  13098. we one more problem to discuss.
  13099. \section{Reveal Functions and the $F_2$ language}
  13100. \label{sec:reveal-functions-r5}
  13101. To support the \code{procedure-arity} operator we need to communicate
  13102. the arity of a function to the point of closure creation. We can
  13103. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  13104. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  13105. output of this pass is the language $F_2$, whose syntax is defined in
  13106. Figure~\ref{fig:f2-syntax}.
  13107. \begin{figure}[tp]
  13108. \centering
  13109. \fbox{
  13110. \begin{minipage}{0.96\textwidth}
  13111. \[
  13112. \begin{array}{lcl}
  13113. \Exp &::=& \ldots \MID \FUNREFARITY{\Var}{\Int}\\
  13114. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13115. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  13116. \end{array}
  13117. \]
  13118. \end{minipage}
  13119. }
  13120. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  13121. (Figure~\ref{fig:Rlam-syntax}).}
  13122. \label{fig:f2-syntax}
  13123. \end{figure}
  13124. \section{Convert Assignments}
  13125. \label{sec:convert-assignments}
  13126. [UNDER CONSTRUCTION: This section was just moved into this location
  13127. and may need to be updated. -Jeremy]
  13128. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  13129. the combination of assignments and lexically-scoped functions requires
  13130. that we box those variables that are both assigned-to and that appear
  13131. free inside a \code{lambda}. The purpose of the
  13132. \code{convert-assignments} pass is to carry out that transformation.
  13133. We recommend placing this pass after \code{uniquify} but before
  13134. \code{reveal\_functions}.
  13135. Consider again the first example from
  13136. Section~\ref{sec:assignment-scoping}:
  13137. \begin{lstlisting}
  13138. (let ([x 0])
  13139. (let ([y 0])
  13140. (let ([z 20])
  13141. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  13142. (begin
  13143. (set! x 10)
  13144. (set! y 12)
  13145. (f y))))))
  13146. \end{lstlisting}
  13147. The variables \code{x} and \code{y} are assigned-to. The variables
  13148. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  13149. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  13150. The boxing of \code{x} consists of three transformations: initialize
  13151. \code{x} with a vector, replace reads from \code{x} with
  13152. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  13153. \code{vector-set!}. The output of \code{convert-assignments} for this
  13154. example is as follows.
  13155. \begin{lstlisting}
  13156. (define (main) : Integer
  13157. (let ([x0 (vector 0)])
  13158. (let ([y1 0])
  13159. (let ([z2 20])
  13160. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  13161. (+ a3 (+ (vector-ref x0 0) z2)))])
  13162. (begin
  13163. (vector-set! x0 0 10)
  13164. (set! y1 12)
  13165. (f4 y1)))))))
  13166. \end{lstlisting}
  13167. \paragraph{Assigned \& Free}
  13168. We recommend defining an auxiliary function named
  13169. \code{assigned\&free} that takes an expression and simultaneously
  13170. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  13171. that occur free within lambda's, and 3) a new version of the
  13172. expression that records which bound variables occurred in the
  13173. intersection of $A$ and $F$. You can use the struct
  13174. \code{AssignedFree} to do this. Consider the case for
  13175. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  13176. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  13177. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  13178. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  13179. \begin{lstlisting}
  13180. (Let |$x$| |$rhs$| |$body$|)
  13181. |$\Rightarrow$|
  13182. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  13183. \end{lstlisting}
  13184. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  13185. The set of assigned variables for this \code{Let} is
  13186. $A_r \cup (A_b - \{x\})$
  13187. and the set of variables free in lambda's is
  13188. $F_r \cup (F_b - \{x\})$.
  13189. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  13190. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  13191. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  13192. and $F_r$.
  13193. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  13194. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  13195. recursively processing \itm{body}. Wrap each of parameter that occurs
  13196. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  13197. Let $P$ be the set of parameter names in \itm{params}. The result is
  13198. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  13199. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  13200. variables of an expression (see Chapter~\ref{ch:Rlam}).
  13201. \paragraph{Convert Assignments}
  13202. Next we discuss the \code{convert-assignment} pass with its auxiliary
  13203. functions for expressions and definitions. The function for
  13204. expressions, \code{cnvt-assign-exp}, should take an expression and a
  13205. set of assigned-and-free variables (obtained from the result of
  13206. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  13207. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  13208. \code{vector-ref}.
  13209. \begin{lstlisting}
  13210. (Var |$x$|)
  13211. |$\Rightarrow$|
  13212. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  13213. \end{lstlisting}
  13214. %
  13215. In the case for $\LET{\LP\code{AssignedFree}\,
  13216. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  13217. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  13218. \itm{body'} but with $x$ added to the set of assigned-and-free
  13219. variables. Translate the let-expression as follows to bind $x$ to a
  13220. boxed value.
  13221. \begin{lstlisting}
  13222. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  13223. |$\Rightarrow$|
  13224. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  13225. \end{lstlisting}
  13226. %
  13227. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  13228. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  13229. variables, translate the \code{set!} into a \code{vector-set!}
  13230. as follows.
  13231. \begin{lstlisting}
  13232. (SetBang |$x$| |$\itm{rhs}$|)
  13233. |$\Rightarrow$|
  13234. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  13235. \end{lstlisting}
  13236. %
  13237. The case for \code{Lambda} is non-trivial, but it is similar to the
  13238. case for function definitions, which we discuss next.
  13239. The auxiliary function for definitions, \code{cnvt-assign-def},
  13240. applies assignment conversion to function definitions.
  13241. We translate a function definition as follows.
  13242. \begin{lstlisting}
  13243. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  13244. |$\Rightarrow$|
  13245. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  13246. \end{lstlisting}
  13247. So it remains to explain \itm{params'} and $\itm{body}_4$.
  13248. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  13249. \code{assigned\&free} on $\itm{body_1}$.
  13250. Let $P$ be the parameter names in \itm{params}.
  13251. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  13252. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  13253. as the set of assigned-and-free variables.
  13254. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  13255. in a sequence of let-expressions that box the parameters
  13256. that are in $A_b \cap F_b$.
  13257. %
  13258. Regarding \itm{params'}, change the names of the parameters that are
  13259. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  13260. variables can retain the original names). Recall the second example in
  13261. Section~\ref{sec:assignment-scoping} involving a counter
  13262. abstraction. The following is the output of assignment version for
  13263. function \code{f}.
  13264. \begin{lstlisting}
  13265. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  13266. (vector
  13267. (lambda: () : Integer x1)
  13268. (lambda: () : Void (set! x1 (+ 1 x1)))))
  13269. |$\Rightarrow$|
  13270. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  13271. (let ([x1 (vector param_x1)])
  13272. (vector (lambda: () : Integer (vector-ref x1 0))
  13273. (lambda: () : Void
  13274. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  13275. \end{lstlisting}
  13276. \section{Closure Conversion}
  13277. \label{sec:closure-conversion}
  13278. \index{subject}{closure conversion}
  13279. The compiling of lexically-scoped functions into top-level function
  13280. definitions is accomplished in the pass \code{convert-to-closures}
  13281. that comes after \code{reveal\_functions} and before
  13282. \code{limit-functions}.
  13283. As usual, we implement the pass as a recursive function over the
  13284. AST. All of the action is in the cases for \key{Lambda} and
  13285. \key{Apply}. We transform a \key{Lambda} expression into an expression
  13286. that creates a closure, that is, a vector whose first element is a
  13287. function pointer and the rest of the elements are the free variables
  13288. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  13289. using \code{vector} so that we can distinguish closures from vectors
  13290. in Section~\ref{sec:optimize-closures} and to record the arity. In
  13291. the generated code below, the \itm{name} is a unique symbol generated
  13292. to identify the function and the \itm{arity} is the number of
  13293. parameters (the length of \itm{ps}).
  13294. \begin{lstlisting}
  13295. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  13296. |$\Rightarrow$|
  13297. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  13298. \end{lstlisting}
  13299. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  13300. create a top-level function definition for each \key{Lambda}, as
  13301. shown below.\\
  13302. \begin{minipage}{0.8\textwidth}
  13303. \begin{lstlisting}
  13304. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  13305. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  13306. ...
  13307. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  13308. |\itm{body'}|)...))
  13309. \end{lstlisting}
  13310. \end{minipage}\\
  13311. The \code{clos} parameter refers to the closure. Translate the type
  13312. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  13313. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  13314. $\itm{fvts}$ are the types of the free variables in the lambda and the
  13315. underscore \code{\_} is a dummy type that we use because it is rather
  13316. difficult to give a type to the function in the closure's
  13317. type.\footnote{To give an accurate type to a closure, we would need to
  13318. add existential types to the type checker~\citep{Minamide:1996ys}.}
  13319. The dummy type is considered to be equal to any other type during type
  13320. checking. The sequence of \key{Let} forms bind the free variables to
  13321. their values obtained from the closure.
  13322. Closure conversion turns functions into vectors, so the type
  13323. annotations in the program must also be translated. We recommend
  13324. defining a auxiliary recursive function for this purpose. Function
  13325. types should be translated as follows.
  13326. \begin{lstlisting}
  13327. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  13328. |$\Rightarrow$|
  13329. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  13330. \end{lstlisting}
  13331. The above type says that the first thing in the vector is a function
  13332. pointer. The first parameter of the function pointer is a vector (a
  13333. closure) and the rest of the parameters are the ones from the original
  13334. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  13335. the closure omits the types of the free variables because 1) those
  13336. types are not available in this context and 2) we do not need them in
  13337. the code that is generated for function application.
  13338. We transform function application into code that retrieves the
  13339. function pointer from the closure and then calls the function, passing
  13340. in the closure as the first argument. We bind $e'$ to a temporary
  13341. variable to avoid code duplication.
  13342. \begin{lstlisting}
  13343. (Apply |$e$| |\itm{es}|)
  13344. |$\Rightarrow$|
  13345. (Let |\itm{tmp}| |$e'$|
  13346. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  13347. \end{lstlisting}
  13348. There is also the question of what to do with references top-level
  13349. function definitions. To maintain a uniform translation of function
  13350. application, we turn function references into closures.
  13351. \begin{tabular}{lll}
  13352. \begin{minipage}{0.3\textwidth}
  13353. \begin{lstlisting}
  13354. (FunRefArity |$f$| |$n$|)
  13355. \end{lstlisting}
  13356. \end{minipage}
  13357. &
  13358. $\Rightarrow$
  13359. &
  13360. \begin{minipage}{0.5\textwidth}
  13361. \begin{lstlisting}
  13362. (Closure |$n$| (FunRef |$f$|) '())
  13363. \end{lstlisting}
  13364. \end{minipage}
  13365. \end{tabular} \\
  13366. %
  13367. The top-level function definitions need to be updated as well to take
  13368. an extra closure parameter.
  13369. \section{An Example Translation}
  13370. \label{sec:example-lambda}
  13371. Figure~\ref{fig:lexical-functions-example} shows the result of
  13372. \code{reveal\_functions} and \code{convert-to-closures} for the example
  13373. program demonstrating lexical scoping that we discussed at the
  13374. beginning of this chapter.
  13375. \begin{figure}[tbp]
  13376. \begin{minipage}{0.8\textwidth}
  13377. % tests/lambda_test_6.rkt
  13378. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13379. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  13380. (let ([y8 4])
  13381. (lambda: ([z9 : Integer]) : Integer
  13382. (+ x7 (+ y8 z9)))))
  13383. (define (main) : Integer
  13384. (let ([g0 ((fun-ref-arity f6 1) 5)])
  13385. (let ([h1 ((fun-ref-arity f6 1) 3)])
  13386. (+ (g0 11) (h1 15)))))
  13387. \end{lstlisting}
  13388. $\Rightarrow$
  13389. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13390. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  13391. (let ([y8 4])
  13392. (closure 1 (list (fun-ref lambda2) x7 y8))))
  13393. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  13394. (let ([x7 (vector-ref fvs3 1)])
  13395. (let ([y8 (vector-ref fvs3 2)])
  13396. (+ x7 (+ y8 z9)))))
  13397. (define (main) : Integer
  13398. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  13399. ((vector-ref clos5 0) clos5 5))])
  13400. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  13401. ((vector-ref clos6 0) clos6 3))])
  13402. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  13403. \end{lstlisting}
  13404. \end{minipage}
  13405. \caption{Example of closure conversion.}
  13406. \label{fig:lexical-functions-example}
  13407. \end{figure}
  13408. \begin{exercise}\normalfont
  13409. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  13410. Create 5 new programs that use \key{lambda} functions and make use of
  13411. lexical scoping. Test your compiler on these new programs and all of
  13412. your previously created test programs.
  13413. \end{exercise}
  13414. \section{Expose Allocation}
  13415. \label{sec:expose-allocation-r5}
  13416. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  13417. that allocates and initializes a vector, similar to the translation of
  13418. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  13419. The only difference is replacing the use of
  13420. \ALLOC{\itm{len}}{\itm{type}} with
  13421. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  13422. \section{Explicate Control and \LangCLam{}}
  13423. \label{sec:explicate-r5}
  13424. The output language of \code{explicate\_control} is \LangCLam{} whose
  13425. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  13426. difference with respect to \LangCFun{} is the addition of the
  13427. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  13428. of \code{AllocateClosure} in the \code{explicate\_control} pass is
  13429. similar to the handling of other expressions such as primitive
  13430. operators.
  13431. \begin{figure}[tp]
  13432. \fbox{
  13433. \begin{minipage}{0.96\textwidth}
  13434. \small
  13435. \[
  13436. \begin{array}{lcl}
  13437. \Exp &::= & \ldots
  13438. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  13439. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  13440. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  13441. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  13442. \MID \GOTO{\itm{label}} } \\
  13443. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  13444. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  13445. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  13446. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  13447. \end{array}
  13448. \]
  13449. \end{minipage}
  13450. }
  13451. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  13452. \label{fig:c4-syntax}
  13453. \end{figure}
  13454. \section{Select Instructions}
  13455. \label{sec:select-instructions-Rlambda}
  13456. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  13457. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  13458. (Section~\ref{sec:select-instructions-gc}). The only difference is
  13459. that you should place the \itm{arity} in the tag that is stored at
  13460. position $0$ of the vector. Recall that in
  13461. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  13462. was not used. We store the arity in the $5$ bits starting at position
  13463. $58$.
  13464. Compile the \code{procedure-arity} operator into a sequence of
  13465. instructions that access the tag from position $0$ of the vector and
  13466. extract the $5$-bits starting at position $58$ from the tag.
  13467. \begin{figure}[p]
  13468. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13469. \node (Rfun) at (0,2) {\large \LangLam{}};
  13470. \node (Rfun-2) at (3,2) {\large \LangLam{}};
  13471. \node (Rfun-3) at (6,2) {\large \LangLam{}};
  13472. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  13473. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  13474. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13475. \node (F1-3) at (6,0) {\large \LangFunRef{}};
  13476. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  13477. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  13478. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13479. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13480. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13481. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13482. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13483. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13484. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13485. \path[->,bend left=15] (Rfun) edge [above] node
  13486. {\ttfamily\footnotesize shrink} (Rfun-2);
  13487. \path[->,bend left=15] (Rfun-2) edge [above] node
  13488. {\ttfamily\footnotesize uniquify} (Rfun-3);
  13489. \path[->,bend left=15] (Rfun-3) edge [above] node
  13490. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  13491. \path[->,bend left=15] (F1-0) edge [right] node
  13492. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  13493. \path[->,bend left=15] (F1-1) edge [below] node
  13494. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  13495. \path[->,bend right=15] (F1-2) edge [above] node
  13496. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  13497. \path[->,bend right=15] (F1-3) edge [above] node
  13498. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  13499. \path[->,bend right=15] (F1-4) edge [above] node
  13500. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  13501. \path[->,bend right=15] (F1-5) edge [right] node
  13502. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13503. \path[->,bend left=15] (C3-2) edge [left] node
  13504. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13505. \path[->,bend right=15] (x86-2) edge [left] node
  13506. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13507. \path[->,bend right=15] (x86-2-1) edge [below] node
  13508. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13509. \path[->,bend right=15] (x86-2-2) edge [left] node
  13510. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13511. \path[->,bend left=15] (x86-3) edge [above] node
  13512. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13513. \path[->,bend left=15] (x86-4) edge [right] node
  13514. {\ttfamily\footnotesize print\_x86} (x86-5);
  13515. \end{tikzpicture}
  13516. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  13517. functions.}
  13518. \label{fig:Rlambda-passes}
  13519. \end{figure}
  13520. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  13521. for the compilation of \LangLam{}.
  13522. \clearpage
  13523. \section{Challenge: Optimize Closures}
  13524. \label{sec:optimize-closures}
  13525. In this chapter we compiled lexically-scoped functions into a
  13526. relatively efficient representation: flat closures. However, even this
  13527. representation comes with some overhead. For example, consider the
  13528. following program with a function \code{tail\_sum} that does not have
  13529. any free variables and where all the uses of \code{tail\_sum} are in
  13530. applications where we know that only \code{tail\_sum} is being applied
  13531. (and not any other functions).
  13532. \begin{center}
  13533. \begin{minipage}{0.95\textwidth}
  13534. \begin{lstlisting}
  13535. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  13536. (if (eq? n 0)
  13537. r
  13538. (tail_sum (- n 1) (+ n r))))
  13539. (+ (tail_sum 5 0) 27)
  13540. \end{lstlisting}
  13541. \end{minipage}
  13542. \end{center}
  13543. As described in this chapter, we uniformly apply closure conversion to
  13544. all functions, obtaining the following output for this program.
  13545. \begin{center}
  13546. \begin{minipage}{0.95\textwidth}
  13547. \begin{lstlisting}
  13548. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  13549. (if (eq? n2 0)
  13550. r3
  13551. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  13552. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  13553. (define (main) : Integer
  13554. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  13555. ((vector-ref clos6 0) clos6 5 0)) 27))
  13556. \end{lstlisting}
  13557. \end{minipage}
  13558. \end{center}
  13559. In the previous Chapter, there would be no allocation in the program
  13560. and the calls to \code{tail\_sum} would be direct calls. In contrast,
  13561. the above program allocates memory for each \code{closure} and the
  13562. calls to \code{tail\_sum} are indirect. These two differences incur
  13563. considerable overhead in a program such as this one, where the
  13564. allocations and indirect calls occur inside a tight loop.
  13565. One might think that this problem is trivial to solve: can't we just
  13566. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  13567. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  13568. e'_n$)} instead of treating it like a call to a closure? We would
  13569. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  13570. %
  13571. However, this problem is not so trivial because a global function may
  13572. ``escape'' and become involved in applications that also involve
  13573. closures. Consider the following example in which the application
  13574. \code{(f 41)} needs to be compiled into a closure application, because
  13575. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  13576. function might also get bound to \code{f}.
  13577. \begin{lstlisting}
  13578. (define (add1 [x : Integer]) : Integer
  13579. (+ x 1))
  13580. (let ([y (read)])
  13581. (let ([f (if (eq? (read) 0)
  13582. add1
  13583. (lambda: ([x : Integer]) : Integer (- x y)))])
  13584. (f 41)))
  13585. \end{lstlisting}
  13586. If a global function name is used in any way other than as the
  13587. operator in a direct call, then we say that the function
  13588. \emph{escapes}. If a global function does not escape, then we do not
  13589. need to perform closure conversion on the function.
  13590. \begin{exercise}\normalfont
  13591. Implement an auxiliary function for detecting which global
  13592. functions escape. Using that function, implement an improved version
  13593. of closure conversion that does not apply closure conversion to
  13594. global functions that do not escape but instead compiles them as
  13595. regular functions. Create several new test cases that check whether
  13596. you properly detect whether global functions escape or not.
  13597. \end{exercise}
  13598. So far we have reduced the overhead of calling global functions, but
  13599. it would also be nice to reduce the overhead of calling a
  13600. \code{lambda} when we can determine at compile time which
  13601. \code{lambda} will be called. We refer to such calls as \emph{known
  13602. calls}. Consider the following example in which a \code{lambda} is
  13603. bound to \code{f} and then applied.
  13604. \begin{lstlisting}
  13605. (let ([y (read)])
  13606. (let ([f (lambda: ([x : Integer]) : Integer
  13607. (+ x y))])
  13608. (f 21)))
  13609. \end{lstlisting}
  13610. Closure conversion compiles \code{(f 21)} into an indirect call:
  13611. \begin{lstlisting}
  13612. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  13613. (let ([y2 (vector-ref fvs6 1)])
  13614. (+ x3 y2)))
  13615. (define (main) : Integer
  13616. (let ([y2 (read)])
  13617. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  13618. ((vector-ref f4 0) f4 21))))
  13619. \end{lstlisting}
  13620. but we can instead compile the application \code{(f 21)} into a direct call
  13621. to \code{lambda5}:
  13622. \begin{lstlisting}
  13623. (define (main) : Integer
  13624. (let ([y2 (read)])
  13625. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  13626. ((fun-ref lambda5) f4 21))))
  13627. \end{lstlisting}
  13628. The problem of determining which lambda will be called from a
  13629. particular application is quite challenging in general and the topic
  13630. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  13631. following exercise we recommend that you compile an application to a
  13632. direct call when the operator is a variable and the variable is
  13633. \code{let}-bound to a closure. This can be accomplished by maintaining
  13634. an environment mapping \code{let}-bound variables to function names.
  13635. Extend the environment whenever you encounter a closure on the
  13636. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  13637. to the name of the global function for the closure. This pass should
  13638. come after closure conversion.
  13639. \begin{exercise}\normalfont
  13640. Implement a compiler pass, named \code{optimize-known-calls}, that
  13641. compiles known calls into direct calls. Verify that your compiler is
  13642. successful in this regard on several example programs.
  13643. \end{exercise}
  13644. These exercises only scratches the surface of optimizing of
  13645. closures. A good next step for the interested reader is to look at the
  13646. work of \citet{Keep:2012ab}.
  13647. \section{Further Reading}
  13648. The notion of lexically scoped anonymous functions predates modern
  13649. computers by about a decade. They were invented by
  13650. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  13651. foundation for logic. Anonymous functions were included in the
  13652. LISP~\citep{McCarthy:1960dz} programming language but were initially
  13653. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  13654. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  13655. compile Scheme programs. However, environments were represented as
  13656. linked lists, so variable lookup was linear in the size of the
  13657. environment. In this chapter we represent environments using flat
  13658. closures, which were invented by
  13659. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  13660. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  13661. closures, variable lookup is constant time but the time to create a
  13662. closure is proportional to the number of its free variables. Flat
  13663. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  13664. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  13665. \fi
  13666. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13667. \chapter{Dynamic Typing}
  13668. \label{ch:Rdyn}
  13669. \index{subject}{dynamic typing}
  13670. \if\edition\racketEd
  13671. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  13672. typed language that is a subset of Racket. This is in contrast to the
  13673. previous chapters, which have studied the compilation of Typed
  13674. Racket. In dynamically typed languages such as \LangDyn{}, a given
  13675. expression may produce a value of a different type each time it is
  13676. executed. Consider the following example with a conditional \code{if}
  13677. expression that may return a Boolean or an integer depending on the
  13678. input to the program.
  13679. % part of dynamic_test_25.rkt
  13680. \begin{lstlisting}
  13681. (not (if (eq? (read) 1) #f 0))
  13682. \end{lstlisting}
  13683. Languages that allow expressions to produce different kinds of values
  13684. are called \emph{polymorphic}, a word composed of the Greek roots
  13685. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  13686. are several kinds of polymorphism in programming languages, such as
  13687. subtype polymorphism and parametric
  13688. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  13689. study in this chapter does not have a special name but it is the kind
  13690. that arises in dynamically typed languages.
  13691. Another characteristic of dynamically typed languages is that
  13692. primitive operations, such as \code{not}, are often defined to operate
  13693. on many different types of values. In fact, in Racket, the \code{not}
  13694. operator produces a result for any kind of value: given \code{\#f} it
  13695. returns \code{\#t} and given anything else it returns \code{\#f}.
  13696. Furthermore, even when primitive operations restrict their inputs to
  13697. values of a certain type, this restriction is enforced at runtime
  13698. instead of during compilation. For example, the following vector
  13699. reference results in a run-time contract violation because the index
  13700. must be in integer, not a Boolean such as \code{\#t}.
  13701. \begin{lstlisting}
  13702. (vector-ref (vector 42) #t)
  13703. \end{lstlisting}
  13704. \begin{figure}[tp]
  13705. \centering
  13706. \fbox{
  13707. \begin{minipage}{0.97\textwidth}
  13708. \[
  13709. \begin{array}{rcl}
  13710. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  13711. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  13712. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  13713. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  13714. &\MID& \key{\#t} \MID \key{\#f}
  13715. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  13716. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  13717. \MID \CUNIOP{\key{not}}{\Exp} \\
  13718. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  13719. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  13720. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  13721. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  13722. &\MID& \LP\Exp \; \Exp\ldots\RP
  13723. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  13724. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  13725. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  13726. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  13727. \LangDynM{} &::=& \Def\ldots\; \Exp
  13728. \end{array}
  13729. \]
  13730. \end{minipage}
  13731. }
  13732. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  13733. \label{fig:r7-concrete-syntax}
  13734. \end{figure}
  13735. \begin{figure}[tp]
  13736. \centering
  13737. \fbox{
  13738. \begin{minipage}{0.96\textwidth}
  13739. \small
  13740. \[
  13741. \begin{array}{lcl}
  13742. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  13743. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  13744. &\MID& \BOOL{\itm{bool}}
  13745. \MID \IF{\Exp}{\Exp}{\Exp} \\
  13746. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  13747. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  13748. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  13749. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  13750. \end{array}
  13751. \]
  13752. \end{minipage}
  13753. }
  13754. \caption{The abstract syntax of \LangDyn{}.}
  13755. \label{fig:r7-syntax}
  13756. \end{figure}
  13757. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  13758. defined in Figures~\ref{fig:r7-concrete-syntax} and
  13759. \ref{fig:r7-syntax}.
  13760. %
  13761. There is no type checker for \LangDyn{} because it is not a statically
  13762. typed language (it's dynamically typed!).
  13763. The definitional interpreter for \LangDyn{} is presented in
  13764. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  13765. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  13766. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  13767. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  13768. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  13769. value} that combines an underlying value with a tag that identifies
  13770. what kind of value it is. We define the following struct
  13771. to represented tagged values.
  13772. \begin{lstlisting}
  13773. (struct Tagged (value tag) #:transparent)
  13774. \end{lstlisting}
  13775. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  13776. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  13777. but don't always capture all the information that a type does. For
  13778. example, a vector of type \code{(Vector Any Any)} is tagged with
  13779. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  13780. is tagged with \code{Procedure}.
  13781. Next consider the match case for \code{vector-ref}. The
  13782. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  13783. is used to ensure that the first argument is a vector and the second
  13784. is an integer. If they are not, a \code{trapped-error} is raised.
  13785. Recall from Section~\ref{sec:interp_Lint} that when a definition
  13786. interpreter raises a \code{trapped-error} error, the compiled code
  13787. must also signal an error by exiting with return code \code{255}. A
  13788. \code{trapped-error} is also raised if the index is not less than
  13789. length of the vector.
  13790. \begin{figure}[tbp]
  13791. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13792. (define ((interp-Rdyn-exp env) ast)
  13793. (define recur (interp-Rdyn-exp env))
  13794. (match ast
  13795. [(Var x) (lookup x env)]
  13796. [(Int n) (Tagged n 'Integer)]
  13797. [(Bool b) (Tagged b 'Boolean)]
  13798. [(Lambda xs rt body)
  13799. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  13800. [(Prim 'vector es)
  13801. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  13802. [(Prim 'vector-ref (list e1 e2))
  13803. (define vec (recur e1)) (define i (recur e2))
  13804. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  13805. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  13806. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  13807. (vector-ref (Tagged-value vec) (Tagged-value i))]
  13808. [(Prim 'vector-set! (list e1 e2 e3))
  13809. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  13810. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  13811. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  13812. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  13813. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  13814. (Tagged (void) 'Void)]
  13815. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  13816. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  13817. [(Prim 'or (list e1 e2))
  13818. (define v1 (recur e1))
  13819. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  13820. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  13821. [(Prim op (list e1))
  13822. #:when (set-member? type-predicates op)
  13823. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  13824. [(Prim op es)
  13825. (define args (map recur es))
  13826. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  13827. (unless (for/or ([expected-tags (op-tags op)])
  13828. (equal? expected-tags tags))
  13829. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  13830. (tag-value
  13831. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  13832. [(If q t f)
  13833. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  13834. [(Apply f es)
  13835. (define new-f (recur f)) (define args (map recur es))
  13836. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  13837. (match f-val
  13838. [`(function ,xs ,body ,lam-env)
  13839. (unless (eq? (length xs) (length args))
  13840. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  13841. (define new-env (append (map cons xs args) lam-env))
  13842. ((interp-Rdyn-exp new-env) body)]
  13843. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  13844. \end{lstlisting}
  13845. \caption{Interpreter for the \LangDyn{} language.}
  13846. \label{fig:interp-Rdyn}
  13847. \end{figure}
  13848. \begin{figure}[tbp]
  13849. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13850. (define (interp-op op)
  13851. (match op
  13852. ['+ fx+]
  13853. ['- fx-]
  13854. ['read read-fixnum]
  13855. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  13856. ['< (lambda (v1 v2)
  13857. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  13858. ['<= (lambda (v1 v2)
  13859. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  13860. ['> (lambda (v1 v2)
  13861. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  13862. ['>= (lambda (v1 v2)
  13863. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  13864. ['boolean? boolean?]
  13865. ['integer? fixnum?]
  13866. ['void? void?]
  13867. ['vector? vector?]
  13868. ['vector-length vector-length]
  13869. ['procedure? (match-lambda
  13870. [`(functions ,xs ,body ,env) #t] [else #f])]
  13871. [else (error 'interp-op "unknown operator" op)]))
  13872. (define (op-tags op)
  13873. (match op
  13874. ['+ '((Integer Integer))]
  13875. ['- '((Integer Integer) (Integer))]
  13876. ['read '(())]
  13877. ['not '((Boolean))]
  13878. ['< '((Integer Integer))]
  13879. ['<= '((Integer Integer))]
  13880. ['> '((Integer Integer))]
  13881. ['>= '((Integer Integer))]
  13882. ['vector-length '((Vector))]))
  13883. (define type-predicates
  13884. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  13885. (define (tag-value v)
  13886. (cond [(boolean? v) (Tagged v 'Boolean)]
  13887. [(fixnum? v) (Tagged v 'Integer)]
  13888. [(procedure? v) (Tagged v 'Procedure)]
  13889. [(vector? v) (Tagged v 'Vector)]
  13890. [(void? v) (Tagged v 'Void)]
  13891. [else (error 'tag-value "unidentified value ~a" v)]))
  13892. (define (check-tag val expected ast)
  13893. (define tag (Tagged-tag val))
  13894. (unless (eq? tag expected)
  13895. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  13896. \end{lstlisting}
  13897. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  13898. \label{fig:interp-Rdyn-aux}
  13899. \end{figure}
  13900. \clearpage
  13901. \section{Representation of Tagged Values}
  13902. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  13903. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  13904. values at the bit level. Because almost every operation in \LangDyn{}
  13905. involves manipulating tagged values, the representation must be
  13906. efficient. Recall that all of our values are 64 bits. We shall steal
  13907. the 3 right-most bits to encode the tag. We use $001$ to identify
  13908. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  13909. and $101$ for the void value. We define the following auxiliary
  13910. function for mapping types to tag codes.
  13911. \begin{align*}
  13912. \itm{tagof}(\key{Integer}) &= 001 \\
  13913. \itm{tagof}(\key{Boolean}) &= 100 \\
  13914. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  13915. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  13916. \itm{tagof}(\key{Void}) &= 101
  13917. \end{align*}
  13918. This stealing of 3 bits comes at some price: our integers are reduced
  13919. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  13920. affect vectors and procedures because those values are addresses, and
  13921. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  13922. they are always $000$. Thus, we do not lose information by overwriting
  13923. the rightmost 3 bits with the tag and we can simply zero-out the tag
  13924. to recover the original address.
  13925. To make tagged values into first-class entities, we can give them a
  13926. type, called \code{Any}, and define operations such as \code{Inject}
  13927. and \code{Project} for creating and using them, yielding the \LangAny{}
  13928. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  13929. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  13930. in greater detail.
  13931. \section{The \LangAny{} Language}
  13932. \label{sec:Rany-lang}
  13933. \newcommand{\LAnyAST}{
  13934. \begin{array}{lcl}
  13935. \Type &::= & \key{Any} \\
  13936. \itm{op} &::= & \code{any-vector-length}
  13937. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  13938. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  13939. \MID \code{procedure?} \MID \code{void?} \\
  13940. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  13941. \end{array}
  13942. }
  13943. \begin{figure}[tp]
  13944. \centering
  13945. \fbox{
  13946. \begin{minipage}{0.96\textwidth}
  13947. \small
  13948. \[
  13949. \begin{array}{l}
  13950. \gray{\LintOpAST} \\ \hline
  13951. \gray{\LvarAST{}} \\ \hline
  13952. \gray{\LifAST{}} \\ \hline
  13953. \gray{\LwhileAST{}} \\ \hline
  13954. \gray{\LtupASTRacket{}} \\ \hline
  13955. \gray{\LfunASTRacket} \\ \hline
  13956. \gray{\LlambdaASTRacket} \\ \hline
  13957. \LAnyAST \\
  13958. \begin{array}{lcl}
  13959. %% \Type &::= & \ldots \MID \key{Any} \\
  13960. %% \itm{op} &::= & \ldots \MID \code{any-vector-length}
  13961. %% \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  13962. %% &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  13963. %% \MID \code{procedure?} \MID \code{void?} \\
  13964. %% \Exp &::=& \ldots
  13965. %% \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  13966. %% &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  13967. %% \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  13968. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  13969. \end{array}
  13970. \end{array}
  13971. \]
  13972. \end{minipage}
  13973. }
  13974. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  13975. \label{fig:Rany-syntax}
  13976. \end{figure}
  13977. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  13978. (The concrete syntax of \LangAny{} is in the Appendix,
  13979. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  13980. converts the value produced by expression $e$ of type $T$ into a
  13981. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  13982. produced by expression $e$ into a value of type $T$ or else halts the
  13983. program if the type tag is not equivalent to $T$.
  13984. %
  13985. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  13986. restricted to a flat type $\FType$, which simplifies the
  13987. implementation and corresponds with what is needed for compiling \LangDyn{}.
  13988. The \code{any-vector} operators adapt the vector operations so that
  13989. they can be applied to a value of type \code{Any}. They also
  13990. generalize the vector operations in that the index is not restricted
  13991. to be a literal integer in the grammar but is allowed to be any
  13992. expression.
  13993. The type predicates such as \key{boolean?} expect their argument to
  13994. produce a tagged value; they return \key{\#t} if the tag corresponds
  13995. to the predicate and they return \key{\#f} otherwise.
  13996. The type checker for \LangAny{} is shown in
  13997. Figures~\ref{fig:type-check-Rany-part-1} and
  13998. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  13999. Figure~\ref{fig:type-check-Rany-aux}.
  14000. %
  14001. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  14002. auxiliary functions \code{apply-inject} and \code{apply-project} are
  14003. in Figure~\ref{fig:apply-project}.
  14004. \begin{figure}[btp]
  14005. \begin{lstlisting}[basicstyle=\ttfamily\small]
  14006. (define type-check-Rany_class
  14007. (class type-check-Rlambda_class
  14008. (super-new)
  14009. (inherit check-type-equal?)
  14010. (define/override (type-check-exp env)
  14011. (lambda (e)
  14012. (define recur (type-check-exp env))
  14013. (match e
  14014. [(Inject e1 ty)
  14015. (unless (flat-ty? ty)
  14016. (error 'type-check "may only inject from flat type, not ~a" ty))
  14017. (define-values (new-e1 e-ty) (recur e1))
  14018. (check-type-equal? e-ty ty e)
  14019. (values (Inject new-e1 ty) 'Any)]
  14020. [(Project e1 ty)
  14021. (unless (flat-ty? ty)
  14022. (error 'type-check "may only project to flat type, not ~a" ty))
  14023. (define-values (new-e1 e-ty) (recur e1))
  14024. (check-type-equal? e-ty 'Any e)
  14025. (values (Project new-e1 ty) ty)]
  14026. [(Prim 'any-vector-length (list e1))
  14027. (define-values (e1^ t1) (recur e1))
  14028. (check-type-equal? t1 'Any e)
  14029. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  14030. [(Prim 'any-vector-ref (list e1 e2))
  14031. (define-values (e1^ t1) (recur e1))
  14032. (define-values (e2^ t2) (recur e2))
  14033. (check-type-equal? t1 'Any e)
  14034. (check-type-equal? t2 'Integer e)
  14035. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  14036. [(Prim 'any-vector-set! (list e1 e2 e3))
  14037. (define-values (e1^ t1) (recur e1))
  14038. (define-values (e2^ t2) (recur e2))
  14039. (define-values (e3^ t3) (recur e3))
  14040. (check-type-equal? t1 'Any e)
  14041. (check-type-equal? t2 'Integer e)
  14042. (check-type-equal? t3 'Any e)
  14043. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  14044. \end{lstlisting}
  14045. \caption{Type checker for the \LangAny{} language, part 1.}
  14046. \label{fig:type-check-Rany-part-1}
  14047. \end{figure}
  14048. \begin{figure}[btp]
  14049. \begin{lstlisting}[basicstyle=\ttfamily\small]
  14050. [(ValueOf e ty)
  14051. (define-values (new-e e-ty) (recur e))
  14052. (values (ValueOf new-e ty) ty)]
  14053. [(Prim pred (list e1))
  14054. #:when (set-member? (type-predicates) pred)
  14055. (define-values (new-e1 e-ty) (recur e1))
  14056. (check-type-equal? e-ty 'Any e)
  14057. (values (Prim pred (list new-e1)) 'Boolean)]
  14058. [(If cnd thn els)
  14059. (define-values (cnd^ Tc) (recur cnd))
  14060. (define-values (thn^ Tt) (recur thn))
  14061. (define-values (els^ Te) (recur els))
  14062. (check-type-equal? Tc 'Boolean cnd)
  14063. (check-type-equal? Tt Te e)
  14064. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  14065. [(Exit) (values (Exit) '_)]
  14066. [(Prim 'eq? (list arg1 arg2))
  14067. (define-values (e1 t1) (recur arg1))
  14068. (define-values (e2 t2) (recur arg2))
  14069. (match* (t1 t2)
  14070. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  14071. [(other wise) (check-type-equal? t1 t2 e)])
  14072. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  14073. [else ((super type-check-exp env) e)])))
  14074. ))
  14075. \end{lstlisting}
  14076. \caption{Type checker for the \LangAny{} language, part 2.}
  14077. \label{fig:type-check-Rany-part-2}
  14078. \end{figure}
  14079. \begin{figure}[tbp]
  14080. \begin{lstlisting}
  14081. (define/override (operator-types)
  14082. (append
  14083. '((integer? . ((Any) . Boolean))
  14084. (vector? . ((Any) . Boolean))
  14085. (procedure? . ((Any) . Boolean))
  14086. (void? . ((Any) . Boolean))
  14087. (tag-of-any . ((Any) . Integer))
  14088. (make-any . ((_ Integer) . Any))
  14089. )
  14090. (super operator-types)))
  14091. (define/public (type-predicates)
  14092. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  14093. (define/public (combine-types t1 t2)
  14094. (match (list t1 t2)
  14095. [(list '_ t2) t2]
  14096. [(list t1 '_) t1]
  14097. [(list `(Vector ,ts1 ...)
  14098. `(Vector ,ts2 ...))
  14099. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  14100. (combine-types t1 t2)))]
  14101. [(list `(,ts1 ... -> ,rt1)
  14102. `(,ts2 ... -> ,rt2))
  14103. `(,@(for/list ([t1 ts1] [t2 ts2])
  14104. (combine-types t1 t2))
  14105. -> ,(combine-types rt1 rt2))]
  14106. [else t1]))
  14107. (define/public (flat-ty? ty)
  14108. (match ty
  14109. [(or `Integer `Boolean '_ `Void) #t]
  14110. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  14111. [`(,ts ... -> ,rt)
  14112. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  14113. [else #f]))
  14114. \end{lstlisting}
  14115. \caption{Auxiliary methods for type checking \LangAny{}.}
  14116. \label{fig:type-check-Rany-aux}
  14117. \end{figure}
  14118. \begin{figure}[btp]
  14119. \begin{lstlisting}
  14120. (define interp-Rany_class
  14121. (class interp-Rlambda_class
  14122. (super-new)
  14123. (define/override (interp-op op)
  14124. (match op
  14125. ['boolean? (match-lambda
  14126. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  14127. [else #f])]
  14128. ['integer? (match-lambda
  14129. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  14130. [else #f])]
  14131. ['vector? (match-lambda
  14132. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  14133. [else #f])]
  14134. ['procedure? (match-lambda
  14135. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  14136. [else #f])]
  14137. ['eq? (match-lambda*
  14138. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  14139. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  14140. [ls (apply (super interp-op op) ls)])]
  14141. ['any-vector-ref (lambda (v i)
  14142. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  14143. ['any-vector-set! (lambda (v i a)
  14144. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  14145. ['any-vector-length (lambda (v)
  14146. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  14147. [else (super interp-op op)]))
  14148. (define/override ((interp-exp env) e)
  14149. (define recur (interp-exp env))
  14150. (match e
  14151. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  14152. [(Project e ty2) (apply-project (recur e) ty2)]
  14153. [else ((super interp-exp env) e)]))
  14154. ))
  14155. (define (interp-Rany p)
  14156. (send (new interp-Rany_class) interp-program p))
  14157. \end{lstlisting}
  14158. \caption{Interpreter for \LangAny{}.}
  14159. \label{fig:interp-Rany}
  14160. \end{figure}
  14161. \begin{figure}[tbp]
  14162. \begin{lstlisting}
  14163. (define/public (apply-inject v tg) (Tagged v tg))
  14164. (define/public (apply-project v ty2)
  14165. (define tag2 (any-tag ty2))
  14166. (match v
  14167. [(Tagged v1 tag1)
  14168. (cond
  14169. [(eq? tag1 tag2)
  14170. (match ty2
  14171. [`(Vector ,ts ...)
  14172. (define l1 ((interp-op 'vector-length) v1))
  14173. (cond
  14174. [(eq? l1 (length ts)) v1]
  14175. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  14176. l1 (length ts))])]
  14177. [`(,ts ... -> ,rt)
  14178. (match v1
  14179. [`(function ,xs ,body ,env)
  14180. (cond [(eq? (length xs) (length ts)) v1]
  14181. [else
  14182. (error 'apply-project "arity mismatch ~a != ~a"
  14183. (length xs) (length ts))])]
  14184. [else (error 'apply-project "expected function not ~a" v1)])]
  14185. [else v1])]
  14186. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  14187. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  14188. \end{lstlisting}
  14189. \caption{Auxiliary functions for injection and projection.}
  14190. \label{fig:apply-project}
  14191. \end{figure}
  14192. \clearpage
  14193. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  14194. \label{sec:compile-r7}
  14195. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  14196. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  14197. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  14198. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  14199. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  14200. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  14201. the Boolean \code{\#t}, which must be injected to produce an
  14202. expression of type \key{Any}.
  14203. %
  14204. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  14205. addition, is representative of compilation for many primitive
  14206. operations: the arguments have type \key{Any} and must be projected to
  14207. \key{Integer} before the addition can be performed.
  14208. The compilation of \key{lambda} (third row of
  14209. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  14210. produce type annotations: we simply use \key{Any}.
  14211. %
  14212. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  14213. has to account for some differences in behavior between \LangDyn{} and
  14214. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  14215. kind of values can be used in various places. For example, the
  14216. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  14217. the arguments need not be of the same type (in that case the
  14218. result is \code{\#f}).
  14219. \begin{figure}[btp]
  14220. \centering
  14221. \begin{tabular}{|lll|} \hline
  14222. \begin{minipage}{0.27\textwidth}
  14223. \begin{lstlisting}
  14224. #t
  14225. \end{lstlisting}
  14226. \end{minipage}
  14227. &
  14228. $\Rightarrow$
  14229. &
  14230. \begin{minipage}{0.65\textwidth}
  14231. \begin{lstlisting}
  14232. (inject #t Boolean)
  14233. \end{lstlisting}
  14234. \end{minipage}
  14235. \\[2ex]\hline
  14236. \begin{minipage}{0.27\textwidth}
  14237. \begin{lstlisting}
  14238. (+ |$e_1$| |$e_2$|)
  14239. \end{lstlisting}
  14240. \end{minipage}
  14241. &
  14242. $\Rightarrow$
  14243. &
  14244. \begin{minipage}{0.65\textwidth}
  14245. \begin{lstlisting}
  14246. (inject
  14247. (+ (project |$e'_1$| Integer)
  14248. (project |$e'_2$| Integer))
  14249. Integer)
  14250. \end{lstlisting}
  14251. \end{minipage}
  14252. \\[2ex]\hline
  14253. \begin{minipage}{0.27\textwidth}
  14254. \begin{lstlisting}
  14255. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  14256. \end{lstlisting}
  14257. \end{minipage}
  14258. &
  14259. $\Rightarrow$
  14260. &
  14261. \begin{minipage}{0.65\textwidth}
  14262. \begin{lstlisting}
  14263. (inject
  14264. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  14265. (Any|$\ldots$|Any -> Any))
  14266. \end{lstlisting}
  14267. \end{minipage}
  14268. \\[2ex]\hline
  14269. \begin{minipage}{0.27\textwidth}
  14270. \begin{lstlisting}
  14271. (|$e_0$| |$e_1 \ldots e_n$|)
  14272. \end{lstlisting}
  14273. \end{minipage}
  14274. &
  14275. $\Rightarrow$
  14276. &
  14277. \begin{minipage}{0.65\textwidth}
  14278. \begin{lstlisting}
  14279. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  14280. \end{lstlisting}
  14281. \end{minipage}
  14282. \\[2ex]\hline
  14283. \begin{minipage}{0.27\textwidth}
  14284. \begin{lstlisting}
  14285. (vector-ref |$e_1$| |$e_2$|)
  14286. \end{lstlisting}
  14287. \end{minipage}
  14288. &
  14289. $\Rightarrow$
  14290. &
  14291. \begin{minipage}{0.65\textwidth}
  14292. \begin{lstlisting}
  14293. (any-vector-ref |$e_1'$| |$e_2'$|)
  14294. \end{lstlisting}
  14295. \end{minipage}
  14296. \\[2ex]\hline
  14297. \begin{minipage}{0.27\textwidth}
  14298. \begin{lstlisting}
  14299. (if |$e_1$| |$e_2$| |$e_3$|)
  14300. \end{lstlisting}
  14301. \end{minipage}
  14302. &
  14303. $\Rightarrow$
  14304. &
  14305. \begin{minipage}{0.65\textwidth}
  14306. \begin{lstlisting}
  14307. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  14308. \end{lstlisting}
  14309. \end{minipage}
  14310. \\[2ex]\hline
  14311. \begin{minipage}{0.27\textwidth}
  14312. \begin{lstlisting}
  14313. (eq? |$e_1$| |$e_2$|)
  14314. \end{lstlisting}
  14315. \end{minipage}
  14316. &
  14317. $\Rightarrow$
  14318. &
  14319. \begin{minipage}{0.65\textwidth}
  14320. \begin{lstlisting}
  14321. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  14322. \end{lstlisting}
  14323. \end{minipage}
  14324. \\[2ex]\hline
  14325. \begin{minipage}{0.27\textwidth}
  14326. \begin{lstlisting}
  14327. (not |$e_1$|)
  14328. \end{lstlisting}
  14329. \end{minipage}
  14330. &
  14331. $\Rightarrow$
  14332. &
  14333. \begin{minipage}{0.65\textwidth}
  14334. \begin{lstlisting}
  14335. (if (eq? |$e'_1$| (inject #f Boolean))
  14336. (inject #t Boolean) (inject #f Boolean))
  14337. \end{lstlisting}
  14338. \end{minipage}
  14339. \\[2ex]\hline
  14340. \end{tabular}
  14341. \caption{Cast Insertion}
  14342. \label{fig:compile-r7-Rany}
  14343. \end{figure}
  14344. \section{Reveal Casts}
  14345. \label{sec:reveal-casts-Rany}
  14346. % TODO: define R'_6
  14347. In the \code{reveal-casts} pass we recommend compiling \code{project}
  14348. into an \code{if} expression that checks whether the value's tag
  14349. matches the target type; if it does, the value is converted to a value
  14350. of the target type by removing the tag; if it does not, the program
  14351. exits. To perform these actions we need a new primitive operation,
  14352. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  14353. The \code{tag-of-any} operation retrieves the type tag from a tagged
  14354. value of type \code{Any}. The \code{ValueOf} form retrieves the
  14355. underlying value from a tagged value. The \code{ValueOf} form
  14356. includes the type for the underlying value which is used by the type
  14357. checker. Finally, the \code{Exit} form ends the execution of the
  14358. program.
  14359. If the target type of the projection is \code{Boolean} or
  14360. \code{Integer}, then \code{Project} can be translated as follows.
  14361. \begin{center}
  14362. \begin{minipage}{1.0\textwidth}
  14363. \begin{lstlisting}
  14364. (Project |$e$| |$\FType$|)
  14365. |$\Rightarrow$|
  14366. (Let |$\itm{tmp}$| |$e'$|
  14367. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  14368. (Int |$\itm{tagof}(\FType)$|)))
  14369. (ValueOf |$\itm{tmp}$| |$\FType$|)
  14370. (Exit)))
  14371. \end{lstlisting}
  14372. \end{minipage}
  14373. \end{center}
  14374. If the target type of the projection is a vector or function type,
  14375. then there is a bit more work to do. For vectors, check that the
  14376. length of the vector type matches the length of the vector (using the
  14377. \code{vector-length} primitive). For functions, check that the number
  14378. of parameters in the function type matches the function's arity (using
  14379. \code{procedure-arity}).
  14380. Regarding \code{inject}, we recommend compiling it to a slightly
  14381. lower-level primitive operation named \code{make-any}. This operation
  14382. takes a tag instead of a type.
  14383. \begin{center}
  14384. \begin{minipage}{1.0\textwidth}
  14385. \begin{lstlisting}
  14386. (Inject |$e$| |$\FType$|)
  14387. |$\Rightarrow$|
  14388. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  14389. \end{lstlisting}
  14390. \end{minipage}
  14391. \end{center}
  14392. The type predicates (\code{boolean?}, etc.) can be translated into
  14393. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  14394. translation of \code{Project}.
  14395. The \code{any-vector-ref} and \code{any-vector-set!} operations
  14396. combine the projection action with the vector operation. Also, the
  14397. read and write operations allow arbitrary expressions for the index so
  14398. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  14399. cannot guarantee that the index is within bounds. Thus, we insert code
  14400. to perform bounds checking at runtime. The translation for
  14401. \code{any-vector-ref} is as follows and the other two operations are
  14402. translated in a similar way.
  14403. \begin{lstlisting}
  14404. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  14405. |$\Rightarrow$|
  14406. (Let |$v$| |$e'_1$|
  14407. (Let |$i$| |$e'_2$|
  14408. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  14409. (If (Prim '< (list (Var |$i$|)
  14410. (Prim 'any-vector-length (list (Var |$v$|)))))
  14411. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  14412. (Exit))))
  14413. \end{lstlisting}
  14414. \section{Remove Complex Operands}
  14415. \label{sec:rco-Rany}
  14416. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  14417. The subexpression of \code{ValueOf} must be atomic.
  14418. \section{Explicate Control and \LangCAny{}}
  14419. \label{sec:explicate-Rany}
  14420. The output of \code{explicate\_control} is the \LangCAny{} language whose
  14421. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  14422. form that we added to \LangAny{} remains an expression and the \code{Exit}
  14423. expression becomes a $\Tail$. Also, note that the index argument of
  14424. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  14425. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  14426. \begin{figure}[tp]
  14427. \fbox{
  14428. \begin{minipage}{0.96\textwidth}
  14429. \small
  14430. \[
  14431. \begin{array}{lcl}
  14432. \Exp &::= & \ldots
  14433. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  14434. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  14435. &\MID& \VALUEOF{\Exp}{\FType} \\
  14436. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  14437. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  14438. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  14439. \MID \GOTO{\itm{label}} } \\
  14440. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  14441. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  14442. \MID \LP\key{Exit}\RP \\
  14443. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  14444. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  14445. \end{array}
  14446. \]
  14447. \end{minipage}
  14448. }
  14449. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  14450. \label{fig:c5-syntax}
  14451. \end{figure}
  14452. \section{Select Instructions}
  14453. \label{sec:select-Rany}
  14454. In the \code{select\_instructions} pass we translate the primitive
  14455. operations on the \code{Any} type to x86 instructions that involve
  14456. manipulating the 3 tag bits of the tagged value.
  14457. \paragraph{Make-any}
  14458. We recommend compiling the \key{make-any} primitive as follows if the
  14459. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  14460. shifts the destination to the left by the number of bits specified its
  14461. source argument (in this case $3$, the length of the tag) and it
  14462. preserves the sign of the integer. We use the \key{orq} instruction to
  14463. combine the tag and the value to form the tagged value. \\
  14464. \begin{lstlisting}
  14465. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  14466. |$\Rightarrow$|
  14467. movq |$e'$|, |\itm{lhs'}|
  14468. salq $3, |\itm{lhs'}|
  14469. orq $|$\itm{tag}$|, |\itm{lhs'}|
  14470. \end{lstlisting}
  14471. The instruction selection for vectors and procedures is different
  14472. because their is no need to shift them to the left. The rightmost 3
  14473. bits are already zeros as described at the beginning of this
  14474. chapter. So we just combine the value and the tag using \key{orq}. \\
  14475. \begin{lstlisting}
  14476. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  14477. |$\Rightarrow$|
  14478. movq |$e'$|, |\itm{lhs'}|
  14479. orq $|$\itm{tag}$|, |\itm{lhs'}|
  14480. \end{lstlisting}
  14481. \paragraph{Tag-of-any}
  14482. Recall that the \code{tag-of-any} operation extracts the type tag from
  14483. a value of type \code{Any}. The type tag is the bottom three bits, so
  14484. we obtain the tag by taking the bitwise-and of the value with $111$
  14485. ($7$ in decimal).
  14486. \begin{lstlisting}
  14487. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  14488. |$\Rightarrow$|
  14489. movq |$e'$|, |\itm{lhs'}|
  14490. andq $7, |\itm{lhs'}|
  14491. \end{lstlisting}
  14492. \paragraph{ValueOf}
  14493. Like \key{make-any}, the instructions for \key{ValueOf} are different
  14494. depending on whether the type $T$ is a pointer (vector or procedure)
  14495. or not (Integer or Boolean). The following shows the instruction
  14496. selection for Integer and Boolean. We produce an untagged value by
  14497. shifting it to the right by 3 bits.
  14498. \begin{lstlisting}
  14499. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  14500. |$\Rightarrow$|
  14501. movq |$e'$|, |\itm{lhs'}|
  14502. sarq $3, |\itm{lhs'}|
  14503. \end{lstlisting}
  14504. %
  14505. In the case for vectors and procedures, there is no need to
  14506. shift. Instead we just need to zero-out the rightmost 3 bits. We
  14507. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  14508. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  14509. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  14510. then apply \code{andq} with the tagged value to get the desired
  14511. result. \\
  14512. \begin{lstlisting}
  14513. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  14514. |$\Rightarrow$|
  14515. movq $|$-8$|, |\itm{lhs'}|
  14516. andq |$e'$|, |\itm{lhs'}|
  14517. \end{lstlisting}
  14518. %% \paragraph{Type Predicates} We leave it to the reader to
  14519. %% devise a sequence of instructions to implement the type predicates
  14520. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  14521. \paragraph{Any-vector-length}
  14522. \begin{lstlisting}
  14523. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  14524. |$\Longrightarrow$|
  14525. movq |$\neg 111$|, %r11
  14526. andq |$a_1'$|, %r11
  14527. movq 0(%r11), %r11
  14528. andq $126, %r11
  14529. sarq $1, %r11
  14530. movq %r11, |$\itm{lhs'}$|
  14531. \end{lstlisting}
  14532. \paragraph{Any-vector-ref}
  14533. The index may be an arbitrary atom so instead of computing the offset
  14534. at compile time, instructions need to be generated to compute the
  14535. offset at runtime as follows. Note the use of the new instruction
  14536. \code{imulq}.
  14537. \begin{center}
  14538. \begin{minipage}{0.96\textwidth}
  14539. \begin{lstlisting}
  14540. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  14541. |$\Longrightarrow$|
  14542. movq |$\neg 111$|, %r11
  14543. andq |$a_1'$|, %r11
  14544. movq |$a_2'$|, %rax
  14545. addq $1, %rax
  14546. imulq $8, %rax
  14547. addq %rax, %r11
  14548. movq 0(%r11) |$\itm{lhs'}$|
  14549. \end{lstlisting}
  14550. \end{minipage}
  14551. \end{center}
  14552. \paragraph{Any-vector-set!}
  14553. The code generation for \code{any-vector-set!} is similar to the other
  14554. \code{any-vector} operations.
  14555. \section{Register Allocation for \LangAny{}}
  14556. \label{sec:register-allocation-Rany}
  14557. \index{subject}{register allocation}
  14558. There is an interesting interaction between tagged values and garbage
  14559. collection that has an impact on register allocation. A variable of
  14560. type \code{Any} might refer to a vector and therefore it might be a
  14561. root that needs to be inspected and copied during garbage
  14562. collection. Thus, we need to treat variables of type \code{Any} in a
  14563. similar way to variables of type \code{Vector} for purposes of
  14564. register allocation. In particular,
  14565. \begin{itemize}
  14566. \item If a variable of type \code{Any} is live during a function call,
  14567. then it must be spilled. This can be accomplished by changing
  14568. \code{build\_interference} to mark all variables of type \code{Any}
  14569. that are live after a \code{callq} as interfering with all the
  14570. registers.
  14571. \item If a variable of type \code{Any} is spilled, it must be spilled
  14572. to the root stack instead of the normal procedure call stack.
  14573. \end{itemize}
  14574. Another concern regarding the root stack is that the garbage collector
  14575. needs to differentiate between (1) plain old pointers to tuples, (2) a
  14576. tagged value that points to a tuple, and (3) a tagged value that is
  14577. not a tuple. We enable this differentiation by choosing not to use the
  14578. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  14579. reserved for identifying plain old pointers to tuples. That way, if
  14580. one of the first three bits is set, then we have a tagged value and
  14581. inspecting the tag can differentiation between vectors ($010$) and the
  14582. other kinds of values.
  14583. \begin{exercise}\normalfont
  14584. Expand your compiler to handle \LangAny{} as discussed in the last few
  14585. sections. Create 5 new programs that use the \code{Any} type and the
  14586. new operations (\code{inject}, \code{project}, \code{boolean?},
  14587. etc.). Test your compiler on these new programs and all of your
  14588. previously created test programs.
  14589. \end{exercise}
  14590. \begin{exercise}\normalfont
  14591. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  14592. Create tests for \LangDyn{} by adapting ten of your previous test programs
  14593. by removing type annotations. Add 5 more tests programs that
  14594. specifically rely on the language being dynamically typed. That is,
  14595. they should not be legal programs in a statically typed language, but
  14596. nevertheless, they should be valid \LangDyn{} programs that run to
  14597. completion without error.
  14598. \end{exercise}
  14599. \begin{figure}[p]
  14600. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14601. \node (Rfun) at (0,4) {\large \LangDyn{}};
  14602. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  14603. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  14604. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  14605. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  14606. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  14607. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  14608. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  14609. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  14610. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  14611. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  14612. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  14613. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14614. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14615. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14616. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14617. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14618. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14619. \path[->,bend left=15] (Rfun) edge [above] node
  14620. {\ttfamily\footnotesize shrink} (Rfun-2);
  14621. \path[->,bend left=15] (Rfun-2) edge [above] node
  14622. {\ttfamily\footnotesize uniquify} (Rfun-3);
  14623. \path[->,bend left=15] (Rfun-3) edge [above] node
  14624. {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  14625. \path[->,bend right=15] (Rfun-4) edge [left] node
  14626. {\ttfamily\footnotesize cast\_insert} (Rfun-5);
  14627. \path[->,bend left=15] (Rfun-5) edge [above] node
  14628. {\ttfamily\footnotesize check\_bounds} (Rfun-6);
  14629. \path[->,bend left=15] (Rfun-6) edge [left] node
  14630. {\ttfamily\footnotesize reveal\_casts} (Rfun-7);
  14631. \path[->,bend left=15] (Rfun-7) edge [below] node
  14632. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  14633. \path[->,bend right=15] (F1-2) edge [above] node
  14634. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  14635. \path[->,bend right=15] (F1-3) edge [above] node
  14636. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  14637. \path[->,bend right=15] (F1-4) edge [above] node
  14638. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  14639. \path[->,bend right=15] (F1-5) edge [right] node
  14640. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14641. \path[->,bend left=15] (C3-2) edge [left] node
  14642. {\ttfamily\footnotesize select\_instr.} (x86-2);
  14643. \path[->,bend right=15] (x86-2) edge [left] node
  14644. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14645. \path[->,bend right=15] (x86-2-1) edge [below] node
  14646. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  14647. \path[->,bend right=15] (x86-2-2) edge [left] node
  14648. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  14649. \path[->,bend left=15] (x86-3) edge [above] node
  14650. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  14651. \path[->,bend left=15] (x86-4) edge [right] node
  14652. {\ttfamily\footnotesize print\_x86} (x86-5);
  14653. \end{tikzpicture}
  14654. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  14655. \label{fig:Rdyn-passes}
  14656. \end{figure}
  14657. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  14658. for the compilation of \LangDyn{}.
  14659. % Further Reading
  14660. \fi % racketEd
  14661. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14662. {\if\edition\pythonEd
  14663. \chapter{Objects}
  14664. \label{ch:Robject}
  14665. \index{subject}{objects}
  14666. \index{subject}{classes}
  14667. \fi}
  14668. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14669. \chapter{Gradual Typing}
  14670. \label{ch:Rgrad}
  14671. \index{subject}{gradual typing}
  14672. \if\edition\racketEd
  14673. This chapter studies a language, \LangGrad{}, in which the programmer
  14674. can choose between static and dynamic type checking in different parts
  14675. of a program, thereby mixing the statically typed \LangLoop{} language
  14676. with the dynamically typed \LangDyn{}. There are several approaches to
  14677. mixing static and dynamic typing, including multi-language
  14678. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  14679. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  14680. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  14681. programmer controls the amount of static versus dynamic checking by
  14682. adding or removing type annotations on parameters and
  14683. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  14684. %
  14685. The concrete syntax of \LangGrad{} is defined in
  14686. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  14687. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  14688. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  14689. non-terminals that make type annotations optional. The return types
  14690. are not optional in the abstract syntax; the parser fills in
  14691. \code{Any} when the return type is not specified in the concrete
  14692. syntax.
  14693. \begin{figure}[tp]
  14694. \centering
  14695. \fbox{
  14696. \begin{minipage}{0.96\textwidth}
  14697. \small
  14698. \[
  14699. \begin{array}{lcl}
  14700. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  14701. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  14702. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  14703. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  14704. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  14705. &\MID& \gray{\key{\#t} \MID \key{\#f}
  14706. \MID (\key{and}\;\Exp\;\Exp)
  14707. \MID (\key{or}\;\Exp\;\Exp)
  14708. \MID (\key{not}\;\Exp) } \\
  14709. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  14710. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  14711. (\key{vector-ref}\;\Exp\;\Int)} \\
  14712. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  14713. \MID (\Exp \; \Exp\ldots) } \\
  14714. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  14715. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  14716. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  14717. \MID \CBEGIN{\Exp\ldots}{\Exp}
  14718. \MID \CWHILE{\Exp}{\Exp} } \\
  14719. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  14720. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  14721. \end{array}
  14722. \]
  14723. \end{minipage}
  14724. }
  14725. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  14726. \label{fig:Rgrad-concrete-syntax}
  14727. \end{figure}
  14728. \begin{figure}[tp]
  14729. \centering
  14730. \fbox{
  14731. \begin{minipage}{0.96\textwidth}
  14732. \small
  14733. \[
  14734. \begin{array}{lcl}
  14735. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  14736. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  14737. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  14738. &\MID& \gray{ \BOOL{\itm{bool}}
  14739. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  14740. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  14741. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  14742. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  14743. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  14744. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  14745. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  14746. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  14747. \end{array}
  14748. \]
  14749. \end{minipage}
  14750. }
  14751. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  14752. \label{fig:Rgrad-syntax}
  14753. \end{figure}
  14754. Both the type checker and the interpreter for \LangGrad{} require some
  14755. interesting changes to enable gradual typing, which we discuss in the
  14756. next two sections in the context of the \code{map-vec} example from
  14757. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  14758. revised the \code{map-vec} example, omitting the type annotations from
  14759. the \code{add1} function.
  14760. \begin{figure}[btp]
  14761. % gradual_test_9.rkt
  14762. \begin{lstlisting}
  14763. (define (map-vec [f : (Integer -> Integer)]
  14764. [v : (Vector Integer Integer)])
  14765. : (Vector Integer Integer)
  14766. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14767. (define (add1 x) (+ x 1))
  14768. (vector-ref (map-vec add1 (vector 0 41)) 1)
  14769. \end{lstlisting}
  14770. \caption{A partially-typed version of the \code{map-vec} example.}
  14771. \label{fig:gradual-map-vec}
  14772. \end{figure}
  14773. \section{Type Checking \LangGrad{} and \LangCast{}}
  14774. \label{sec:gradual-type-check}
  14775. The type checker for \LangGrad{} uses the \code{Any} type for missing
  14776. parameter and return types. For example, the \code{x} parameter of
  14777. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  14778. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  14779. consider the \code{+} operator inside \code{add1}. It expects both
  14780. arguments to have type \code{Integer}, but its first argument \code{x}
  14781. has type \code{Any}. In a gradually typed language, such differences
  14782. are allowed so long as the types are \emph{consistent}, that is, they
  14783. are equal except in places where there is an \code{Any} type. The type
  14784. \code{Any} is consistent with every other type.
  14785. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  14786. \begin{figure}[tbp]
  14787. \begin{lstlisting}
  14788. (define/public (consistent? t1 t2)
  14789. (match* (t1 t2)
  14790. [('Integer 'Integer) #t]
  14791. [('Boolean 'Boolean) #t]
  14792. [('Void 'Void) #t]
  14793. [('Any t2) #t]
  14794. [(t1 'Any) #t]
  14795. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  14796. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  14797. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  14798. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  14799. (consistent? rt1 rt2))]
  14800. [(other wise) #f]))
  14801. \end{lstlisting}
  14802. \caption{The consistency predicate on types.}
  14803. \label{fig:consistent}
  14804. \end{figure}
  14805. Returning to the \code{map-vec} example of
  14806. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  14807. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  14808. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  14809. because the two types are consistent. In particular, \code{->} is
  14810. equal to \code{->} and because \code{Any} is consistent with
  14811. \code{Integer}.
  14812. Next consider a program with an error, such as applying the
  14813. \code{map-vec} to a function that sometimes returns a Boolean, as
  14814. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  14815. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  14816. consistent with the type of parameter \code{f} of \code{map-vec}, that
  14817. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  14818. Integer)}. One might say that a gradual type checker is optimistic
  14819. in that it accepts programs that might execute without a runtime type
  14820. error.
  14821. %
  14822. Unfortunately, running this program with input \code{1} triggers an
  14823. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  14824. performs checking at runtime to ensure the integrity of the static
  14825. types, such as the \code{(Integer -> Integer)} annotation on parameter
  14826. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  14827. new \code{Cast} form that is inserted by the type checker. Thus, the
  14828. output of the type checker is a program in the \LangCast{} language, which
  14829. adds \code{Cast} to \LangLoop{}, as shown in
  14830. Figure~\ref{fig:Rgrad-prime-syntax}.
  14831. \begin{figure}[tp]
  14832. \centering
  14833. \fbox{
  14834. \begin{minipage}{0.96\textwidth}
  14835. \small
  14836. \[
  14837. \begin{array}{lcl}
  14838. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  14839. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  14840. \end{array}
  14841. \]
  14842. \end{minipage}
  14843. }
  14844. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  14845. \label{fig:Rgrad-prime-syntax}
  14846. \end{figure}
  14847. \begin{figure}[tbp]
  14848. \begin{lstlisting}
  14849. (define (map-vec [f : (Integer -> Integer)]
  14850. [v : (Vector Integer Integer)])
  14851. : (Vector Integer Integer)
  14852. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14853. (define (add1 x) (+ x 1))
  14854. (define (true) #t)
  14855. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  14856. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  14857. \end{lstlisting}
  14858. \caption{A variant of the \code{map-vec} example with an error.}
  14859. \label{fig:map-vec-maybe-add1}
  14860. \end{figure}
  14861. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  14862. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  14863. inserted every time the type checker sees two types that are
  14864. consistent but not equal. In the \code{add1} function, \code{x} is
  14865. cast to \code{Integer} and the result of the \code{+} is cast to
  14866. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  14867. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  14868. \begin{figure}[btp]
  14869. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14870. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  14871. : (Vector Integer Integer)
  14872. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14873. (define (add1 [x : Any]) : Any
  14874. (cast (+ (cast x Any Integer) 1) Integer Any))
  14875. (define (true) : Any (cast #t Boolean Any))
  14876. (define (maybe-add1 [x : Any]) : Any
  14877. (if (eq? 0 (read)) (add1 x) (true)))
  14878. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  14879. (vector 0 41)) 0)
  14880. \end{lstlisting}
  14881. \caption{Output of type checking \code{map-vec}
  14882. and \code{maybe-add1}.}
  14883. \label{fig:map-vec-cast}
  14884. \end{figure}
  14885. The type checker for \LangGrad{} is defined in
  14886. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  14887. and \ref{fig:type-check-Rgradual-3}.
  14888. \begin{figure}[tbp]
  14889. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14890. (define type-check-gradual_class
  14891. (class type-check-Rwhile_class
  14892. (super-new)
  14893. (inherit operator-types type-predicates)
  14894. (define/override (type-check-exp env)
  14895. (lambda (e)
  14896. (define recur (type-check-exp env))
  14897. (match e
  14898. [(Prim 'vector-length (list e1))
  14899. (define-values (e1^ t) (recur e1))
  14900. (match t
  14901. [`(Vector ,ts ...)
  14902. (values (Prim 'vector-length (list e1^)) 'Integer)]
  14903. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  14904. [(Prim 'vector-ref (list e1 e2))
  14905. (define-values (e1^ t1) (recur e1))
  14906. (define-values (e2^ t2) (recur e2))
  14907. (check-consistent? t2 'Integer e)
  14908. (match t1
  14909. [`(Vector ,ts ...)
  14910. (match e2^
  14911. [(Int i)
  14912. (unless (and (0 . <= . i) (i . < . (length ts)))
  14913. (error 'type-check "invalid index ~a in ~a" i e))
  14914. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  14915. [else (define e1^^ (make-cast e1^ t1 'Any))
  14916. (define e2^^ (make-cast e2^ t2 'Integer))
  14917. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  14918. ['Any
  14919. (define e2^^ (make-cast e2^ t2 'Integer))
  14920. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  14921. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  14922. [(Prim 'vector-set! (list e1 e2 e3) )
  14923. (define-values (e1^ t1) (recur e1))
  14924. (define-values (e2^ t2) (recur e2))
  14925. (define-values (e3^ t3) (recur e3))
  14926. (check-consistent? t2 'Integer e)
  14927. (match t1
  14928. [`(Vector ,ts ...)
  14929. (match e2^
  14930. [(Int i)
  14931. (unless (and (0 . <= . i) (i . < . (length ts)))
  14932. (error 'type-check "invalid index ~a in ~a" i e))
  14933. (check-consistent? (list-ref ts i) t3 e)
  14934. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  14935. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  14936. [else
  14937. (define e1^^ (make-cast e1^ t1 'Any))
  14938. (define e2^^ (make-cast e2^ t2 'Integer))
  14939. (define e3^^ (make-cast e3^ t3 'Any))
  14940. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  14941. ['Any
  14942. (define e2^^ (make-cast e2^ t2 'Integer))
  14943. (define e3^^ (make-cast e3^ t3 'Any))
  14944. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  14945. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  14946. \end{lstlisting}
  14947. \caption{Type checker for the \LangGrad{} language, part 1.}
  14948. \label{fig:type-check-Rgradual-1}
  14949. \end{figure}
  14950. \begin{figure}[tbp]
  14951. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14952. [(Prim 'eq? (list e1 e2))
  14953. (define-values (e1^ t1) (recur e1))
  14954. (define-values (e2^ t2) (recur e2))
  14955. (check-consistent? t1 t2 e)
  14956. (define T (meet t1 t2))
  14957. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  14958. 'Boolean)]
  14959. [(Prim 'not (list e1))
  14960. (define-values (e1^ t1) (recur e1))
  14961. (match t1
  14962. ['Any
  14963. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  14964. (Bool #t) (Bool #f)))]
  14965. [else
  14966. (define-values (t-ret new-es^)
  14967. (type-check-op 'not (list t1) (list e1^) e))
  14968. (values (Prim 'not new-es^) t-ret)])]
  14969. [(Prim 'and (list e1 e2))
  14970. (recur (If e1 e2 (Bool #f)))]
  14971. [(Prim 'or (list e1 e2))
  14972. (define tmp (gensym 'tmp))
  14973. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  14974. [(Prim op es)
  14975. #:when (not (set-member? explicit-prim-ops op))
  14976. (define-values (new-es ts)
  14977. (for/lists (exprs types) ([e es])
  14978. (recur e)))
  14979. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  14980. (values (Prim op new-es^) t-ret)]
  14981. [(If e1 e2 e3)
  14982. (define-values (e1^ T1) (recur e1))
  14983. (define-values (e2^ T2) (recur e2))
  14984. (define-values (e3^ T3) (recur e3))
  14985. (check-consistent? T2 T3 e)
  14986. (match T1
  14987. ['Boolean
  14988. (define Tif (join T2 T3))
  14989. (values (If e1^ (make-cast e2^ T2 Tif)
  14990. (make-cast e3^ T3 Tif)) Tif)]
  14991. ['Any
  14992. (define Tif (meet T2 T3))
  14993. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  14994. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  14995. Tif)]
  14996. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  14997. [(HasType e1 T)
  14998. (define-values (e1^ T1) (recur e1))
  14999. (check-consistent? T1 T)
  15000. (values (make-cast e1^ T1 T) T)]
  15001. [(SetBang x e1)
  15002. (define-values (e1^ T1) (recur e1))
  15003. (define varT (dict-ref env x))
  15004. (check-consistent? T1 varT e)
  15005. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  15006. [(WhileLoop e1 e2)
  15007. (define-values (e1^ T1) (recur e1))
  15008. (check-consistent? T1 'Boolean e)
  15009. (define-values (e2^ T2) ((type-check-exp env) e2))
  15010. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  15011. \end{lstlisting}
  15012. \caption{Type checker for the \LangGrad{} language, part 2.}
  15013. \label{fig:type-check-Rgradual-2}
  15014. \end{figure}
  15015. \begin{figure}[tbp]
  15016. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15017. [(Apply e1 e2s)
  15018. (define-values (e1^ T1) (recur e1))
  15019. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  15020. (match T1
  15021. [`(,T1ps ... -> ,T1rt)
  15022. (for ([T2 T2s] [Tp T1ps])
  15023. (check-consistent? T2 Tp e))
  15024. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  15025. (make-cast e2 src tgt)))
  15026. (values (Apply e1^ e2s^^) T1rt)]
  15027. [`Any
  15028. (define e1^^ (make-cast e1^ 'Any
  15029. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  15030. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  15031. (make-cast e2 src 'Any)))
  15032. (values (Apply e1^^ e2s^^) 'Any)]
  15033. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  15034. [(Lambda params Tr e1)
  15035. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  15036. (match p
  15037. [`[,x : ,T] (values x T)]
  15038. [(? symbol? x) (values x 'Any)])))
  15039. (define-values (e1^ T1)
  15040. ((type-check-exp (append (map cons xs Ts) env)) e1))
  15041. (check-consistent? Tr T1 e)
  15042. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  15043. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  15044. [else ((super type-check-exp env) e)]
  15045. )))
  15046. \end{lstlisting}
  15047. \caption{Type checker for the \LangGrad{} language, part 3.}
  15048. \label{fig:type-check-Rgradual-3}
  15049. \end{figure}
  15050. \begin{figure}[tbp]
  15051. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15052. (define/public (join t1 t2)
  15053. (match* (t1 t2)
  15054. [('Integer 'Integer) 'Integer]
  15055. [('Boolean 'Boolean) 'Boolean]
  15056. [('Void 'Void) 'Void]
  15057. [('Any t2) t2]
  15058. [(t1 'Any) t1]
  15059. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  15060. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  15061. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  15062. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  15063. -> ,(join rt1 rt2))]))
  15064. (define/public (meet t1 t2)
  15065. (match* (t1 t2)
  15066. [('Integer 'Integer) 'Integer]
  15067. [('Boolean 'Boolean) 'Boolean]
  15068. [('Void 'Void) 'Void]
  15069. [('Any t2) 'Any]
  15070. [(t1 'Any) 'Any]
  15071. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  15072. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  15073. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  15074. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  15075. -> ,(meet rt1 rt2))]))
  15076. (define/public (make-cast e src tgt)
  15077. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  15078. (define/public (check-consistent? t1 t2 e)
  15079. (unless (consistent? t1 t2)
  15080. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  15081. (define/override (type-check-op op arg-types args e)
  15082. (match (dict-ref (operator-types) op)
  15083. [`(,param-types . ,return-type)
  15084. (for ([at arg-types] [pt param-types])
  15085. (check-consistent? at pt e))
  15086. (values return-type
  15087. (for/list ([e args] [s arg-types] [t param-types])
  15088. (make-cast e s t)))]
  15089. [else (error 'type-check-op "unrecognized ~a" op)]))
  15090. (define explicit-prim-ops
  15091. (set-union
  15092. (type-predicates)
  15093. (set 'procedure-arity 'eq?
  15094. 'vector 'vector-length 'vector-ref 'vector-set!
  15095. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  15096. (define/override (fun-def-type d)
  15097. (match d
  15098. [(Def f params rt info body)
  15099. (define ps
  15100. (for/list ([p params])
  15101. (match p
  15102. [`[,x : ,T] T]
  15103. [(? symbol?) 'Any]
  15104. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  15105. `(,@ps -> ,rt)]
  15106. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  15107. \end{lstlisting}
  15108. \caption{Auxiliary functions for type checking \LangGrad{}.}
  15109. \label{fig:type-check-Rgradual-aux}
  15110. \end{figure}
  15111. \clearpage
  15112. \section{Interpreting \LangCast{}}
  15113. \label{sec:interp-casts}
  15114. The runtime behavior of first-order casts is straightforward, that is,
  15115. casts involving simple types such as \code{Integer} and
  15116. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  15117. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  15118. puts the integer into a tagged value
  15119. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  15120. \code{Integer} is accomplished with the \code{Project} operator, that
  15121. is, by checking the value's tag and either retrieving the underlying
  15122. integer or signaling an error if it the tag is not the one for
  15123. integers (Figure~\ref{fig:apply-project}).
  15124. %
  15125. Things get more interesting for higher-order casts, that is, casts
  15126. involving function or vector types.
  15127. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  15128. Any)} to \code{(Integer -> Integer)}. When a function flows through
  15129. this cast at runtime, we can't know in general whether the function
  15130. will always return an integer.\footnote{Predicting the return value of
  15131. a function is equivalent to the halting problem, which is
  15132. undecidable.} The \LangCast{} interpreter therefore delays the checking
  15133. of the cast until the function is applied. This is accomplished by
  15134. wrapping \code{maybe-add1} in a new function that casts its parameter
  15135. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  15136. casts the return value from \code{Any} to \code{Integer}.
  15137. Turning our attention to casts involving vector types, we consider the
  15138. example in Figure~\ref{fig:map-vec-bang} that defines a
  15139. partially-typed version of \code{map-vec} whose parameter \code{v} has
  15140. type \code{(Vector Any Any)} and that updates \code{v} in place
  15141. instead of returning a new vector. So we name this function
  15142. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  15143. the type checker inserts a cast from \code{(Vector Integer Integer)}
  15144. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  15145. cast between vector types would be a build a new vector whose elements
  15146. are the result of casting each of the original elements to the
  15147. appropriate target type. However, this approach is only valid for
  15148. immutable vectors; and our vectors are mutable. In the example of
  15149. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  15150. the updates inside of \code{map-vec!} would happen to the new vector
  15151. and not the original one.
  15152. \begin{figure}[tbp]
  15153. % gradual_test_11.rkt
  15154. \begin{lstlisting}
  15155. (define (map-vec! [f : (Any -> Any)]
  15156. [v : (Vector Any Any)]) : Void
  15157. (begin
  15158. (vector-set! v 0 (f (vector-ref v 0)))
  15159. (vector-set! v 1 (f (vector-ref v 1)))))
  15160. (define (add1 x) (+ x 1))
  15161. (let ([v (vector 0 41)])
  15162. (begin (map-vec! add1 v) (vector-ref v 1)))
  15163. \end{lstlisting}
  15164. \caption{An example involving casts on vectors.}
  15165. \label{fig:map-vec-bang}
  15166. \end{figure}
  15167. Instead the interpreter needs to create a new kind of value, a
  15168. \emph{vector proxy}, that intercepts every vector operation. On a
  15169. read, the proxy reads from the underlying vector and then applies a
  15170. cast to the resulting value. On a write, the proxy casts the argument
  15171. value and then performs the write to the underlying vector. For the
  15172. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  15173. \code{0} from \code{Integer} to \code{Any}. For the first
  15174. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  15175. to \code{Integer}.
  15176. The final category of cast that we need to consider are casts between
  15177. the \code{Any} type and either a function or a vector
  15178. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  15179. in which parameter \code{v} does not have a type annotation, so it is
  15180. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  15181. type \code{(Vector Integer Integer)} so the type checker inserts a
  15182. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  15183. thought is to use \code{Inject}, but that doesn't work because
  15184. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  15185. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  15186. to \code{Any}.
  15187. \begin{figure}[tbp]
  15188. \begin{lstlisting}
  15189. (define (map-vec! [f : (Any -> Any)] v) : Void
  15190. (begin
  15191. (vector-set! v 0 (f (vector-ref v 0)))
  15192. (vector-set! v 1 (f (vector-ref v 1)))))
  15193. (define (add1 x) (+ x 1))
  15194. (let ([v (vector 0 41)])
  15195. (begin (map-vec! add1 v) (vector-ref v 1)))
  15196. \end{lstlisting}
  15197. \caption{Casting a vector to \code{Any}.}
  15198. \label{fig:map-vec-any}
  15199. \end{figure}
  15200. The \LangCast{} interpreter uses an auxiliary function named
  15201. \code{apply-cast} to cast a value from a source type to a target type,
  15202. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  15203. of the kinds of casts that we've discussed in this section.
  15204. \begin{figure}[tbp]
  15205. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15206. (define/public (apply-cast v s t)
  15207. (match* (s t)
  15208. [(t1 t2) #:when (equal? t1 t2) v]
  15209. [('Any t2)
  15210. (match t2
  15211. [`(,ts ... -> ,rt)
  15212. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  15213. (define v^ (apply-project v any->any))
  15214. (apply-cast v^ any->any `(,@ts -> ,rt))]
  15215. [`(Vector ,ts ...)
  15216. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  15217. (define v^ (apply-project v vec-any))
  15218. (apply-cast v^ vec-any `(Vector ,@ts))]
  15219. [else (apply-project v t2)])]
  15220. [(t1 'Any)
  15221. (match t1
  15222. [`(,ts ... -> ,rt)
  15223. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  15224. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  15225. (apply-inject v^ (any-tag any->any))]
  15226. [`(Vector ,ts ...)
  15227. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  15228. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  15229. (apply-inject v^ (any-tag vec-any))]
  15230. [else (apply-inject v (any-tag t1))])]
  15231. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  15232. (define x (gensym 'x))
  15233. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  15234. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  15235. (define cast-writes
  15236. (for/list ([t1 ts1] [t2 ts2])
  15237. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  15238. `(vector-proxy ,(vector v (apply vector cast-reads)
  15239. (apply vector cast-writes)))]
  15240. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  15241. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  15242. `(function ,xs ,(Cast
  15243. (Apply (Value v)
  15244. (for/list ([x xs][t1 ts1][t2 ts2])
  15245. (Cast (Var x) t2 t1)))
  15246. rt1 rt2) ())]
  15247. ))
  15248. \end{lstlisting}
  15249. \caption{The \code{apply-cast} auxiliary method.}
  15250. \label{fig:apply-cast}
  15251. \end{figure}
  15252. The interpreter for \LangCast{} is defined in
  15253. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  15254. dispatching to \code{apply-cast}. To handle the addition of vector
  15255. proxies, we update the vector primitives in \code{interp-op} using the
  15256. functions in Figure~\ref{fig:guarded-vector}.
  15257. \begin{figure}[tbp]
  15258. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15259. (define interp-Rcast_class
  15260. (class interp-Rwhile_class
  15261. (super-new)
  15262. (inherit apply-fun apply-inject apply-project)
  15263. (define/override (interp-op op)
  15264. (match op
  15265. ['vector-length guarded-vector-length]
  15266. ['vector-ref guarded-vector-ref]
  15267. ['vector-set! guarded-vector-set!]
  15268. ['any-vector-ref (lambda (v i)
  15269. (match v [`(tagged ,v^ ,tg)
  15270. (guarded-vector-ref v^ i)]))]
  15271. ['any-vector-set! (lambda (v i a)
  15272. (match v [`(tagged ,v^ ,tg)
  15273. (guarded-vector-set! v^ i a)]))]
  15274. ['any-vector-length (lambda (v)
  15275. (match v [`(tagged ,v^ ,tg)
  15276. (guarded-vector-length v^)]))]
  15277. [else (super interp-op op)]
  15278. ))
  15279. (define/override ((interp-exp env) e)
  15280. (define (recur e) ((interp-exp env) e))
  15281. (match e
  15282. [(Value v) v]
  15283. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  15284. [else ((super interp-exp env) e)]))
  15285. ))
  15286. (define (interp-Rcast p)
  15287. (send (new interp-Rcast_class) interp-program p))
  15288. \end{lstlisting}
  15289. \caption{The interpreter for \LangCast{}.}
  15290. \label{fig:interp-Rcast}
  15291. \end{figure}
  15292. \begin{figure}[tbp]
  15293. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15294. (define (guarded-vector-ref vec i)
  15295. (match vec
  15296. [`(vector-proxy ,proxy)
  15297. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  15298. (define rd (vector-ref (vector-ref proxy 1) i))
  15299. (apply-fun rd (list val) 'guarded-vector-ref)]
  15300. [else (vector-ref vec i)]))
  15301. (define (guarded-vector-set! vec i arg)
  15302. (match vec
  15303. [`(vector-proxy ,proxy)
  15304. (define wr (vector-ref (vector-ref proxy 2) i))
  15305. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  15306. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  15307. [else (vector-set! vec i arg)]))
  15308. (define (guarded-vector-length vec)
  15309. (match vec
  15310. [`(vector-proxy ,proxy)
  15311. (guarded-vector-length (vector-ref proxy 0))]
  15312. [else (vector-length vec)]))
  15313. \end{lstlisting}
  15314. \caption{The guarded-vector auxiliary functions.}
  15315. \label{fig:guarded-vector}
  15316. \end{figure}
  15317. \section{Lower Casts}
  15318. \label{sec:lower-casts}
  15319. The next step in the journey towards x86 is the \code{lower-casts}
  15320. pass that translates the casts in \LangCast{} to the lower-level
  15321. \code{Inject} and \code{Project} operators and a new operator for
  15322. creating vector proxies, extending the \LangLoop{} language to create
  15323. \LangProxy{}. We recommend creating an auxiliary function named
  15324. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  15325. and a target type, and translates it to expression in \LangProxy{} that has
  15326. the same behavior as casting the expression from the source to the
  15327. target type in the interpreter.
  15328. The \code{lower-cast} function can follow a code structure similar to
  15329. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  15330. the interpreter for \LangCast{} because it must handle the same cases as
  15331. \code{apply-cast} and it needs to mimic the behavior of
  15332. \code{apply-cast}. The most interesting cases are those concerning the
  15333. casts between two vector types and between two function types.
  15334. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  15335. type to another vector type is accomplished by creating a proxy that
  15336. intercepts the operations on the underlying vector. Here we make the
  15337. creation of the proxy explicit with the \code{vector-proxy} primitive
  15338. operation. It takes three arguments, the first is an expression for
  15339. the vector, the second is a vector of functions for casting an element
  15340. that is being read from the vector, and the third is a vector of
  15341. functions for casting an element that is being written to the vector.
  15342. You can create the functions using \code{Lambda}. Also, as we shall
  15343. see in the next section, we need to differentiate these vectors from
  15344. the user-created ones, so we recommend using a new primitive operator
  15345. named \code{raw-vector} instead of \code{vector} to create these
  15346. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  15347. the output of \code{lower-casts} on the example in
  15348. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  15349. integers to a vector of \code{Any}.
  15350. \begin{figure}[tbp]
  15351. \begin{lstlisting}
  15352. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  15353. (begin
  15354. (vector-set! v 0 (f (vector-ref v 0)))
  15355. (vector-set! v 1 (f (vector-ref v 1)))))
  15356. (define (add1 [x : Any]) : Any
  15357. (inject (+ (project x Integer) 1) Integer))
  15358. (let ([v (vector 0 41)])
  15359. (begin
  15360. (map-vec! add1 (vector-proxy v
  15361. (raw-vector (lambda: ([x9 : Integer]) : Any
  15362. (inject x9 Integer))
  15363. (lambda: ([x9 : Integer]) : Any
  15364. (inject x9 Integer)))
  15365. (raw-vector (lambda: ([x9 : Any]) : Integer
  15366. (project x9 Integer))
  15367. (lambda: ([x9 : Any]) : Integer
  15368. (project x9 Integer)))))
  15369. (vector-ref v 1)))
  15370. \end{lstlisting}
  15371. \caption{Output of \code{lower-casts} on the example in
  15372. Figure~\ref{fig:map-vec-bang}.}
  15373. \label{fig:map-vec-bang-lower-cast}
  15374. \end{figure}
  15375. A cast from one function type to another function type is accomplished
  15376. by generating a \code{Lambda} whose parameter and return types match
  15377. the target function type. The body of the \code{Lambda} should cast
  15378. the parameters from the target type to the source type (yes,
  15379. backwards! functions are contravariant\index{subject}{contravariant} in the
  15380. parameters), then call the underlying function, and finally cast the
  15381. result from the source return type to the target return type.
  15382. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  15383. \code{lower-casts} pass on the \code{map-vec} example in
  15384. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  15385. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  15386. \begin{figure}[tbp]
  15387. \begin{lstlisting}
  15388. (define (map-vec [f : (Integer -> Integer)]
  15389. [v : (Vector Integer Integer)])
  15390. : (Vector Integer Integer)
  15391. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  15392. (define (add1 [x : Any]) : Any
  15393. (inject (+ (project x Integer) 1) Integer))
  15394. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  15395. (project (add1 (inject x9 Integer)) Integer))
  15396. (vector 0 41)) 1)
  15397. \end{lstlisting}
  15398. \caption{Output of \code{lower-casts} on the example in
  15399. Figure~\ref{fig:gradual-map-vec}.}
  15400. \label{fig:map-vec-lower-cast}
  15401. \end{figure}
  15402. \section{Differentiate Proxies}
  15403. \label{sec:differentiate-proxies}
  15404. So far the job of differentiating vectors and vector proxies has been
  15405. the job of the interpreter. For example, the interpreter for \LangCast{}
  15406. implements \code{vector-ref} using the \code{guarded-vector-ref}
  15407. function in Figure~\ref{fig:guarded-vector}. In the
  15408. \code{differentiate-proxies} pass we shift this responsibility to the
  15409. generated code.
  15410. We begin by designing the output language $R^p_8$. In
  15411. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  15412. proxies. In $R^p_8$ we return the \code{Vector} type to
  15413. its original meaning, as the type of real vectors, and we introduce a
  15414. new type, \code{PVector}, whose values can be either real vectors or
  15415. vector proxies. This new type comes with a suite of new primitive
  15416. operations for creating and using values of type \code{PVector}. We
  15417. don't need to introduce a new type to represent vector proxies. A
  15418. proxy is represented by a vector containing three things: 1) the
  15419. underlying vector, 2) a vector of functions for casting elements that
  15420. are read from the vector, and 3) a vector of functions for casting
  15421. values to be written to the vector. So we define the following
  15422. abbreviation for the type of a vector proxy:
  15423. \[
  15424. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  15425. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  15426. \to (\key{PVector}~ T' \ldots)
  15427. \]
  15428. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  15429. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  15430. %
  15431. Next we describe each of the new primitive operations.
  15432. \begin{description}
  15433. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  15434. (\key{PVector} $T \ldots$)]\ \\
  15435. %
  15436. This operation brands a vector as a value of the \code{PVector} type.
  15437. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  15438. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  15439. %
  15440. This operation brands a vector proxy as value of the \code{PVector} type.
  15441. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  15442. \code{Boolean}] \ \\
  15443. %
  15444. returns true if the value is a vector proxy and false if it is a
  15445. real vector.
  15446. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  15447. (\key{Vector} $T \ldots$)]\ \\
  15448. %
  15449. Assuming that the input is a vector (and not a proxy), this
  15450. operation returns the vector.
  15451. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  15452. $\to$ \code{Boolean}]\ \\
  15453. %
  15454. Given a vector proxy, this operation returns the length of the
  15455. underlying vector.
  15456. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  15457. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  15458. %
  15459. Given a vector proxy, this operation returns the $i$th element of
  15460. the underlying vector.
  15461. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  15462. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  15463. proxy, this operation writes a value to the $i$th element of the
  15464. underlying vector.
  15465. \end{description}
  15466. Now to discuss the translation that differentiates vectors from
  15467. proxies. First, every type annotation in the program must be
  15468. translated (recursively) to replace \code{Vector} with \code{PVector}.
  15469. Next, we must insert uses of \code{PVector} operations in the
  15470. appropriate places. For example, we wrap every vector creation with an
  15471. \code{inject-vector}.
  15472. \begin{lstlisting}
  15473. (vector |$e_1 \ldots e_n$|)
  15474. |$\Rightarrow$|
  15475. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  15476. \end{lstlisting}
  15477. The \code{raw-vector} operator that we introduced in the previous
  15478. section does not get injected.
  15479. \begin{lstlisting}
  15480. (raw-vector |$e_1 \ldots e_n$|)
  15481. |$\Rightarrow$|
  15482. (vector |$e'_1 \ldots e'_n$|)
  15483. \end{lstlisting}
  15484. The \code{vector-proxy} primitive translates as follows.
  15485. \begin{lstlisting}
  15486. (vector-proxy |$e_1~e_2~e_3$|)
  15487. |$\Rightarrow$|
  15488. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  15489. \end{lstlisting}
  15490. We translate the vector operations into conditional expressions that
  15491. check whether the value is a proxy and then dispatch to either the
  15492. appropriate proxy vector operation or the regular vector operation.
  15493. For example, the following is the translation for \code{vector-ref}.
  15494. \begin{lstlisting}
  15495. (vector-ref |$e_1$| |$i$|)
  15496. |$\Rightarrow$|
  15497. (let ([|$v~e_1$|])
  15498. (if (proxy? |$v$|)
  15499. (proxy-vector-ref |$v$| |$i$|)
  15500. (vector-ref (project-vector |$v$|) |$i$|)
  15501. \end{lstlisting}
  15502. Note in the case of a real vector, we must apply \code{project-vector}
  15503. before the \code{vector-ref}.
  15504. \section{Reveal Casts}
  15505. \label{sec:reveal-casts-gradual}
  15506. Recall that the \code{reveal-casts} pass
  15507. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  15508. \code{Inject} and \code{Project} into lower-level operations. In
  15509. particular, \code{Project} turns into a conditional expression that
  15510. inspects the tag and retrieves the underlying value. Here we need to
  15511. augment the translation of \code{Project} to handle the situation when
  15512. the target type is \code{PVector}. Instead of using
  15513. \code{vector-length} we need to use \code{proxy-vector-length}.
  15514. \begin{lstlisting}
  15515. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  15516. |$\Rightarrow$|
  15517. (let |$\itm{tmp}$| |$e'$|
  15518. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  15519. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  15520. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  15521. (exit)))
  15522. \end{lstlisting}
  15523. \section{Closure Conversion}
  15524. \label{sec:closure-conversion-gradual}
  15525. The closure conversion pass only requires one minor adjustment. The
  15526. auxiliary function that translates type annotations needs to be
  15527. updated to handle the \code{PVector} type.
  15528. \section{Explicate Control}
  15529. \label{sec:explicate-control-gradual}
  15530. Update the \code{explicate\_control} pass to handle the new primitive
  15531. operations on the \code{PVector} type.
  15532. \section{Select Instructions}
  15533. \label{sec:select-instructions-gradual}
  15534. Recall that the \code{select\_instructions} pass is responsible for
  15535. lowering the primitive operations into x86 instructions. So we need
  15536. to translate the new \code{PVector} operations to x86. To do so, the
  15537. first question we need to answer is how will we differentiate the two
  15538. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  15539. We need just one bit to accomplish this, and use the bit in position
  15540. $57$ of the 64-bit tag at the front of every vector (see
  15541. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  15542. for \code{inject-vector} we leave it that way.
  15543. \begin{lstlisting}
  15544. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  15545. |$\Rightarrow$|
  15546. movq |$e'_1$|, |$\itm{lhs'}$|
  15547. \end{lstlisting}
  15548. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  15549. \begin{lstlisting}
  15550. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  15551. |$\Rightarrow$|
  15552. movq |$e'_1$|, %r11
  15553. movq |$(1 << 57)$|, %rax
  15554. orq 0(%r11), %rax
  15555. movq %rax, 0(%r11)
  15556. movq %r11, |$\itm{lhs'}$|
  15557. \end{lstlisting}
  15558. The \code{proxy?} operation consumes the information so carefully
  15559. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  15560. isolates the $57$th bit to tell whether the value is a real vector or
  15561. a proxy.
  15562. \begin{lstlisting}
  15563. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  15564. |$\Rightarrow$|
  15565. movq |$e_1'$|, %r11
  15566. movq 0(%r11), %rax
  15567. sarq $57, %rax
  15568. andq $1, %rax
  15569. movq %rax, |$\itm{lhs'}$|
  15570. \end{lstlisting}
  15571. The \code{project-vector} operation is straightforward to translate,
  15572. so we leave it up to the reader.
  15573. Regarding the \code{proxy-vector} operations, the runtime provides
  15574. procedures that implement them (they are recursive functions!) so
  15575. here we simply need to translate these vector operations into the
  15576. appropriate function call. For example, here is the translation for
  15577. \code{proxy-vector-ref}.
  15578. \begin{lstlisting}
  15579. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  15580. |$\Rightarrow$|
  15581. movq |$e_1'$|, %rdi
  15582. movq |$e_2'$|, %rsi
  15583. callq proxy_vector_ref
  15584. movq %rax, |$\itm{lhs'}$|
  15585. \end{lstlisting}
  15586. We have another batch of vector operations to deal with, those for the
  15587. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  15588. \code{any-vector-ref} when there is a \code{vector-ref} on something
  15589. of type \code{Any}, and similarly for \code{any-vector-set!} and
  15590. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  15591. Section~\ref{sec:select-Rany} we selected instructions for these
  15592. operations based on the idea that the underlying value was a real
  15593. vector. But in the current setting, the underlying value is of type
  15594. \code{PVector}. So \code{any-vector-ref} can be translates to
  15595. pseudo-x86 as follows. We begin by projecting the underlying value out
  15596. of the tagged value and then call the \code{proxy\_vector\_ref}
  15597. procedure in the runtime.
  15598. \begin{lstlisting}
  15599. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  15600. movq |$\neg 111$|, %rdi
  15601. andq |$e_1'$|, %rdi
  15602. movq |$e_2'$|, %rsi
  15603. callq proxy_vector_ref
  15604. movq %rax, |$\itm{lhs'}$|
  15605. \end{lstlisting}
  15606. The \code{any-vector-set!} and \code{any-vector-length} operators can
  15607. be translated in a similar way.
  15608. \begin{exercise}\normalfont
  15609. Implement a compiler for the gradually-typed \LangGrad{} language by
  15610. extending and adapting your compiler for \LangLoop{}. Create 10 new
  15611. partially-typed test programs. In addition to testing with these
  15612. new programs, also test your compiler on all the tests for \LangLoop{}
  15613. and tests for \LangDyn{}. Sometimes you may get a type checking error
  15614. on the \LangDyn{} programs but you can adapt them by inserting
  15615. a cast to the \code{Any} type around each subexpression
  15616. causing a type error. While \LangDyn{} doesn't have explicit casts,
  15617. you can induce one by wrapping the subexpression \code{e}
  15618. with a call to an un-annotated identity function, like this:
  15619. \code{((lambda (x) x) e)}.
  15620. \end{exercise}
  15621. \begin{figure}[p]
  15622. \begin{tikzpicture}[baseline=(current bounding box.center)]
  15623. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  15624. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  15625. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  15626. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  15627. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  15628. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  15629. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  15630. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  15631. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  15632. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  15633. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  15634. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  15635. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  15636. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  15637. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  15638. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  15639. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  15640. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  15641. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  15642. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  15643. \path[->,bend right=15] (Rgradual) edge [above] node
  15644. {\ttfamily\footnotesize type\_check} (Rgradualp);
  15645. \path[->,bend right=15] (Rgradualp) edge [above] node
  15646. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  15647. \path[->,bend right=15] (Rwhilepp) edge [right] node
  15648. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  15649. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  15650. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  15651. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  15652. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  15653. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  15654. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  15655. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  15656. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  15657. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  15658. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  15659. \path[->,bend left=15] (F1-1) edge [below] node
  15660. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15661. \path[->,bend right=15] (F1-2) edge [above] node
  15662. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15663. \path[->,bend right=15] (F1-3) edge [above] node
  15664. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  15665. \path[->,bend right=15] (F1-4) edge [above] node
  15666. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  15667. \path[->,bend right=15] (F1-5) edge [right] node
  15668. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15669. \path[->,bend left=15] (C3-2) edge [left] node
  15670. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15671. \path[->,bend right=15] (x86-2) edge [left] node
  15672. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15673. \path[->,bend right=15] (x86-2-1) edge [below] node
  15674. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15675. \path[->,bend right=15] (x86-2-2) edge [left] node
  15676. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15677. \path[->,bend left=15] (x86-3) edge [above] node
  15678. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15679. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  15680. \end{tikzpicture}
  15681. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  15682. \label{fig:Rgradual-passes}
  15683. \end{figure}
  15684. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  15685. for the compilation of \LangGrad{}.
  15686. \section{Further Reading}
  15687. This chapter just scratches the surface of gradual typing. The basic
  15688. approach described here is missing two key ingredients that one would
  15689. want in a implementation of gradual typing: blame
  15690. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  15691. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  15692. problem addressed by blame tracking is that when a cast on a
  15693. higher-order value fails, it often does so at a point in the program
  15694. that is far removed from the original cast. Blame tracking is a
  15695. technique for propagating extra information through casts and proxies
  15696. so that when a cast fails, the error message can point back to the
  15697. original location of the cast in the source program.
  15698. The problem addressed by space-efficient casts also relates to
  15699. higher-order casts. It turns out that in partially typed programs, a
  15700. function or vector can flow through very-many casts at runtime. With
  15701. the approach described in this chapter, each cast adds another
  15702. \code{lambda} wrapper or a vector proxy. Not only does this take up
  15703. considerable space, but it also makes the function calls and vector
  15704. operations slow. For example, a partially-typed version of quicksort
  15705. could, in the worst case, build a chain of proxies of length $O(n)$
  15706. around the vector, changing the overall time complexity of the
  15707. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  15708. solution to this problem by representing casts using the coercion
  15709. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  15710. long chains of proxies by compressing them into a concise normal
  15711. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  15712. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  15713. the Grift compiler.
  15714. \begin{center}
  15715. \url{https://github.com/Gradual-Typing/Grift}
  15716. \end{center}
  15717. There are also interesting interactions between gradual typing and
  15718. other language features, such as parametetric polymorphism,
  15719. information-flow types, and type inference, to name a few. We
  15720. recommend the reader to the online gradual typing bibliography:
  15721. \begin{center}
  15722. \url{http://samth.github.io/gradual-typing-bib/}
  15723. \end{center}
  15724. % TODO: challenge problem:
  15725. % type analysis and type specialization?
  15726. % coercions?
  15727. \fi
  15728. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15729. \chapter{Parametric Polymorphism}
  15730. \label{ch:Rpoly}
  15731. \index{subject}{parametric polymorphism}
  15732. \index{subject}{generics}
  15733. \if\edition\racketEd
  15734. This chapter studies the compilation of parametric
  15735. polymorphism\index{subject}{parametric polymorphism}
  15736. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  15737. Racket. Parametric polymorphism enables improved code reuse by
  15738. parameterizing functions and data structures with respect to the types
  15739. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  15740. revisits the \code{map-vec} example but this time gives it a more
  15741. fitting type. This \code{map-vec} function is parameterized with
  15742. respect to the element type of the vector. The type of \code{map-vec}
  15743. is the following polymorphic type as specified by the \code{All} and
  15744. the type parameter \code{a}.
  15745. \begin{lstlisting}
  15746. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  15747. \end{lstlisting}
  15748. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  15749. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  15750. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  15751. \code{a}, but we could have just as well applied \code{map-vec} to a
  15752. vector of Booleans (and a function on Booleans).
  15753. \begin{figure}[tbp]
  15754. % poly_test_2.rkt
  15755. \begin{lstlisting}
  15756. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  15757. (define (map-vec f v)
  15758. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  15759. (define (add1 [x : Integer]) : Integer (+ x 1))
  15760. (vector-ref (map-vec add1 (vector 0 41)) 1)
  15761. \end{lstlisting}
  15762. \caption{The \code{map-vec} example using parametric polymorphism.}
  15763. \label{fig:map-vec-poly}
  15764. \end{figure}
  15765. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  15766. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  15767. syntax. We add a second form for function definitions in which a type
  15768. declaration comes before the \code{define}. In the abstract syntax,
  15769. the return type in the \code{Def} is \code{Any}, but that should be
  15770. ignored in favor of the return type in the type declaration. (The
  15771. \code{Any} comes from using the same parser as in
  15772. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  15773. enables the use of an \code{All} type for a function, thereby making
  15774. it polymorphic. The grammar for types is extended to include
  15775. polymorphic types and type variables.
  15776. \begin{figure}[tp]
  15777. \centering
  15778. \fbox{
  15779. \begin{minipage}{0.96\textwidth}
  15780. \small
  15781. \[
  15782. \begin{array}{lcl}
  15783. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  15784. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  15785. &\MID& \LP\key{:}~\Var~\Type\RP \\
  15786. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  15787. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  15788. \end{array}
  15789. \]
  15790. \end{minipage}
  15791. }
  15792. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  15793. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  15794. \label{fig:Rpoly-concrete-syntax}
  15795. \end{figure}
  15796. \begin{figure}[tp]
  15797. \centering
  15798. \fbox{
  15799. \begin{minipage}{0.96\textwidth}
  15800. \small
  15801. \[
  15802. \begin{array}{lcl}
  15803. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  15804. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  15805. &\MID& \DECL{\Var}{\Type} \\
  15806. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  15807. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  15808. \end{array}
  15809. \]
  15810. \end{minipage}
  15811. }
  15812. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  15813. (Figure~\ref{fig:Lwhile-syntax}).}
  15814. \label{fig:Rpoly-syntax}
  15815. \end{figure}
  15816. By including polymorphic types in the $\Type$ non-terminal we choose
  15817. to make them first-class which has interesting repercussions on the
  15818. compiler. Many languages with polymorphism, such as
  15819. C++~\citep{stroustrup88:_param_types} and Standard
  15820. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  15821. it is useful to see an example of first-class polymorphism. In
  15822. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  15823. whose parameter is a polymorphic function. The occurrence of a
  15824. polymorphic type underneath a function type is enabled by the normal
  15825. recursive structure of the grammar for $\Type$ and the categorization
  15826. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  15827. applies the polymorphic function to a Boolean and to an integer.
  15828. \begin{figure}[tbp]
  15829. \begin{lstlisting}
  15830. (: apply-twice ((All (b) (b -> b)) -> Integer))
  15831. (define (apply-twice f)
  15832. (if (f #t) (f 42) (f 777)))
  15833. (: id (All (a) (a -> a)))
  15834. (define (id x) x)
  15835. (apply-twice id)
  15836. \end{lstlisting}
  15837. \caption{An example illustrating first-class polymorphism.}
  15838. \label{fig:apply-twice}
  15839. \end{figure}
  15840. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  15841. three new responsibilities (compared to \LangLoop{}). The type checking of
  15842. function application is extended to handle the case where the operator
  15843. expression is a polymorphic function. In that case the type arguments
  15844. are deduced by matching the type of the parameters with the types of
  15845. the arguments.
  15846. %
  15847. The \code{match-types} auxiliary function carries out this deduction
  15848. by recursively descending through a parameter type \code{pt} and the
  15849. corresponding argument type \code{at}, making sure that they are equal
  15850. except when there is a type parameter on the left (in the parameter
  15851. type). If it's the first time that the type parameter has been
  15852. encountered, then the algorithm deduces an association of the type
  15853. parameter to the corresponding type on the right (in the argument
  15854. type). If it's not the first time that the type parameter has been
  15855. encountered, the algorithm looks up its deduced type and makes sure
  15856. that it is equal to the type on the right.
  15857. %
  15858. Once the type arguments are deduced, the operator expression is
  15859. wrapped in an \code{Inst} AST node (for instantiate) that records the
  15860. type of the operator, but more importantly, records the deduced type
  15861. arguments. The return type of the application is the return type of
  15862. the polymorphic function, but with the type parameters replaced by the
  15863. deduced type arguments, using the \code{subst-type} function.
  15864. The second responsibility of the type checker is extending the
  15865. function \code{type-equal?} to handle the \code{All} type. This is
  15866. not quite a simple as equal on other types, such as function and
  15867. vector types, because two polymorphic types can be syntactically
  15868. different even though they are equivalent types. For example,
  15869. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  15870. Two polymorphic types should be considered equal if they differ only
  15871. in the choice of the names of the type parameters. The
  15872. \code{type-equal?} function in Figure~\ref{fig:type-check-Lvar0-aux}
  15873. renames the type parameters of the first type to match the type
  15874. parameters of the second type.
  15875. The third responsibility of the type checker is making sure that only
  15876. defined type variables appear in type annotations. The
  15877. \code{check-well-formed} function defined in
  15878. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  15879. sure that each type variable has been defined.
  15880. The output language of the type checker is \LangInst{}, defined in
  15881. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  15882. declaration and polymorphic function into a single definition, using
  15883. the \code{Poly} form, to make polymorphic functions more convenient to
  15884. process in next pass of the compiler.
  15885. \begin{figure}[tp]
  15886. \centering
  15887. \fbox{
  15888. \begin{minipage}{0.96\textwidth}
  15889. \small
  15890. \[
  15891. \begin{array}{lcl}
  15892. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  15893. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  15894. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  15895. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  15896. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  15897. \end{array}
  15898. \]
  15899. \end{minipage}
  15900. }
  15901. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  15902. (Figure~\ref{fig:Lwhile-syntax}).}
  15903. \label{fig:Rpoly-prime-syntax}
  15904. \end{figure}
  15905. The output of the type checker on the polymorphic \code{map-vec}
  15906. example is listed in Figure~\ref{fig:map-vec-type-check}.
  15907. \begin{figure}[tbp]
  15908. % poly_test_2.rkt
  15909. \begin{lstlisting}
  15910. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  15911. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  15912. (define (add1 [x : Integer]) : Integer (+ x 1))
  15913. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  15914. (Integer))
  15915. add1 (vector 0 41)) 1)
  15916. \end{lstlisting}
  15917. \caption{Output of the type checker on the \code{map-vec} example.}
  15918. \label{fig:map-vec-type-check}
  15919. \end{figure}
  15920. \begin{figure}[tbp]
  15921. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15922. (define type-check-poly-class
  15923. (class type-check-Rwhile-class
  15924. (super-new)
  15925. (inherit check-type-equal?)
  15926. (define/override (type-check-apply env e1 es)
  15927. (define-values (e^ ty) ((type-check-exp env) e1))
  15928. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  15929. ((type-check-exp env) e)))
  15930. (match ty
  15931. [`(,ty^* ... -> ,rt)
  15932. (for ([arg-ty ty*] [param-ty ty^*])
  15933. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  15934. (values e^ es^ rt)]
  15935. [`(All ,xs (,tys ... -> ,rt))
  15936. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  15937. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  15938. (match-types env^^ param-ty arg-ty)))
  15939. (define targs
  15940. (for/list ([x xs])
  15941. (match (dict-ref env^^ x (lambda () #f))
  15942. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  15943. x (Apply e1 es))]
  15944. [ty ty])))
  15945. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  15946. [else (error 'type-check "expected a function, not ~a" ty)]))
  15947. (define/override ((type-check-exp env) e)
  15948. (match e
  15949. [(Lambda `([,xs : ,Ts] ...) rT body)
  15950. (for ([T Ts]) ((check-well-formed env) T))
  15951. ((check-well-formed env) rT)
  15952. ((super type-check-exp env) e)]
  15953. [(HasType e1 ty)
  15954. ((check-well-formed env) ty)
  15955. ((super type-check-exp env) e)]
  15956. [else ((super type-check-exp env) e)]))
  15957. (define/override ((type-check-def env) d)
  15958. (verbose 'type-check "poly/def" d)
  15959. (match d
  15960. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  15961. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  15962. (for ([p ps]) ((check-well-formed ts-env) p))
  15963. ((check-well-formed ts-env) rt)
  15964. (define new-env (append ts-env (map cons xs ps) env))
  15965. (define-values (body^ ty^) ((type-check-exp new-env) body))
  15966. (check-type-equal? ty^ rt body)
  15967. (Generic ts (Def f p:t* rt info body^))]
  15968. [else ((super type-check-def env) d)]))
  15969. (define/override (type-check-program p)
  15970. (match p
  15971. [(Program info body)
  15972. (type-check-program (ProgramDefsExp info '() body))]
  15973. [(ProgramDefsExp info ds body)
  15974. (define ds^ (combine-decls-defs ds))
  15975. (define new-env (for/list ([d ds^])
  15976. (cons (def-name d) (fun-def-type d))))
  15977. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  15978. (define-values (body^ ty) ((type-check-exp new-env) body))
  15979. (check-type-equal? ty 'Integer body)
  15980. (ProgramDefsExp info ds^^ body^)]))
  15981. ))
  15982. \end{lstlisting}
  15983. \caption{Type checker for the \LangPoly{} language.}
  15984. \label{fig:type-check-Lvar0}
  15985. \end{figure}
  15986. \begin{figure}[tbp]
  15987. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15988. (define/override (type-equal? t1 t2)
  15989. (match* (t1 t2)
  15990. [(`(All ,xs ,T1) `(All ,ys ,T2))
  15991. (define env (map cons xs ys))
  15992. (type-equal? (subst-type env T1) T2)]
  15993. [(other wise)
  15994. (super type-equal? t1 t2)]))
  15995. (define/public (match-types env pt at)
  15996. (match* (pt at)
  15997. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  15998. [('Void 'Void) env] [('Any 'Any) env]
  15999. [(`(Vector ,pts ...) `(Vector ,ats ...))
  16000. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  16001. (match-types env^ pt1 at1))]
  16002. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  16003. (define env^ (match-types env prt art))
  16004. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  16005. (match-types env^^ pt1 at1))]
  16006. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  16007. (define env^ (append (map cons pxs axs) env))
  16008. (match-types env^ pt1 at1)]
  16009. [((? symbol? x) at)
  16010. (match (dict-ref env x (lambda () #f))
  16011. [#f (error 'type-check "undefined type variable ~a" x)]
  16012. ['Type (cons (cons x at) env)]
  16013. [t^ (check-type-equal? at t^ 'matching) env])]
  16014. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  16015. (define/public (subst-type env pt)
  16016. (match pt
  16017. ['Integer 'Integer] ['Boolean 'Boolean]
  16018. ['Void 'Void] ['Any 'Any]
  16019. [`(Vector ,ts ...)
  16020. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  16021. [`(,ts ... -> ,rt)
  16022. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  16023. [`(All ,xs ,t)
  16024. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  16025. [(? symbol? x) (dict-ref env x)]
  16026. [else (error 'type-check "expected a type not ~a" pt)]))
  16027. (define/public (combine-decls-defs ds)
  16028. (match ds
  16029. ['() '()]
  16030. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  16031. (unless (equal? name f)
  16032. (error 'type-check "name mismatch, ~a != ~a" name f))
  16033. (match type
  16034. [`(All ,xs (,ps ... -> ,rt))
  16035. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  16036. (cons (Generic xs (Def name params^ rt info body))
  16037. (combine-decls-defs ds^))]
  16038. [`(,ps ... -> ,rt)
  16039. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  16040. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  16041. [else (error 'type-check "expected a function type, not ~a" type) ])]
  16042. [`(,(Def f params rt info body) . ,ds^)
  16043. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  16044. \end{lstlisting}
  16045. \caption{Auxiliary functions for type checking \LangPoly{}.}
  16046. \label{fig:type-check-Lvar0-aux}
  16047. \end{figure}
  16048. \begin{figure}[tbp]
  16049. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  16050. (define/public ((check-well-formed env) ty)
  16051. (match ty
  16052. ['Integer (void)]
  16053. ['Boolean (void)]
  16054. ['Void (void)]
  16055. [(? symbol? a)
  16056. (match (dict-ref env a (lambda () #f))
  16057. ['Type (void)]
  16058. [else (error 'type-check "undefined type variable ~a" a)])]
  16059. [`(Vector ,ts ...)
  16060. (for ([t ts]) ((check-well-formed env) t))]
  16061. [`(,ts ... -> ,t)
  16062. (for ([t ts]) ((check-well-formed env) t))
  16063. ((check-well-formed env) t)]
  16064. [`(All ,xs ,t)
  16065. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  16066. ((check-well-formed env^) t)]
  16067. [else (error 'type-check "unrecognized type ~a" ty)]))
  16068. \end{lstlisting}
  16069. \caption{Well-formed types.}
  16070. \label{fig:well-formed-types}
  16071. \end{figure}
  16072. % TODO: interpreter for R'_10
  16073. \section{Compiling Polymorphism}
  16074. \label{sec:compiling-poly}
  16075. Broadly speaking, there are four approaches to compiling parametric
  16076. polymorphism, which we describe below.
  16077. \begin{description}
  16078. \item[Monomorphization] generates a different version of a polymorphic
  16079. function for each set of type arguments that it is used with,
  16080. producing type-specialized code. This approach results in the most
  16081. efficient code but requires whole-program compilation (no separate
  16082. compilation) and increases code size. For our current purposes
  16083. monomorphization is a non-starter because, with first-class
  16084. polymorphism, it is sometimes not possible to determine which
  16085. generic functions are used with which type arguments during
  16086. compilation. (It can be done at runtime, with just-in-time
  16087. compilation.) This approach is used to compile C++
  16088. templates~\citep{stroustrup88:_param_types} and polymorphic
  16089. functions in NESL~\citep{Blelloch:1993aa} and
  16090. ML~\citep{Weeks:2006aa}.
  16091. \item[Uniform representation] generates one version of each
  16092. polymorphic function but requires all values have a common ``boxed''
  16093. format, such as the tagged values of type \code{Any} in
  16094. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  16095. similarly to code in a dynamically typed language (like \LangDyn{}),
  16096. in which primitive operators require their arguments to be projected
  16097. from \code{Any} and their results are injected into \code{Any}. (In
  16098. object-oriented languages, the projection is accomplished via
  16099. virtual method dispatch.) The uniform representation approach is
  16100. compatible with separate compilation and with first-class
  16101. polymorphism. However, it produces the least-efficient code because
  16102. it introduces overhead in the entire program, including
  16103. non-polymorphic code. This approach is used in implementations of
  16104. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  16105. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  16106. Java~\citep{Bracha:1998fk}.
  16107. \item[Mixed representation] generates one version of each polymorphic
  16108. function, using a boxed representation for type
  16109. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  16110. and conversions are performed at the boundaries between monomorphic
  16111. and polymorphic (e.g. when a polymorphic function is instantiated
  16112. and called). This approach is compatible with separate compilation
  16113. and first-class polymorphism and maintains the efficiency of
  16114. monomorphic code. The tradeoff is increased overhead at the boundary
  16115. between monomorphic and polymorphic code. This approach is used in
  16116. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  16117. Java 5 with the addition of autoboxing.
  16118. \item[Type passing] uses the unboxed representation in both
  16119. monomorphic and polymorphic code. Each polymorphic function is
  16120. compiled to a single function with extra parameters that describe
  16121. the type arguments. The type information is used by the generated
  16122. code to know how to access the unboxed values at runtime. This
  16123. approach is used in implementation of the Napier88
  16124. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  16125. passing is compatible with separate compilation and first-class
  16126. polymorphism and maintains the efficiency for monomorphic
  16127. code. There is runtime overhead in polymorphic code from dispatching
  16128. on type information.
  16129. \end{description}
  16130. In this chapter we use the mixed representation approach, partly
  16131. because of its favorable attributes, and partly because it is
  16132. straightforward to implement using the tools that we have already
  16133. built to support gradual typing. To compile polymorphic functions, we
  16134. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  16135. \LangCast{}.
  16136. \section{Erase Types}
  16137. \label{sec:erase-types}
  16138. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  16139. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  16140. shows the output of the \code{erase-types} pass on the polymorphic
  16141. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  16142. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  16143. \code{All} types are removed from the type of \code{map-vec}.
  16144. \begin{figure}[tbp]
  16145. \begin{lstlisting}
  16146. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  16147. : (Vector Any Any)
  16148. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16149. (define (add1 [x : Integer]) : Integer (+ x 1))
  16150. (vector-ref ((cast map-vec
  16151. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  16152. ((Integer -> Integer) (Vector Integer Integer)
  16153. -> (Vector Integer Integer)))
  16154. add1 (vector 0 41)) 1)
  16155. \end{lstlisting}
  16156. \caption{The polymorphic \code{map-vec} example after type erasure.}
  16157. \label{fig:map-vec-erase}
  16158. \end{figure}
  16159. This process of type erasure creates a challenge at points of
  16160. instantiation. For example, consider the instantiation of
  16161. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  16162. The type of \code{map-vec} is
  16163. \begin{lstlisting}
  16164. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  16165. \end{lstlisting}
  16166. and it is instantiated to
  16167. \begin{lstlisting}
  16168. ((Integer -> Integer) (Vector Integer Integer)
  16169. -> (Vector Integer Integer))
  16170. \end{lstlisting}
  16171. After erasure, the type of \code{map-vec} is
  16172. \begin{lstlisting}
  16173. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  16174. \end{lstlisting}
  16175. but we need to convert it to the instantiated type. This is easy to
  16176. do in the target language \LangCast{} with a single \code{cast}. In
  16177. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  16178. has been compiled to a \code{cast} from the type of \code{map-vec} to
  16179. the instantiated type. The source and target type of a cast must be
  16180. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  16181. because both the source and target are obtained from the same
  16182. polymorphic type of \code{map-vec}, replacing the type parameters with
  16183. \code{Any} in the former and with the deduced type arguments in the
  16184. later. (Recall that the \code{Any} type is consistent with any type.)
  16185. To implement the \code{erase-types} pass, we recommend defining a
  16186. recursive auxiliary function named \code{erase-type} that applies the
  16187. following two transformations. It replaces type variables with
  16188. \code{Any}
  16189. \begin{lstlisting}
  16190. |$x$|
  16191. |$\Rightarrow$|
  16192. Any
  16193. \end{lstlisting}
  16194. and it removes the polymorphic \code{All} types.
  16195. \begin{lstlisting}
  16196. (All |$xs$| |$T_1$|)
  16197. |$\Rightarrow$|
  16198. |$T'_1$|
  16199. \end{lstlisting}
  16200. Apply the \code{erase-type} function to all of the type annotations in
  16201. the program.
  16202. Regarding the translation of expressions, the case for \code{Inst} is
  16203. the interesting one. We translate it into a \code{Cast}, as shown
  16204. below. The type of the subexpression $e$ is the polymorphic type
  16205. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  16206. $T$, the type $T'$. The target type $T''$ is the result of
  16207. substituting the arguments types $ts$ for the type parameters $xs$ in
  16208. $T$ followed by doing type erasure.
  16209. \begin{lstlisting}
  16210. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  16211. |$\Rightarrow$|
  16212. (Cast |$e'$| |$T'$| |$T''$|)
  16213. \end{lstlisting}
  16214. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  16215. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  16216. Finally, each polymorphic function is translated to a regular
  16217. functions in which type erasure has been applied to all the type
  16218. annotations and the body.
  16219. \begin{lstlisting}
  16220. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  16221. |$\Rightarrow$|
  16222. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  16223. \end{lstlisting}
  16224. \begin{exercise}\normalfont
  16225. Implement a compiler for the polymorphic language \LangPoly{} by
  16226. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  16227. programs that use polymorphic functions. Some of them should make
  16228. use of first-class polymorphism.
  16229. \end{exercise}
  16230. \begin{figure}[p]
  16231. \begin{tikzpicture}[baseline=(current bounding box.center)]
  16232. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  16233. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  16234. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  16235. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  16236. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  16237. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  16238. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  16239. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  16240. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  16241. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  16242. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  16243. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  16244. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  16245. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  16246. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  16247. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  16248. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  16249. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  16250. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  16251. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  16252. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  16253. \path[->,bend right=15] (Rpoly) edge [above] node
  16254. {\ttfamily\footnotesize type\_check} (Rpolyp);
  16255. \path[->,bend right=15] (Rpolyp) edge [above] node
  16256. {\ttfamily\footnotesize erase\_types} (Rgradualp);
  16257. \path[->,bend right=15] (Rgradualp) edge [above] node
  16258. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  16259. \path[->,bend right=15] (Rwhilepp) edge [right] node
  16260. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  16261. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  16262. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  16263. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  16264. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  16265. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  16266. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  16267. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  16268. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  16269. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  16270. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16271. \path[->,bend left=15] (F1-1) edge [below] node
  16272. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  16273. \path[->,bend right=15] (F1-2) edge [above] node
  16274. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  16275. \path[->,bend right=15] (F1-3) edge [above] node
  16276. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  16277. \path[->,bend right=15] (F1-4) edge [above] node
  16278. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  16279. \path[->,bend right=15] (F1-5) edge [right] node
  16280. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16281. \path[->,bend left=15] (C3-2) edge [left] node
  16282. {\ttfamily\footnotesize select\_instr.} (x86-2);
  16283. \path[->,bend right=15] (x86-2) edge [left] node
  16284. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16285. \path[->,bend right=15] (x86-2-1) edge [below] node
  16286. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  16287. \path[->,bend right=15] (x86-2-2) edge [left] node
  16288. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  16289. \path[->,bend left=15] (x86-3) edge [above] node
  16290. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  16291. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  16292. \end{tikzpicture}
  16293. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  16294. \label{fig:Rpoly-passes}
  16295. \end{figure}
  16296. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  16297. for the compilation of \LangPoly{}.
  16298. % TODO: challenge problem: specialization of instantiations
  16299. % Further Reading
  16300. \fi
  16301. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16302. \clearpage
  16303. \appendix
  16304. \chapter{Appendix}
  16305. \if\edition\racketEd
  16306. \section{Interpreters}
  16307. \label{appendix:interp}
  16308. \index{subject}{interpreter}
  16309. We provide interpreters for each of the source languages \LangInt{},
  16310. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  16311. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  16312. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  16313. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  16314. and x86 are in the \key{interp.rkt} file.
  16315. \section{Utility Functions}
  16316. \label{appendix:utilities}
  16317. The utility functions described in this section are in the
  16318. \key{utilities.rkt} file of the support code.
  16319. \paragraph{\code{interp-tests}}
  16320. The \key{interp-tests} function runs the compiler passes and the
  16321. interpreters on each of the specified tests to check whether each pass
  16322. is correct. The \key{interp-tests} function has the following
  16323. parameters:
  16324. \begin{description}
  16325. \item[name (a string)] a name to identify the compiler,
  16326. \item[typechecker] a function of exactly one argument that either
  16327. raises an error using the \code{error} function when it encounters a
  16328. type error, or returns \code{\#f} when it encounters a type
  16329. error. If there is no type error, the type checker returns the
  16330. program.
  16331. \item[passes] a list with one entry per pass. An entry is a list with
  16332. four things:
  16333. \begin{enumerate}
  16334. \item a string giving the name of the pass,
  16335. \item the function that implements the pass (a translator from AST
  16336. to AST),
  16337. \item a function that implements the interpreter (a function from
  16338. AST to result value) for the output language,
  16339. \item and a type checker for the output language. Type checkers for
  16340. the $R$ and $C$ languages are provided in the support code. For
  16341. example, the type checkers for \LangVar{} and \LangCVar{} are in
  16342. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  16343. type checker entry is optional. The support code does not provide
  16344. type checkers for the x86 languages.
  16345. \end{enumerate}
  16346. \item[source-interp] an interpreter for the source language. The
  16347. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  16348. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  16349. \item[tests] a list of test numbers that specifies which tests to
  16350. run. (see below)
  16351. \end{description}
  16352. %
  16353. The \key{interp-tests} function assumes that the subdirectory
  16354. \key{tests} has a collection of Racket programs whose names all start
  16355. with the family name, followed by an underscore and then the test
  16356. number, ending with the file extension \key{.rkt}. Also, for each test
  16357. program that calls \code{read} one or more times, there is a file with
  16358. the same name except that the file extension is \key{.in} that
  16359. provides the input for the Racket program. If the test program is
  16360. expected to fail type checking, then there should be an empty file of
  16361. the same name but with extension \key{.tyerr}.
  16362. \paragraph{\code{compiler-tests}}
  16363. runs the compiler passes to generate x86 (a \key{.s} file) and then
  16364. runs the GNU C compiler (gcc) to generate machine code. It runs the
  16365. machine code and checks that the output is $42$. The parameters to the
  16366. \code{compiler-tests} function are similar to those of the
  16367. \code{interp-tests} function, and consist of
  16368. \begin{itemize}
  16369. \item a compiler name (a string),
  16370. \item a type checker,
  16371. \item description of the passes,
  16372. \item name of a test-family, and
  16373. \item a list of test numbers.
  16374. \end{itemize}
  16375. \paragraph{\code{compile-file}}
  16376. takes a description of the compiler passes (see the comment for
  16377. \key{interp-tests}) and returns a function that, given a program file
  16378. name (a string ending in \key{.rkt}), applies all of the passes and
  16379. writes the output to a file whose name is the same as the program file
  16380. name but with \key{.rkt} replaced with \key{.s}.
  16381. \paragraph{\code{read-program}}
  16382. takes a file path and parses that file (it must be a Racket program)
  16383. into an abstract syntax tree.
  16384. \paragraph{\code{parse-program}}
  16385. takes an S-expression representation of an abstract syntax tree and converts it into
  16386. the struct-based representation.
  16387. \paragraph{\code{assert}}
  16388. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  16389. and displays the message \key{msg} if the Boolean \key{bool} is false.
  16390. \paragraph{\code{lookup}}
  16391. % remove discussion of lookup? -Jeremy
  16392. takes a key and an alist, and returns the first value that is
  16393. associated with the given key, if there is one. If not, an error is
  16394. triggered. The alist may contain both immutable pairs (built with
  16395. \key{cons}) and mutable pairs (built with \key{mcons}).
  16396. %The \key{map2} function ...
  16397. \fi %\racketEd
  16398. \section{x86 Instruction Set Quick-Reference}
  16399. \label{sec:x86-quick-reference}
  16400. \index{subject}{x86}
  16401. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  16402. do. We write $A \to B$ to mean that the value of $A$ is written into
  16403. location $B$. Address offsets are given in bytes. The instruction
  16404. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  16405. registers (such as \code{\%rax}), or memory references (such as
  16406. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  16407. reference per instruction. Other operands must be immediates or
  16408. registers.
  16409. \begin{table}[tbp]
  16410. \centering
  16411. \begin{tabular}{l|l}
  16412. \textbf{Instruction} & \textbf{Operation} \\ \hline
  16413. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  16414. \texttt{negq} $A$ & $- A \to A$ \\
  16415. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  16416. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  16417. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  16418. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  16419. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  16420. \texttt{retq} & Pops the return address and jumps to it \\
  16421. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  16422. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  16423. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  16424. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  16425. be an immediate) \\
  16426. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  16427. matches the condition code of the instruction, otherwise go to the
  16428. next instructions. The condition codes are \key{e} for ``equal'',
  16429. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  16430. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  16431. \texttt{jl} $L$ & \\
  16432. \texttt{jle} $L$ & \\
  16433. \texttt{jg} $L$ & \\
  16434. \texttt{jge} $L$ & \\
  16435. \texttt{jmp} $L$ & Jump to label $L$ \\
  16436. \texttt{movq} $A$, $B$ & $A \to B$ \\
  16437. \texttt{movzbq} $A$, $B$ &
  16438. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  16439. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  16440. and the extra bytes of $B$ are set to zero.} \\
  16441. & \\
  16442. & \\
  16443. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  16444. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  16445. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  16446. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  16447. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  16448. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  16449. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  16450. description of the condition codes. $A$ must be a single byte register
  16451. (e.g., \texttt{al} or \texttt{cl}).} \\
  16452. \texttt{setl} $A$ & \\
  16453. \texttt{setle} $A$ & \\
  16454. \texttt{setg} $A$ & \\
  16455. \texttt{setge} $A$ &
  16456. \end{tabular}
  16457. \vspace{5pt}
  16458. \caption{Quick-reference for the x86 instructions used in this book.}
  16459. \label{tab:x86-instr}
  16460. \end{table}
  16461. \if\edition\racketEd
  16462. \cleardoublepage
  16463. \section{Concrete Syntax for Intermediate Languages}
  16464. The concrete syntax of \LangAny{} is defined in
  16465. Figure~\ref{fig:Rany-concrete-syntax}.
  16466. \begin{figure}[tp]
  16467. \centering
  16468. \fbox{
  16469. \begin{minipage}{0.97\textwidth}\small
  16470. \[
  16471. \begin{array}{lcl}
  16472. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  16473. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  16474. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \key{Any} \\
  16475. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  16476. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  16477. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  16478. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  16479. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  16480. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  16481. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  16482. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  16483. \MID \LP\key{void?}\;\Exp\RP \\
  16484. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  16485. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  16486. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  16487. \end{array}
  16488. \]
  16489. \end{minipage}
  16490. }
  16491. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  16492. (Figure~\ref{fig:Rlam-syntax}).}
  16493. \label{fig:Rany-concrete-syntax}
  16494. \end{figure}
  16495. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  16496. defined in Figures~\ref{fig:c0-concrete-syntax},
  16497. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  16498. and \ref{fig:c3-concrete-syntax}, respectively.
  16499. \begin{figure}[tbp]
  16500. \fbox{
  16501. \begin{minipage}{0.96\textwidth}
  16502. \small
  16503. \[
  16504. \begin{array}{lcl}
  16505. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  16506. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  16507. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  16508. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  16509. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  16510. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  16511. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  16512. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  16513. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  16514. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  16515. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  16516. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  16517. \end{array}
  16518. \]
  16519. \end{minipage}
  16520. }
  16521. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  16522. \label{fig:c2-concrete-syntax}
  16523. \end{figure}
  16524. \begin{figure}[tp]
  16525. \fbox{
  16526. \begin{minipage}{0.96\textwidth}
  16527. \small
  16528. \[
  16529. \begin{array}{lcl}
  16530. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  16531. \\
  16532. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  16533. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  16534. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  16535. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  16536. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  16537. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  16538. &\MID& \LP\key{fun-ref}~\itm{label}\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  16539. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  16540. \MID \LP\key{collect} \,\itm{int}\RP }\\
  16541. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  16542. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  16543. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  16544. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  16545. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  16546. \LangCFunM{} & ::= & \Def\ldots
  16547. \end{array}
  16548. \]
  16549. \end{minipage}
  16550. }
  16551. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  16552. \label{fig:c3-concrete-syntax}
  16553. \end{figure}
  16554. \fi % racketEd
  16555. \backmatter
  16556. \addtocontents{toc}{\vspace{11pt}}
  16557. %% \addtocontents{toc}{\vspace{11pt}}
  16558. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  16559. \nocite{*}\let\bibname\refname
  16560. \addcontentsline{toc}{fmbm}{\refname}
  16561. \printbibliography
  16562. \printindex{authors}{Author Index}
  16563. \printindex{subject}{Subject Index}
  16564. \end{document}
  16565. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  16566. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  16567. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  16568. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  16569. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  16570. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  16571. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  16572. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  16573. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  16574. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  16575. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  16576. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  16577. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  16578. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  16579. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  16580. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  16581. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  16582. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  16583. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS
  16584. % LocalWords: morekeywords fullflexible