book.tex 665 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750
  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, Cameron Swords, and Chris
  365. Wailes. We thank Andre Kuhlenschmidt for work on the garbage
  366. collector, Michael Vollmer for work on efficient tail calls, and
  367. Michael Vitousek for help running the first offering of the
  368. incremental compiler course at IU.
  369. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  370. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  371. Michael Wollowski for teaching courses based on drafts of this book
  372. and for their 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 \CREAD \RP \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  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{\LvarASTRacket}{
  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. \LvarASTRacket \\
  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& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2360. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \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. \newcommand{\CvarGrammarRacket}{
  2569. \begin{array}{lcl}
  2570. \Atm &::=& \Int \MID \Var \\
  2571. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2572. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2573. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2574. \end{array}
  2575. }
  2576. \newcommand{\CvarASTRacket}{
  2577. \begin{array}{lcl}
  2578. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2579. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2580. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2581. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2582. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2583. \end{array}
  2584. }
  2585. {\if\edition\racketEd
  2586. \subsection{The \LangCVar{} Intermediate Language}
  2587. The output of \code{explicate\_control} is similar to the $C$
  2588. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2589. categories for expressions and statements, so we name it \LangCVar{}.
  2590. This style of intermediate language is also known as
  2591. \emph{three-address code}, to emphasize that the typical form of a
  2592. statement is \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2593. addresses~\citep{Aho:2006wb}.
  2594. The concrete syntax for \LangCVar{} is defined in
  2595. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for
  2596. \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2597. %
  2598. The \LangCVar{} language supports the same operators as \LangVar{} but
  2599. the arguments of operators are restricted to atomic
  2600. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2601. assignment statements which can be executed in sequence using the
  2602. \key{Seq} form. A sequence of statements always ends with
  2603. \key{Return}, a guarantee that is baked into the grammar rules for
  2604. \itm{tail}. The naming of this non-terminal comes from the term
  2605. \emph{tail position}\index{subject}{tail position}, which refers to an
  2606. expression that is the last one to execute within a function.
  2607. A \LangCVar{} program consists of an alist mapping labels to
  2608. tails. This is more general than necessary for the present chapter, as
  2609. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2610. us from having to change the syntax in Chapter~\ref{ch:Lif}. For now
  2611. there will be just one label, \key{start}, and the whole program is
  2612. its tail.
  2613. %
  2614. The $\itm{info}$ field of the \key{CProgram} form, after the
  2615. \code{explicate\_control} pass, contains a mapping from the symbol
  2616. \key{locals} to a list of variables, that is, a list of all the
  2617. variables used in the program. At the start of the program, these
  2618. variables are uninitialized; they become initialized on their first
  2619. assignment.
  2620. \begin{figure}[tbp]
  2621. \fbox{
  2622. \begin{minipage}{0.96\textwidth}
  2623. \[
  2624. \begin{array}{l}
  2625. \CvarGrammarRacket \\
  2626. \begin{array}{lcl}
  2627. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2628. \end{array}
  2629. \end{array}
  2630. \]
  2631. \end{minipage}
  2632. }
  2633. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2634. \label{fig:c0-concrete-syntax}
  2635. \end{figure}
  2636. \begin{figure}[tbp]
  2637. \fbox{
  2638. \begin{minipage}{0.96\textwidth}
  2639. \[
  2640. \begin{array}{l}
  2641. \CvarASTRacket \\
  2642. \begin{array}{lcl}
  2643. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2644. \end{array}
  2645. \end{array}
  2646. \]
  2647. \end{minipage}
  2648. }
  2649. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2650. \label{fig:c0-syntax}
  2651. \end{figure}
  2652. The definitional interpreter for \LangCVar{} is in the support code,
  2653. in the file \code{interp-Cvar.rkt}.
  2654. \fi}
  2655. {\if\edition\racketEd
  2656. \section{Uniquify Variables}
  2657. \label{sec:uniquify-Lvar}
  2658. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2659. programs in which every \key{let} binds a unique variable name. For
  2660. example, the \code{uniquify} pass should translate the program on the
  2661. left into the program on the right.
  2662. \begin{transformation}
  2663. \begin{lstlisting}
  2664. (let ([x 32])
  2665. (+ (let ([x 10]) x) x))
  2666. \end{lstlisting}
  2667. \compilesto
  2668. \begin{lstlisting}
  2669. (let ([x.1 32])
  2670. (+ (let ([x.2 10]) x.2) x.1))
  2671. \end{lstlisting}
  2672. \end{transformation}
  2673. The following is another example translation, this time of a program
  2674. with a \key{let} nested inside the initializing expression of another
  2675. \key{let}.
  2676. \begin{transformation}
  2677. \begin{lstlisting}
  2678. (let ([x (let ([x 4])
  2679. (+ x 1))])
  2680. (+ x 2))
  2681. \end{lstlisting}
  2682. \compilesto
  2683. \begin{lstlisting}
  2684. (let ([x.2 (let ([x.1 4])
  2685. (+ x.1 1))])
  2686. (+ x.2 2))
  2687. \end{lstlisting}
  2688. \end{transformation}
  2689. We recommend implementing \code{uniquify} by creating a structurally
  2690. recursive function named \code{uniquify-exp} that mostly just copies
  2691. an expression. However, when encountering a \key{let}, it should
  2692. generate a unique name for the variable and associate the old name
  2693. with the new name in an alist.\footnote{The Racket function
  2694. \code{gensym} is handy for generating unique variable names.} The
  2695. \code{uniquify-exp} function needs to access this alist when it gets
  2696. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2697. for the alist.
  2698. The skeleton of the \code{uniquify-exp} function is shown in
  2699. Figure~\ref{fig:uniquify-Lvar}. The function is curried so that it is
  2700. convenient to partially apply it to an alist and then apply it to
  2701. different expressions, as in the last case for primitive operations in
  2702. Figure~\ref{fig:uniquify-Lvar}. The
  2703. %
  2704. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2705. %
  2706. form of Racket is useful for transforming each element of a list to
  2707. produce a new list.\index{subject}{for/list}
  2708. \begin{figure}[tbp]
  2709. \begin{lstlisting}
  2710. (define (uniquify-exp env)
  2711. (lambda (e)
  2712. (match e
  2713. [(Var x) ___]
  2714. [(Int n) (Int n)]
  2715. [(Let x e body) ___]
  2716. [(Prim op es)
  2717. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2718. (define (uniquify p)
  2719. (match p
  2720. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2721. \end{lstlisting}
  2722. \caption{Skeleton for the \key{uniquify} pass.}
  2723. \label{fig:uniquify-Lvar}
  2724. \end{figure}
  2725. \begin{exercise}
  2726. \normalfont % I don't like the italics for exercises. -Jeremy
  2727. Complete the \code{uniquify} pass by filling in the blanks in
  2728. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2729. variables and for the \key{let} form in the file \code{compiler.rkt}
  2730. in the support code.
  2731. \end{exercise}
  2732. \begin{exercise}
  2733. \normalfont % I don't like the italics for exercises. -Jeremy
  2734. \label{ex:Lvar}
  2735. Create five \LangVar{} programs that exercise the most interesting
  2736. parts of the \key{uniquify} pass, that is, the programs should include
  2737. \key{let} forms, variables, and variables that shadow each other.
  2738. The five programs should be placed in the subdirectory named
  2739. \key{tests} and the file names should start with \code{var\_test\_}
  2740. followed by a unique integer and end with the file extension
  2741. \key{.rkt}.
  2742. %
  2743. The \key{run-tests.rkt} script in the support code checks whether the
  2744. output programs produce the same result as the input programs. The
  2745. script uses the \key{interp-tests} function
  2746. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2747. your \key{uniquify} pass on the example programs. The \code{passes}
  2748. parameter of \key{interp-tests} is a list that should have one entry
  2749. for each pass in your compiler. For now, define \code{passes} to
  2750. contain just one entry for \code{uniquify} as shown below.
  2751. \begin{lstlisting}
  2752. (define passes
  2753. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2754. \end{lstlisting}
  2755. Run the \key{run-tests.rkt} script in the support code to check
  2756. whether the output programs produce the same result as the input
  2757. programs.
  2758. \end{exercise}
  2759. \fi}
  2760. \section{Remove Complex Operands}
  2761. \label{sec:remove-complex-opera-Lvar}
  2762. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2763. into a restricted form in which the arguments of operations are atomic
  2764. expressions. Put another way, this pass removes complex
  2765. operands\index{subject}{complex operand}, such as the expression
  2766. \racket{\code{(- 10)}}\python{\code{-10}}
  2767. in the program below. This is accomplished by introducing a new
  2768. temporary variable, assigning the complex operand to the new
  2769. variable, and then using the new variable in place of the complex
  2770. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2771. right.
  2772. {\if\edition\racketEd
  2773. \begin{transformation}
  2774. % var_test_19.rkt
  2775. \begin{lstlisting}
  2776. (let ([x (+ 42 (- 10))])
  2777. (+ x 10))
  2778. \end{lstlisting}
  2779. \compilesto
  2780. \begin{lstlisting}
  2781. (let ([x (let ([tmp.1 (- 10)])
  2782. (+ 42 tmp.1))])
  2783. (+ x 10))
  2784. \end{lstlisting}
  2785. \end{transformation}
  2786. \fi}
  2787. {\if\edition\pythonEd
  2788. \begin{transformation}
  2789. \begin{lstlisting}
  2790. x = 42 + -10
  2791. print(x + 10)
  2792. \end{lstlisting}
  2793. \compilesto
  2794. \begin{lstlisting}
  2795. tmp_0 = -10
  2796. x = 42 + tmp_0
  2797. tmp_1 = x + 10
  2798. print(tmp_1)
  2799. \end{lstlisting}
  2800. \end{transformation}
  2801. \fi}
  2802. \begin{figure}[tp]
  2803. \centering
  2804. \fbox{
  2805. \begin{minipage}{0.96\textwidth}
  2806. {\if\edition\racketEd
  2807. \[
  2808. \begin{array}{rcl}
  2809. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2810. \Exp &::=& \Atm \MID \READ{} \\
  2811. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2812. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2813. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2814. \end{array}
  2815. \]
  2816. \fi}
  2817. {\if\edition\pythonEd
  2818. \[
  2819. \begin{array}{rcl}
  2820. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2821. \Exp{} &::=& \Atm \MID \READ{} \\
  2822. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2823. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2824. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  2825. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2826. \end{array}
  2827. \]
  2828. \fi}
  2829. \end{minipage}
  2830. }
  2831. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2832. atomic expressions.}
  2833. \label{fig:Lvar-anf-syntax}
  2834. \end{figure}
  2835. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2836. of this pass, the language \LangVarANF{}. The only difference is that
  2837. operator arguments are restricted to be atomic expressions that are
  2838. defined by the \Atm{} non-terminal. In particular, integer constants
  2839. and variables are atomic.
  2840. The atomic expressions are pure (they do not cause side-effects or
  2841. depend on them) whereas complex expressions may have side effects,
  2842. such as \READ{}. A language with this separation between pure versus
  2843. side-effecting expressions is said to be in monadic normal
  2844. form~\citep{Moggi:1991in,Danvy:2003fk} which explains the \textit{mon}
  2845. in \LangVarANF{}. An important invariant of the
  2846. \code{remove\_complex\_operands} pass is that the relative ordering
  2847. among complex expressions is not changed, but the relative ordering
  2848. between atomic expressions and complex expressions can change and
  2849. often does. The reason that these changes are behaviour preserving is
  2850. that the atomic expressions are pure.
  2851. Another well-known form for intermediate languages is the
  2852. \emph{administrative normal form}
  2853. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2854. \index{subject}{administrative normal form} \index{subject}{ANF}
  2855. %
  2856. The \LangVarANF{} language is not quite in ANF because we allow the
  2857. right-hand side of a \code{let} to be a complex expression.
  2858. {\if\edition\racketEd
  2859. We recommend implementing this pass with two mutually recursive
  2860. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2861. \code{rco\_atom} to subexpressions that need to become atomic and to
  2862. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2863. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2864. returns an expression. The \code{rco\_atom} function returns two
  2865. things: an atomic expression and an alist mapping temporary variables to
  2866. complex subexpressions. You can return multiple things from a function
  2867. using Racket's \key{values} form and you can receive multiple things
  2868. from a function call using the \key{define-values} form.
  2869. Also, the
  2870. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2871. form is useful for applying a function to each element of a list, in
  2872. the case where the function returns multiple values.
  2873. \index{subject}{for/lists}
  2874. \fi}
  2875. %
  2876. {\if\edition\pythonEd
  2877. %
  2878. We recommend implementing this pass with an auxiliary method named
  2879. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2880. Boolean that specifies whether the expression needs to become atomic
  2881. or not. The \code{rco\_exp} method should return a pair consisting of
  2882. the new expression and a list of pairs, associating new temporary
  2883. variables with their initializing expressions.
  2884. %
  2885. \fi}
  2886. {\if\edition\racketEd
  2887. Returning to the example program with the expression \code{(+ 42 (-
  2888. 10))}, the subexpression \code{(- 10)} should be processed using the
  2889. \code{rco\_atom} function because it is an argument of the \code{+} and
  2890. therefore needs to become atomic. The output of \code{rco\_atom}
  2891. applied to \code{(- 10)} is as follows.
  2892. \begin{transformation}
  2893. \begin{lstlisting}
  2894. (- 10)
  2895. \end{lstlisting}
  2896. \compilesto
  2897. \begin{lstlisting}
  2898. tmp.1
  2899. ((tmp.1 . (- 10)))
  2900. \end{lstlisting}
  2901. \end{transformation}
  2902. \fi}
  2903. %
  2904. {\if\edition\pythonEd
  2905. %
  2906. Returning to the example program with the expression \code{42 + -10},
  2907. the subexpression \code{-10} should be processed using the
  2908. \code{rco\_exp} function with \code{True} as the second argument
  2909. because \code{-10} is an argument of the \code{+} operator and
  2910. therefore needs to become atomic. The output of \code{rco\_exp}
  2911. applied to \code{-10} is as follows.
  2912. \begin{transformation}
  2913. \begin{lstlisting}
  2914. -10
  2915. \end{lstlisting}
  2916. \compilesto
  2917. \begin{lstlisting}
  2918. tmp_1
  2919. [(tmp_1, -10)]
  2920. \end{lstlisting}
  2921. \end{transformation}
  2922. %
  2923. \fi}
  2924. Take special care of programs such as the following that
  2925. %
  2926. \racket{bind a variable to an atomic expression}
  2927. %
  2928. \python{assign an atomic expression to a variable}.
  2929. %
  2930. You should leave such \racket{variable bindings}\python{assignments}
  2931. unchanged, as shown in the program on the right\\
  2932. %
  2933. {\if\edition\racketEd
  2934. \begin{transformation}
  2935. % var_test_20.rkt
  2936. \begin{lstlisting}
  2937. (let ([a 42])
  2938. (let ([b a])
  2939. b))
  2940. \end{lstlisting}
  2941. \compilesto
  2942. \begin{lstlisting}
  2943. (let ([a 42])
  2944. (let ([b a])
  2945. b))
  2946. \end{lstlisting}
  2947. \end{transformation}
  2948. \fi}
  2949. {\if\edition\pythonEd
  2950. \begin{transformation}
  2951. \begin{lstlisting}
  2952. a = 42
  2953. b = a
  2954. print(b)
  2955. \end{lstlisting}
  2956. \compilesto
  2957. \begin{lstlisting}
  2958. a = 42
  2959. b = a
  2960. print(b)
  2961. \end{lstlisting}
  2962. \end{transformation}
  2963. \fi}
  2964. %
  2965. \noindent A careless implementation might produce the following output with
  2966. unnecessary temporary variables.
  2967. \begin{center}
  2968. \begin{minipage}{0.4\textwidth}
  2969. {\if\edition\racketEd
  2970. \begin{lstlisting}
  2971. (let ([tmp.1 42])
  2972. (let ([a tmp.1])
  2973. (let ([tmp.2 a])
  2974. (let ([b tmp.2])
  2975. b))))
  2976. \end{lstlisting}
  2977. \fi}
  2978. {\if\edition\pythonEd
  2979. \begin{lstlisting}
  2980. tmp_1 = 42
  2981. a = tmp_1
  2982. tmp_2 = a
  2983. b = tmp_2
  2984. print(b)
  2985. \end{lstlisting}
  2986. \fi}
  2987. \end{minipage}
  2988. \end{center}
  2989. \begin{exercise}
  2990. \normalfont
  2991. {\if\edition\racketEd
  2992. Implement the \code{remove\_complex\_operands} function in
  2993. \code{compiler.rkt}.
  2994. %
  2995. Create three new \LangVar{} programs that exercise the interesting
  2996. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  2997. regarding file names described in Exercise~\ref{ex:Lvar}.
  2998. %
  2999. In the \code{run-tests.rkt} script, add the following entry to the
  3000. list of \code{passes} and then run the script to test your compiler.
  3001. \begin{lstlisting}
  3002. (list "remove-complex" remove-complex-opera* interp_Lvar type-check-Lvar)
  3003. \end{lstlisting}
  3004. While debugging your compiler, it is often useful to see the
  3005. intermediate programs that are output from each pass. To print the
  3006. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  3007. \code{interp-tests} in \code{run-tests.rkt}.
  3008. \fi}
  3009. %
  3010. {\if\edition\pythonEd
  3011. Implement the \code{remove\_complex\_operands} pass in
  3012. \code{compiler.py}, creating auxiliary functions for each
  3013. non-terminal in the grammar, i.e., \code{rco\_exp}
  3014. and \code{rco\_stmt}.
  3015. \fi}
  3016. \end{exercise}
  3017. {\if\edition\pythonEd
  3018. \begin{exercise}
  3019. \normalfont % I don't like the italics for exercises. -Jeremy
  3020. \label{ex:Lvar}
  3021. Create five \LangVar{} programs that exercise the most interesting
  3022. parts of the \code{remove\_complex\_operands} pass. The five programs
  3023. should be placed in the subdirectory named \key{tests} and the file
  3024. names should start with \code{var\_test\_} followed by a unique
  3025. integer and end with the file extension \key{.py}.
  3026. %% The \key{run-tests.rkt} script in the support code checks whether the
  3027. %% output programs produce the same result as the input programs. The
  3028. %% script uses the \key{interp-tests} function
  3029. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3030. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3031. %% parameter of \key{interp-tests} is a list that should have one entry
  3032. %% for each pass in your compiler. For now, define \code{passes} to
  3033. %% contain just one entry for \code{uniquify} as shown below.
  3034. %% \begin{lstlisting}
  3035. %% (define passes
  3036. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3037. %% \end{lstlisting}
  3038. Run the \key{run-tests.py} script in the support code to check
  3039. whether the output programs produce the same result as the input
  3040. programs.
  3041. \end{exercise}
  3042. \fi}
  3043. {\if\edition\racketEd
  3044. \section{Explicate Control}
  3045. \label{sec:explicate-control-Lvar}
  3046. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3047. programs that make the order of execution explicit in their
  3048. syntax. For now this amounts to flattening \key{let} constructs into a
  3049. sequence of assignment statements. For example, consider the following
  3050. \LangVar{} program.\\
  3051. % var_test_11.rkt
  3052. \begin{minipage}{0.96\textwidth}
  3053. \begin{lstlisting}
  3054. (let ([y (let ([x 20])
  3055. (+ x (let ([x 22]) x)))])
  3056. y)
  3057. \end{lstlisting}
  3058. \end{minipage}\\
  3059. %
  3060. The output of the previous pass and of \code{explicate\_control} is
  3061. shown below. Recall that the right-hand-side of a \key{let} executes
  3062. before its body, so the order of evaluation for this program is to
  3063. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  3064. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  3065. output of \code{explicate\_control} makes this ordering explicit.
  3066. \begin{transformation}
  3067. \begin{lstlisting}
  3068. (let ([y (let ([x.1 20])
  3069. (let ([x.2 22])
  3070. (+ x.1 x.2)))])
  3071. y)
  3072. \end{lstlisting}
  3073. \compilesto
  3074. \begin{lstlisting}[language=C]
  3075. start:
  3076. x.1 = 20;
  3077. x.2 = 22;
  3078. y = (+ x.1 x.2);
  3079. return y;
  3080. \end{lstlisting}
  3081. \end{transformation}
  3082. \begin{figure}[tbp]
  3083. \begin{lstlisting}
  3084. (define (explicate_tail e)
  3085. (match e
  3086. [(Var x) ___]
  3087. [(Int n) (Return (Int n))]
  3088. [(Let x rhs body) ___]
  3089. [(Prim op es) ___]
  3090. [else (error "explicate_tail unhandled case" e)]))
  3091. (define (explicate_assign e x cont)
  3092. (match e
  3093. [(Var x) ___]
  3094. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3095. [(Let y rhs body) ___]
  3096. [(Prim op es) ___]
  3097. [else (error "explicate_assign unhandled case" e)]))
  3098. (define (explicate_control p)
  3099. (match p
  3100. [(Program info body) ___]))
  3101. \end{lstlisting}
  3102. \caption{Skeleton for the \code{explicate\_control} pass.}
  3103. \label{fig:explicate-control-Lvar}
  3104. \end{figure}
  3105. The organization of this pass depends on the notion of tail position
  3106. that we have alluded to earlier.
  3107. \begin{definition}
  3108. The following rules define when an expression is in \textbf{\emph{tail
  3109. position}}\index{subject}{tail position} for the language \LangVar{}.
  3110. \begin{enumerate}
  3111. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3112. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3113. \end{enumerate}
  3114. \end{definition}
  3115. We recommend implementing \code{explicate\_control} using two mutually
  3116. recursive functions, \code{explicate\_tail} and
  3117. \code{explicate\_assign}, as suggested in the skeleton code in
  3118. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3119. function should be applied to expressions in tail position whereas the
  3120. \code{explicate\_assign} should be applied to expressions that occur on
  3121. the right-hand-side of a \key{let}.
  3122. %
  3123. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3124. input and produces a \Tail{} in \LangCVar{} (see
  3125. Figure~\ref{fig:c0-syntax}).
  3126. %
  3127. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3128. the variable that it is to be assigned to, and a \Tail{} in
  3129. \LangCVar{} for the code that comes after the assignment. The
  3130. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3131. The \code{explicate\_assign} function is in accumulator-passing style:
  3132. the \code{cont} parameter is used for accumulating the output. This
  3133. accumulator-passing style plays an important role in how we generate
  3134. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  3135. \begin{exercise}\normalfont
  3136. %
  3137. Implement the \code{explicate\_control} function in
  3138. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3139. exercise the code in \code{explicate\_control}.
  3140. %
  3141. In the \code{run-tests.rkt} script, add the following entry to the
  3142. list of \code{passes} and then run the script to test your compiler.
  3143. \begin{lstlisting}
  3144. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3145. \end{lstlisting}
  3146. \end{exercise}
  3147. \fi}
  3148. \section{Select Instructions}
  3149. \label{sec:select-Lvar}
  3150. \index{subject}{instruction selection}
  3151. In the \code{select\_instructions} pass we begin the work of
  3152. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3153. language of this pass is a variant of x86 that still uses variables,
  3154. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3155. non-terminal of the \LangXInt{} abstract syntax
  3156. (Figure~\ref{fig:x86-int-ast}).
  3157. \racket{We recommend implementing the
  3158. \code{select\_instructions} with three auxiliary functions, one for
  3159. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3160. $\Tail$.}
  3161. \python{We recommend implementing an auxiliary function
  3162. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  3163. \racket{
  3164. The cases for $\Atm$ are straightforward; variables stay
  3165. the same and integer constants change to immediates:
  3166. $\INT{n}$ changes to $\IMM{n}$.}
  3167. We consider the cases for the $\Stmt$ non-terminal, starting with
  3168. arithmetic operations. For example, consider the addition operation
  3169. below, on the left side. There is an \key{addq} instruction in x86,
  3170. but it performs an in-place update. So we could move $\Arg_1$
  3171. into the left-hand side \itm{var} and then add $\Arg_2$ to
  3172. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  3173. $\Atm_1$ and $\Atm_2$ respectively.
  3174. \begin{transformation}
  3175. {\if\edition\racketEd
  3176. \begin{lstlisting}
  3177. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3178. \end{lstlisting}
  3179. \fi}
  3180. {\if\edition\pythonEd
  3181. \begin{lstlisting}
  3182. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3183. \end{lstlisting}
  3184. \fi}
  3185. \compilesto
  3186. \begin{lstlisting}
  3187. movq |$\Arg_1$|, |$\itm{var}$|
  3188. addq |$\Arg_2$|, |$\itm{var}$|
  3189. \end{lstlisting}
  3190. \end{transformation}
  3191. There are also cases that require special care to avoid generating
  3192. needlessly complicated code. For example, if one of the arguments of
  3193. the addition is the same variable as the left-hand side of the
  3194. assignment, as shown below, then there is no need for the extra move
  3195. instruction. The assignment statement can be translated into a single
  3196. \key{addq} instruction as follows.
  3197. \begin{transformation}
  3198. {\if\edition\racketEd
  3199. \begin{lstlisting}
  3200. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3201. \end{lstlisting}
  3202. \fi}
  3203. {\if\edition\pythonEd
  3204. \begin{lstlisting}
  3205. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3206. \end{lstlisting}
  3207. \fi}
  3208. \compilesto
  3209. \begin{lstlisting}
  3210. addq |$\Arg_1$|, |$\itm{var}$|
  3211. \end{lstlisting}
  3212. \end{transformation}
  3213. The \READOP{} operation does not have a direct counterpart in x86
  3214. assembly, so we provide this functionality with the function
  3215. \code{read\_int} in the file \code{runtime.c}, written in
  3216. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3217. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3218. system}, or simply the \emph{runtime} for short. When compiling your
  3219. generated x86 assembly code, you need to compile \code{runtime.c} to
  3220. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3221. \code{-c}) and link it into the executable. For our purposes of code
  3222. generation, all you need to do is translate an assignment of
  3223. \READOP{} into a call to the \code{read\_int} function followed by a
  3224. move from \code{rax} to the left-hand-side variable. (Recall that the
  3225. return value of a function goes into \code{rax}.)
  3226. \begin{transformation}
  3227. {\if\edition\racketEd
  3228. \begin{lstlisting}
  3229. |$\itm{var}$| = (read);
  3230. \end{lstlisting}
  3231. \fi}
  3232. {\if\edition\pythonEd
  3233. \begin{lstlisting}
  3234. |$\itm{var}$| = input_int();
  3235. \end{lstlisting}
  3236. \fi}
  3237. \compilesto
  3238. \begin{lstlisting}
  3239. callq read_int
  3240. movq %rax, |$\itm{var}$|
  3241. \end{lstlisting}
  3242. \end{transformation}
  3243. {\if\edition\pythonEd
  3244. %
  3245. Similarly, we translate the \code{print} operation, shown below, into
  3246. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3247. In x86, the first six arguments to functions are passed in registers,
  3248. with the first argument passed in register \code{rdi}. So we move the
  3249. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3250. \code{callq} instruction.
  3251. \begin{transformation}
  3252. \begin{lstlisting}
  3253. print(|$\Atm$|)
  3254. \end{lstlisting}
  3255. \compilesto
  3256. \begin{lstlisting}
  3257. movq |$\Arg$|, %rdi
  3258. callq print_int
  3259. \end{lstlisting}
  3260. \end{transformation}
  3261. %
  3262. \fi}
  3263. {\if\edition\racketEd
  3264. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3265. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3266. assignment to the \key{rax} register followed by a jump to the
  3267. conclusion of the program (so the conclusion needs to be labeled).
  3268. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3269. recursively and then append the resulting instructions.
  3270. \fi}
  3271. {\if\edition\pythonEd
  3272. We recommend that you use the function \code{utils.label\_name()} to
  3273. transform a string into an label argument suitably suitable for, e.g.,
  3274. the target of the \code{callq} instruction. This practice makes your
  3275. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3276. all labels.
  3277. \fi}
  3278. \begin{exercise}
  3279. \normalfont
  3280. {\if\edition\racketEd
  3281. Implement the \code{select\_instructions} pass in
  3282. \code{compiler.rkt}. Create three new example programs that are
  3283. designed to exercise all of the interesting cases in this pass.
  3284. %
  3285. In the \code{run-tests.rkt} script, add the following entry to the
  3286. list of \code{passes} and then run the script to test your compiler.
  3287. \begin{lstlisting}
  3288. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3289. \end{lstlisting}
  3290. \fi}
  3291. {\if\edition\pythonEd
  3292. Implement the \key{select\_instructions} pass in
  3293. \code{compiler.py}. Create three new example programs that are
  3294. designed to exercise all of the interesting cases in this pass.
  3295. Run the \code{run-tests.py} script to to check
  3296. whether the output programs produce the same result as the input
  3297. programs.
  3298. \fi}
  3299. \end{exercise}
  3300. \section{Assign Homes}
  3301. \label{sec:assign-Lvar}
  3302. The \key{assign\_homes} pass compiles \LangXVar{} programs to
  3303. \LangXVar{} programs that no longer use program variables.
  3304. Thus, the \key{assign-homes} pass is responsible for placing all of
  3305. the program variables in registers or on the stack. For runtime
  3306. efficiency, it is better to place variables in registers, but as there
  3307. are only 16 registers, some programs must necessarily resort to
  3308. placing some variables on the stack. In this chapter we focus on the
  3309. mechanics of placing variables on the stack. We study an algorithm for
  3310. placing variables in registers in
  3311. Chapter~\ref{ch:register-allocation-Lvar}.
  3312. Consider again the following \LangVar{} program from
  3313. Section~\ref{sec:remove-complex-opera-Lvar}.
  3314. % var_test_20.rkt
  3315. {\if\edition\racketEd
  3316. \begin{lstlisting}
  3317. (let ([a 42])
  3318. (let ([b a])
  3319. b))
  3320. \end{lstlisting}
  3321. \fi}
  3322. {\if\edition\pythonEd
  3323. \begin{lstlisting}
  3324. a = 42
  3325. b = a
  3326. print(b)
  3327. \end{lstlisting}
  3328. \fi}
  3329. %
  3330. The output of \code{select\_instructions} is shown below, on the left,
  3331. and the output of \code{assign\_homes} is on the right. In this
  3332. example, we assign variable \code{a} to stack location
  3333. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3334. \begin{transformation}
  3335. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3336. movq $42, a
  3337. movq a, b
  3338. movq b, %rax
  3339. \end{lstlisting}
  3340. \compilesto
  3341. %stack-space: 16
  3342. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3343. movq $42, -8(%rbp)
  3344. movq -8(%rbp), -16(%rbp)
  3345. movq -16(%rbp), %rax
  3346. \end{lstlisting}
  3347. \end{transformation}
  3348. \racket{The \code{locals-types} entry in the $\itm{info}$ of the
  3349. \code{X86Program} node is an alist mapping all the variables in the
  3350. program to their types (for now just \code{Integer}). The
  3351. \code{assign\_homes} pass should replace all uses of those variables
  3352. with stack locations. As an aside, the \code{locals-types} entry is
  3353. computed by \code{type-check-Cvar} in the support code, which
  3354. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3355. which should be propagated to the \code{X86Program} node.}
  3356. %
  3357. \python{The \code{assign\_homes} pass should replace all uses of
  3358. variables with stack locations.}
  3359. %
  3360. In the process of assigning variables to stack locations, it is
  3361. convenient for you to compute and store the size of the frame (in
  3362. bytes) in%
  3363. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space}}
  3364. %
  3365. \python{the field \code{stack\_space} of the \key{X86Program} node},
  3366. which is needed later to generate the conclusion of the \code{main}
  3367. procedure. The x86-64 standard requires the frame size to be a
  3368. multiple of 16 bytes.\index{subject}{frame}
  3369. % TODO: store the number of variables instead? -Jeremy
  3370. \begin{exercise}\normalfont
  3371. Implement the \key{assign\_homes} pass in
  3372. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3373. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3374. grammar. We recommend that the auxiliary functions take an extra
  3375. parameter that maps variable names to homes (stack locations for now).
  3376. %
  3377. {\if\edition\racketEd
  3378. In the \code{run-tests.rkt} script, add the following entry to the
  3379. list of \code{passes} and then run the script to test your compiler.
  3380. \begin{lstlisting}
  3381. (list "assign homes" assign-homes interp_x86-0)
  3382. \end{lstlisting}
  3383. \fi}
  3384. {\if\edition\pythonEd
  3385. Run the \code{run-tests.py} script to to check
  3386. whether the output programs produce the same result as the input
  3387. programs.
  3388. \fi}
  3389. \end{exercise}
  3390. \section{Patch Instructions}
  3391. \label{sec:patch-s0}
  3392. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3393. \LangXInt{} by making sure that each instruction adheres to the
  3394. restriction that at most one argument of an instruction may be a
  3395. memory reference.
  3396. We return to the following example.\\
  3397. \begin{minipage}{0.5\textwidth}
  3398. % var_test_20.rkt
  3399. {\if\edition\racketEd
  3400. \begin{lstlisting}
  3401. (let ([a 42])
  3402. (let ([b a])
  3403. b))
  3404. \end{lstlisting}
  3405. \fi}
  3406. {\if\edition\pythonEd
  3407. \begin{lstlisting}
  3408. a = 42
  3409. b = a
  3410. print(b)
  3411. \end{lstlisting}
  3412. \fi}
  3413. \end{minipage}\\
  3414. The \key{assign\_homes} pass produces the following translation. \\
  3415. \begin{minipage}{0.5\textwidth}
  3416. {\if\edition\racketEd
  3417. \begin{lstlisting}
  3418. movq $42, -8(%rbp)
  3419. movq -8(%rbp), -16(%rbp)
  3420. movq -16(%rbp), %rax
  3421. \end{lstlisting}
  3422. \fi}
  3423. {\if\edition\pythonEd
  3424. \begin{lstlisting}
  3425. movq 42, -8(%rbp)
  3426. movq -8(%rbp), -16(%rbp)
  3427. movq -16(%rbp), %rdi
  3428. callq print_int
  3429. \end{lstlisting}
  3430. \fi}
  3431. \end{minipage}\\
  3432. The second \key{movq} instruction is problematic because both
  3433. arguments are stack locations. We suggest fixing this problem by
  3434. moving from the source location to the register \key{rax} and then
  3435. from \key{rax} to the destination location, as follows.
  3436. \begin{lstlisting}
  3437. movq -8(%rbp), %rax
  3438. movq %rax, -16(%rbp)
  3439. \end{lstlisting}
  3440. \begin{exercise}
  3441. \normalfont Implement the \key{patch\_instructions} pass in
  3442. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3443. Create three new example programs that are
  3444. designed to exercise all of the interesting cases in this pass.
  3445. %
  3446. {\if\edition\racketEd
  3447. In the \code{run-tests.rkt} script, add the following entry to the
  3448. list of \code{passes} and then run the script to test your compiler.
  3449. \begin{lstlisting}
  3450. (list "patch instructions" patch_instructions interp_x86-0)
  3451. \end{lstlisting}
  3452. \fi}
  3453. {\if\edition\pythonEd
  3454. Run the \code{run-tests.py} script to to check
  3455. whether the output programs produce the same result as the input
  3456. programs.
  3457. \fi}
  3458. \end{exercise}
  3459. \section{Generate Prelude and Conclusion}
  3460. \label{sec:print-x86}
  3461. \index{subject}{prelude}\index{subject}{conclusion}
  3462. The last step of the compiler from \LangVar{} to x86 is to generate
  3463. the \code{main} function with a prelude and conclusion wrapped around
  3464. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3465. discussed in Section~\ref{sec:x86}.
  3466. When running on Mac OS X, your compiler should prefix an underscore to
  3467. all labels, e.g., changing \key{main} to \key{\_main}.
  3468. %
  3469. \racket{The Racket call \code{(system-type 'os)} is useful for
  3470. determining which operating system the compiler is running on. It
  3471. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3472. %
  3473. \python{The Python \code{platform} library includes a \code{system()}
  3474. function that returns \code{'Linux'}, \code{'Windows'}, or
  3475. \code{'Darwin'} (for Mac).}
  3476. \begin{exercise}\normalfont
  3477. %
  3478. Implement the \key{prelude\_and\_conclusion} pass in
  3479. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3480. %
  3481. {\if\edition\racketEd
  3482. In the \code{run-tests.rkt} script, add the following entry to the
  3483. list of \code{passes} and then run the script to test your compiler.
  3484. \begin{lstlisting}
  3485. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3486. \end{lstlisting}
  3487. %
  3488. Uncomment the call to the \key{compiler-tests} function
  3489. (Appendix~\ref{appendix:utilities}), which tests your complete
  3490. compiler by executing the generated x86 code. It translates the x86
  3491. AST that you produce into a string by invoking the \code{print-x86}
  3492. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3493. the provided \key{runtime.c} file to \key{runtime.o} using
  3494. \key{gcc}. Run the script to test your compiler.
  3495. %
  3496. \fi}
  3497. {\if\edition\pythonEd
  3498. %
  3499. Run the \code{run-tests.py} script to to check whether the output
  3500. programs produce the same result as the input programs. That script
  3501. translates the x86 AST that you produce into a string by invoking the
  3502. \code{repr} method that is implemented by the x86 AST classes in
  3503. \code{x86\_ast.py}.
  3504. %
  3505. \fi}
  3506. \end{exercise}
  3507. \section{Challenge: Partial Evaluator for \LangVar{}}
  3508. \label{sec:pe-Lvar}
  3509. \index{subject}{partial evaluation}
  3510. This section describes two optional challenge exercises that involve
  3511. adapting and improving the partial evaluator for \LangInt{} that was
  3512. introduced in Section~\ref{sec:partial-evaluation}.
  3513. \begin{exercise}\label{ex:pe-Lvar}
  3514. \normalfont
  3515. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3516. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3517. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3518. %
  3519. \racket{\key{let} binding}\python{assignment}
  3520. %
  3521. to the \LangInt{} language, so you will need to add cases for them in
  3522. the \code{pe\_exp}
  3523. %
  3524. \racket{function}
  3525. %
  3526. \python{and \code{pe\_stmt} functions}.
  3527. %
  3528. Once complete, add the partial evaluation pass to the front of your
  3529. compiler and make sure that your compiler still passes all of the
  3530. tests.
  3531. \end{exercise}
  3532. \begin{exercise}
  3533. \normalfont
  3534. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3535. \code{pe\_add} auxiliary functions with functions that know more about
  3536. arithmetic. For example, your partial evaluator should translate
  3537. {\if\edition\racketEd
  3538. \[
  3539. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3540. \code{(+ 2 (read))}
  3541. \]
  3542. \fi}
  3543. {\if\edition\pythonEd
  3544. \[
  3545. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3546. \code{2 + input\_int()}
  3547. \]
  3548. \fi}
  3549. To accomplish this, the \code{pe\_exp} function should produce output
  3550. in the form of the $\itm{residual}$ non-terminal of the following
  3551. grammar. The idea is that when processing an addition expression, we
  3552. can always produce either 1) an integer constant, 2) an addition
  3553. expression with an integer constant on the left-hand side but not the
  3554. right-hand side, or 3) or an addition expression in which neither
  3555. subexpression is a constant.
  3556. {\if\edition\racketEd
  3557. \[
  3558. \begin{array}{lcl}
  3559. \itm{inert} &::=& \Var
  3560. \MID \LP\key{read}\RP
  3561. \MID \LP\key{-} ~\Var\RP
  3562. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3563. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3564. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3565. \itm{residual} &::=& \Int
  3566. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3567. \MID \itm{inert}
  3568. \end{array}
  3569. \]
  3570. \fi}
  3571. {\if\edition\pythonEd
  3572. \[
  3573. \begin{array}{lcl}
  3574. \itm{inert} &::=& \Var
  3575. \MID \key{input\_int}\LP\RP
  3576. \MID \key{-} \Var
  3577. \MID \key{-} \key{input\_int}\LP\RP
  3578. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3579. \itm{residual} &::=& \Int
  3580. \MID \Int ~ \key{+} ~ \itm{inert}
  3581. \MID \itm{inert}
  3582. \end{array}
  3583. \]
  3584. \fi}
  3585. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3586. inputs are $\itm{residual}$ expressions and they should return
  3587. $\itm{residual}$ expressions. Once the improvements are complete,
  3588. make sure that your compiler still passes all of the tests. After
  3589. all, fast code is useless if it produces incorrect results!
  3590. \end{exercise}
  3591. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3592. \chapter{Register Allocation}
  3593. \label{ch:register-allocation-Lvar}
  3594. \index{subject}{register allocation}
  3595. In Chapter~\ref{ch:Lvar} we learned how to store variables on the
  3596. stack. In this chapter we learn how to improve the performance of the
  3597. generated code by assigning some variables to registers. The CPU can
  3598. access a register in a single cycle, whereas accessing the stack can
  3599. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3600. serves as a running example. The source program is on the left and the
  3601. output of instruction selection is on the right. The program is almost
  3602. in the x86 assembly language but it still uses variables.
  3603. \begin{figure}
  3604. \begin{minipage}{0.45\textwidth}
  3605. Example \LangVar{} program:
  3606. % var_test_28.rkt
  3607. {\if\edition\racketEd
  3608. \begin{lstlisting}
  3609. (let ([v 1])
  3610. (let ([w 42])
  3611. (let ([x (+ v 7)])
  3612. (let ([y x])
  3613. (let ([z (+ x w)])
  3614. (+ z (- y)))))))
  3615. \end{lstlisting}
  3616. \fi}
  3617. {\if\edition\pythonEd
  3618. \begin{lstlisting}
  3619. v = 1
  3620. w = 42
  3621. x = v + 7
  3622. y = x
  3623. z = x + w
  3624. print(z + (- y))
  3625. \end{lstlisting}
  3626. \fi}
  3627. \end{minipage}
  3628. \begin{minipage}{0.45\textwidth}
  3629. After instruction selection:
  3630. {\if\edition\racketEd
  3631. \begin{lstlisting}
  3632. locals-types:
  3633. x : Integer, y : Integer,
  3634. z : Integer, t : Integer,
  3635. v : Integer, w : Integer
  3636. start:
  3637. movq $1, v
  3638. movq $42, w
  3639. movq v, x
  3640. addq $7, x
  3641. movq x, y
  3642. movq x, z
  3643. addq w, z
  3644. movq y, t
  3645. negq t
  3646. movq z, %rax
  3647. addq t, %rax
  3648. jmp conclusion
  3649. \end{lstlisting}
  3650. \fi}
  3651. {\if\edition\pythonEd
  3652. \begin{lstlisting}
  3653. movq $1, v
  3654. movq $42, w
  3655. movq v, x
  3656. addq $7, x
  3657. movq x, y
  3658. movq x, z
  3659. addq w, z
  3660. movq y, tmp_0
  3661. negq tmp_0
  3662. movq z, tmp_1
  3663. addq tmp_0, tmp_1
  3664. movq tmp_1, %rdi
  3665. callq print_int
  3666. \end{lstlisting}
  3667. \fi}
  3668. \end{minipage}
  3669. \caption{A running example for register allocation.}
  3670. \label{fig:reg-eg}
  3671. \end{figure}
  3672. The goal of register allocation is to fit as many variables into
  3673. registers as possible. Some programs have more variables than
  3674. registers so we cannot always map each variable to a different
  3675. register. Fortunately, it is common for different variables to be
  3676. needed during different periods of time during program execution, and
  3677. in such cases several variables can be mapped to the same register.
  3678. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3679. After the variable \code{x} is moved to \code{z} it is no longer
  3680. needed. Variable \code{z}, on the other hand, is used only after this
  3681. point, so \code{x} and \code{z} could share the same register. The
  3682. topic of Section~\ref{sec:liveness-analysis-Lvar} is how to compute
  3683. where a variable is needed. Once we have that information, we compute
  3684. which variables are needed at the same time, i.e., which ones
  3685. \emph{interfere} with each other, and represent this relation as an
  3686. undirected graph whose vertices are variables and edges indicate when
  3687. two variables interfere (Section~\ref{sec:build-interference}). We
  3688. then model register allocation as a graph coloring problem
  3689. (Section~\ref{sec:graph-coloring}).
  3690. If we run out of registers despite these efforts, we place the
  3691. remaining variables on the stack, similar to what we did in
  3692. Chapter~\ref{ch:Lvar}. It is common to use the verb \emph{spill} for
  3693. assigning a variable to a stack location. The decision to spill a
  3694. variable is handled as part of the graph coloring process.
  3695. We make the simplifying assumption that each variable is assigned to
  3696. one location (a register or stack address). A more sophisticated
  3697. approach is to assign a variable to one or more locations in different
  3698. regions of the program. For example, if a variable is used many times
  3699. in short sequence and then only used again after many other
  3700. instructions, it could be more efficient to assign the variable to a
  3701. register during the initial sequence and then move it to the stack for
  3702. the rest of its lifetime. We refer the interested reader to
  3703. \citet{Cooper:2011aa} Chapter 13 for more information about that
  3704. approach.
  3705. % discuss prioritizing variables based on how much they are used.
  3706. \section{Registers and Calling Conventions}
  3707. \label{sec:calling-conventions}
  3708. \index{subject}{calling conventions}
  3709. As we perform register allocation, we need to be aware of the
  3710. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  3711. functions calls are performed in x86.
  3712. %
  3713. Even though \LangVar{} does not include programmer-defined functions,
  3714. our generated code includes a \code{main} function that is called by
  3715. the operating system and our generated code contains calls to the
  3716. \code{read\_int} function.
  3717. Function calls require coordination between two pieces of code that
  3718. may be written by different programmers or generated by different
  3719. compilers. Here we follow the System V calling conventions that are
  3720. used by the GNU C compiler on Linux and
  3721. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3722. %
  3723. The calling conventions include rules about how functions share the
  3724. use of registers. In particular, the caller is responsible for freeing
  3725. up some registers prior to the function call for use by the callee.
  3726. These are called the \emph{caller-saved registers}
  3727. \index{subject}{caller-saved registers}
  3728. and they are
  3729. \begin{lstlisting}
  3730. rax rcx rdx rsi rdi r8 r9 r10 r11
  3731. \end{lstlisting}
  3732. On the other hand, the callee is responsible for preserving the values
  3733. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3734. which are
  3735. \begin{lstlisting}
  3736. rsp rbp rbx r12 r13 r14 r15
  3737. \end{lstlisting}
  3738. We can think about this caller/callee convention from two points of
  3739. view, the caller view and the callee view:
  3740. \begin{itemize}
  3741. \item The caller should assume that all the caller-saved registers get
  3742. overwritten with arbitrary values by the callee. On the other hand,
  3743. the caller can safely assume that all the callee-saved registers
  3744. contain the same values after the call that they did before the
  3745. call.
  3746. \item The callee can freely use any of the caller-saved registers.
  3747. However, if the callee wants to use a callee-saved register, the
  3748. callee must arrange to put the original value back in the register
  3749. prior to returning to the caller. This can be accomplished by saving
  3750. the value to the stack in the prelude of the function and restoring
  3751. the value in the conclusion of the function.
  3752. \end{itemize}
  3753. In x86, registers are also used for passing arguments to a function
  3754. and for the return value. In particular, the first six arguments to a
  3755. function are passed in the following six registers, in this order.
  3756. \begin{lstlisting}
  3757. rdi rsi rdx rcx r8 r9
  3758. \end{lstlisting}
  3759. If there are more than six arguments, then the convention is to use
  3760. space on the frame of the caller for the rest of the
  3761. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  3762. need more than six arguments.
  3763. %
  3764. \racket{For now, the only function we care about is \code{read\_int}
  3765. and it takes zero arguments.}
  3766. %
  3767. \python{For now, the only functions we care about are \code{read\_int}
  3768. and \code{print\_int}, which take zero and one argument, respectively.}
  3769. %
  3770. The register \code{rax} is used for the return value of a function.
  3771. The next question is how these calling conventions impact register
  3772. allocation. Consider the \LangVar{} program in
  3773. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3774. example from the caller point of view and then from the callee point
  3775. of view.
  3776. The program makes two calls to \READOP{}. Also, the variable \code{x}
  3777. is in use during the second call to \READOP{}, so we need to make sure
  3778. that the value in \code{x} does not get accidentally wiped out by the
  3779. call to \READOP{}. One obvious approach is to save all the values in
  3780. caller-saved registers to the stack prior to each function call, and
  3781. restore them after each call. That way, if the register allocator
  3782. chooses to assign \code{x} to a caller-saved register, its value will
  3783. be preserved across the call to \READOP{}. However, saving and
  3784. restoring to the stack is relatively slow. If \code{x} is not used
  3785. many times, it may be better to assign \code{x} to a stack location in
  3786. the first place. Or better yet, if we can arrange for \code{x} to be
  3787. placed in a callee-saved register, then it won't need to be saved and
  3788. restored during function calls.
  3789. The approach that we recommend for variables that are in use during a
  3790. function call is to either assign them to callee-saved registers or to
  3791. spill them to the stack. On the other hand, for variables that are not
  3792. in use during a function call, we try the following alternatives in
  3793. order 1) look for an available caller-saved register (to leave room
  3794. for other variables in the callee-saved register), 2) look for a
  3795. callee-saved register, and 3) spill the variable to the stack.
  3796. It is straightforward to implement this approach in a graph coloring
  3797. register allocator. First, we know which variables are in use during
  3798. every function call because we compute that information for every
  3799. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3800. we build the interference graph
  3801. (Section~\ref{sec:build-interference}), we can place an edge between
  3802. each of these call-live variables and the caller-saved registers in
  3803. the interference graph. This will prevent the graph coloring algorithm
  3804. from assigning them to caller-saved registers.
  3805. Returning to the example in
  3806. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3807. generated x86 code on the right-hand side. Notice that variable
  3808. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3809. is already in a safe place during the second call to
  3810. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3811. \code{rcx}, a caller-saved register, because \code{y} is not in the
  3812. live-after set of a \code{callq} instruction.
  3813. Next we analyze the example from the callee point of view, focusing on
  3814. the prelude and conclusion of the \code{main} function. As usual the
  3815. prelude begins with saving the \code{rbp} register to the stack and
  3816. setting the \code{rbp} to the current stack pointer. We now know why
  3817. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3818. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3819. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3820. (\code{x}). The other callee-saved registers are not saved in the
  3821. prelude because they are not used. The prelude subtracts 8 bytes from
  3822. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3823. conclusion, we see that \code{rbx} is restored from the stack with a
  3824. \code{popq} instruction.
  3825. \index{subject}{prelude}\index{subject}{conclusion}
  3826. \begin{figure}[tp]
  3827. \begin{minipage}{0.45\textwidth}
  3828. Example \LangVar{} program:
  3829. %var_test_14.rkt
  3830. {\if\edition\racketEd
  3831. \begin{lstlisting}
  3832. (let ([x (read)])
  3833. (let ([y (read)])
  3834. (+ (+ x y) 42)))
  3835. \end{lstlisting}
  3836. \fi}
  3837. {\if\edition\pythonEd
  3838. \begin{lstlisting}
  3839. x = input_int()
  3840. y = input_int()
  3841. print((x + y) + 42)
  3842. \end{lstlisting}
  3843. \fi}
  3844. \end{minipage}
  3845. \begin{minipage}{0.45\textwidth}
  3846. Generated x86 assembly:
  3847. {\if\edition\racketEd
  3848. \begin{lstlisting}
  3849. start:
  3850. callq read_int
  3851. movq %rax, %rbx
  3852. callq read_int
  3853. movq %rax, %rcx
  3854. addq %rcx, %rbx
  3855. movq %rbx, %rax
  3856. addq $42, %rax
  3857. jmp _conclusion
  3858. .globl main
  3859. main:
  3860. pushq %rbp
  3861. movq %rsp, %rbp
  3862. pushq %rbx
  3863. subq $8, %rsp
  3864. jmp start
  3865. conclusion:
  3866. addq $8, %rsp
  3867. popq %rbx
  3868. popq %rbp
  3869. retq
  3870. \end{lstlisting}
  3871. \fi}
  3872. {\if\edition\pythonEd
  3873. \begin{lstlisting}
  3874. .globl main
  3875. main:
  3876. pushq %rbp
  3877. movq %rsp, %rbp
  3878. pushq %rbx
  3879. subq $8, %rsp
  3880. callq read_int
  3881. movq %rax, %rbx
  3882. callq read_int
  3883. movq %rax, %rcx
  3884. movq %rbx, %rdx
  3885. addq %rcx, %rdx
  3886. movq %rdx, %rcx
  3887. addq $42, %rcx
  3888. movq %rcx, %rdi
  3889. callq print_int
  3890. addq $8, %rsp
  3891. popq %rbx
  3892. popq %rbp
  3893. retq
  3894. \end{lstlisting}
  3895. \fi}
  3896. \end{minipage}
  3897. \caption{An example with function calls.}
  3898. \label{fig:example-calling-conventions}
  3899. \end{figure}
  3900. %\clearpage
  3901. \section{Liveness Analysis}
  3902. \label{sec:liveness-analysis-Lvar}
  3903. \index{subject}{liveness analysis}
  3904. The \code{uncover\_live} \racket{pass}\python{function}
  3905. performs \emph{liveness analysis}, that
  3906. is, it discovers which variables are in-use in different regions of a
  3907. program.
  3908. %
  3909. A variable or register is \emph{live} at a program point if its
  3910. current value is used at some later point in the program. We refer to
  3911. variables, stack locations, and registers collectively as
  3912. \emph{locations}.
  3913. %
  3914. Consider the following code fragment in which there are two writes to
  3915. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3916. \begin{center}
  3917. \begin{minipage}{0.96\textwidth}
  3918. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3919. movq $5, a
  3920. movq $30, b
  3921. movq a, c
  3922. movq $10, b
  3923. addq b, c
  3924. \end{lstlisting}
  3925. \end{minipage}
  3926. \end{center}
  3927. The answer is no because \code{a} is live from line 1 to 3 and
  3928. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3929. line 2 is never used because it is overwritten (line 4) before the
  3930. next read (line 5).
  3931. The live locations can be computed by traversing the instruction
  3932. sequence back to front (i.e., backwards in execution order). Let
  3933. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3934. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3935. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3936. locations before instruction $I_k$.
  3937. \racket{We recommend representing these
  3938. sets with the Racket \code{set} data structure described in
  3939. Figure~\ref{fig:set}.}
  3940. \python{We recommend representing these sets with the Python
  3941. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  3942. data structure.}
  3943. {\if\edition\racketEd
  3944. \begin{figure}[tp]
  3945. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  3946. \small
  3947. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3948. A \emph{set} is an unordered collection of elements without duplicates.
  3949. Here are some of the operations defined on sets.
  3950. \index{subject}{set}
  3951. \begin{description}
  3952. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  3953. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  3954. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  3955. difference of the two sets.
  3956. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  3957. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  3958. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  3959. \end{description}
  3960. \end{tcolorbox}
  3961. %\end{wrapfigure}
  3962. \caption{The \code{set} data structure.}
  3963. \label{fig:set}
  3964. \end{figure}
  3965. \fi}
  3966. The live locations after an instruction are always the same as the
  3967. live locations before the next instruction.
  3968. \index{subject}{live-after} \index{subject}{live-before}
  3969. \begin{equation} \label{eq:live-after-before-next}
  3970. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3971. \end{equation}
  3972. To start things off, there are no live locations after the last
  3973. instruction, so
  3974. \begin{equation}\label{eq:live-last-empty}
  3975. L_{\mathsf{after}}(n) = \emptyset
  3976. \end{equation}
  3977. We then apply the following rule repeatedly, traversing the
  3978. instruction sequence back to front.
  3979. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  3980. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  3981. \end{equation}
  3982. where $W(k)$ are the locations written to by instruction $I_k$ and
  3983. $R(k)$ are the locations read by instruction $I_k$.
  3984. {\if\edition\racketEd
  3985. There is a special case for \code{jmp} instructions. The locations
  3986. that are live before a \code{jmp} should be the locations in
  3987. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  3988. maintaining an alist named \code{label->live} that maps each label to
  3989. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  3990. now the only \code{jmp} in a \LangXVar{} program is the one at the
  3991. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  3992. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  3993. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  3994. \fi}
  3995. Let us walk through the above example, applying these formulas
  3996. starting with the instruction on line 5. We collect the answers in
  3997. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  3998. \code{addq b, c} instruction is $\emptyset$ because it is the last
  3999. instruction (formula~\ref{eq:live-last-empty}). The
  4000. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  4001. because it reads from variables \code{b} and \code{c}
  4002. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  4003. \[
  4004. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4005. \]
  4006. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4007. the live-before set from line 5 to be the live-after set for this
  4008. instruction (formula~\ref{eq:live-after-before-next}).
  4009. \[
  4010. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4011. \]
  4012. This move instruction writes to \code{b} and does not read from any
  4013. variables, so we have the following live-before set
  4014. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  4015. \[
  4016. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4017. \]
  4018. The live-before for instruction \code{movq a, c}
  4019. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4020. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  4021. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4022. variable that is not live and does not read from a variable.
  4023. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4024. because it writes to variable \code{a}.
  4025. \begin{figure}[tbp]
  4026. \begin{minipage}{0.45\textwidth}
  4027. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4028. movq $5, a
  4029. movq $30, b
  4030. movq a, c
  4031. movq $10, b
  4032. addq b, c
  4033. \end{lstlisting}
  4034. \end{minipage}
  4035. \vrule\hspace{10pt}
  4036. \begin{minipage}{0.45\textwidth}
  4037. \begin{align*}
  4038. L_{\mathsf{before}}(1)= \emptyset,
  4039. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4040. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4041. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4042. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4043. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4044. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4045. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4046. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4047. L_{\mathsf{after}}(5)= \emptyset
  4048. \end{align*}
  4049. \end{minipage}
  4050. \caption{Example output of liveness analysis on a short example.}
  4051. \label{fig:liveness-example-0}
  4052. \end{figure}
  4053. \begin{exercise}\normalfont
  4054. Perform liveness analysis on the running example in
  4055. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4056. sets for each instruction. Compare your answers to the solution
  4057. shown in Figure~\ref{fig:live-eg}.
  4058. \end{exercise}
  4059. \begin{figure}[tp]
  4060. \hspace{20pt}
  4061. \begin{minipage}{0.45\textwidth}
  4062. {\if\edition\racketEd
  4063. \begin{lstlisting}
  4064. |$\{\ttm{rsp}\}$|
  4065. movq $1, v
  4066. |$\{\ttm{v},\ttm{rsp}\}$|
  4067. movq $42, w
  4068. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4069. movq v, x
  4070. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4071. addq $7, x
  4072. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4073. movq x, y
  4074. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4075. movq x, z
  4076. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4077. addq w, z
  4078. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4079. movq y, t
  4080. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4081. negq t
  4082. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4083. movq z, %rax
  4084. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4085. addq t, %rax
  4086. |$\{\ttm{rax},\ttm{rsp}\}$|
  4087. jmp conclusion
  4088. \end{lstlisting}
  4089. \fi}
  4090. {\if\edition\pythonEd
  4091. \begin{lstlisting}
  4092. movq $1, v
  4093. |$\{\ttm{v}\}$|
  4094. movq $42, w
  4095. |$\{\ttm{w}, \ttm{v}\}$|
  4096. movq v, x
  4097. |$\{\ttm{w}, \ttm{x}\}$|
  4098. addq $7, x
  4099. |$\{\ttm{w}, \ttm{x}\}$|
  4100. movq x, y
  4101. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4102. movq x, z
  4103. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4104. addq w, z
  4105. |$\{\ttm{y}, \ttm{z}\}$|
  4106. movq y, tmp_0
  4107. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4108. negq tmp_0
  4109. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4110. movq z, tmp_1
  4111. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4112. addq tmp_0, tmp_1
  4113. |$\{\ttm{tmp\_1}\}$|
  4114. movq tmp_1, %rdi
  4115. |$\{\ttm{rdi}\}$|
  4116. callq print_int
  4117. |$\{\}$|
  4118. \end{lstlisting}
  4119. \fi}
  4120. \end{minipage}
  4121. \caption{The running example annotated with live-after sets.}
  4122. \label{fig:live-eg}
  4123. \end{figure}
  4124. \begin{exercise}\normalfont
  4125. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4126. %
  4127. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4128. field of the \code{Block} structure.}
  4129. %
  4130. \python{Return a dictionary that maps each instruction to its
  4131. live-after set.}
  4132. %
  4133. \racket{We recommend creating an auxiliary function that takes a list
  4134. of instructions and an initial live-after set (typically empty) and
  4135. returns the list of live-after sets.}
  4136. %
  4137. We recommend creating auxiliary functions to 1) compute the set
  4138. of locations that appear in an \Arg{}, 2) compute the locations read
  4139. by an instruction (the $R$ function), and 3) the locations written by
  4140. an instruction (the $W$ function). The \code{callq} instruction should
  4141. include all of the caller-saved registers in its write-set $W$ because
  4142. the calling convention says that those registers may be written to
  4143. during the function call. Likewise, the \code{callq} instruction
  4144. should include the appropriate argument-passing registers in its
  4145. read-set $R$, depending on the arity of the function being
  4146. called. (This is why the abstract syntax for \code{callq} includes the
  4147. arity.)
  4148. \end{exercise}
  4149. %\clearpage
  4150. \section{Build the Interference Graph}
  4151. \label{sec:build-interference}
  4152. {\if\edition\racketEd
  4153. \begin{figure}[tp]
  4154. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4155. \small
  4156. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4157. A \emph{graph} is a collection of vertices and edges where each
  4158. edge connects two vertices. A graph is \emph{directed} if each
  4159. edge points from a source to a target. Otherwise the graph is
  4160. \emph{undirected}.
  4161. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4162. \begin{description}
  4163. %% We currently don't use directed graphs. We instead use
  4164. %% directed multi-graphs. -Jeremy
  4165. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4166. directed graph from a list of edges. Each edge is a list
  4167. containing the source and target vertex.
  4168. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4169. undirected graph from a list of edges. Each edge is represented by
  4170. a list containing two vertices.
  4171. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4172. inserts a vertex into the graph.
  4173. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4174. inserts an edge between the two vertices.
  4175. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4176. returns a sequence of vertices adjacent to the vertex.
  4177. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4178. returns a sequence of all vertices in the graph.
  4179. \end{description}
  4180. \end{tcolorbox}
  4181. %\end{wrapfigure}
  4182. \caption{The Racket \code{graph} package.}
  4183. \label{fig:graph}
  4184. \end{figure}
  4185. \fi}
  4186. Based on the liveness analysis, we know where each location is live.
  4187. However, during register allocation, we need to answer questions of
  4188. the specific form: are locations $u$ and $v$ live at the same time?
  4189. (And therefore cannot be assigned to the same register.) To make this
  4190. question more efficient to answer, we create an explicit data
  4191. structure, an \emph{interference graph}\index{subject}{interference
  4192. graph}. An interference graph is an undirected graph that has an
  4193. edge between two locations if they are live at the same time, that is,
  4194. if they interfere with each other.
  4195. %
  4196. \racket{We recommend using the Racket \code{graph} package
  4197. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4198. %
  4199. \python{We provide implementations of directed and undirected graph
  4200. data structures in the file \code{graph.py} of the support code.}
  4201. A straightforward way to compute the interference graph is to look at
  4202. the set of live locations between each instruction and add an edge to
  4203. the graph for every pair of variables in the same set. This approach
  4204. is less than ideal for two reasons. First, it can be expensive because
  4205. it takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  4206. locations. Second, in the special case where two locations hold the
  4207. same value (because one was assigned to the other), they can be live
  4208. at the same time without interfering with each other.
  4209. A better way to compute the interference graph is to focus on
  4210. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4211. must not overwrite something in a live location. So for each
  4212. instruction, we create an edge between the locations being written to
  4213. and the live locations. (Except that one should not create self
  4214. edges.) Note that for the \key{callq} instruction, we consider all of
  4215. the caller-saved registers as being written to, so an edge is added
  4216. between every live variable and every caller-saved register. Also, for
  4217. \key{movq} there is the above-mentioned special case to deal with. If
  4218. a live variable $v$ is the same as the source of the \key{movq}, then
  4219. there is no need to add an edge between $v$ and the destination,
  4220. because they both hold the same value.
  4221. %
  4222. So we have the following two rules.
  4223. \begin{enumerate}
  4224. \item If instruction $I_k$ is a move instruction of the form
  4225. \key{movq} $s$\key{,} $d$, then for every $v \in
  4226. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4227. $(d,v)$.
  4228. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4229. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4230. $(d,v)$.
  4231. \end{enumerate}
  4232. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4233. the above rules to each instruction. We highlight a few of the
  4234. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4235. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4236. so \code{v} interferes with \code{rsp}.}
  4237. %
  4238. \python{The first instruction is \lstinline{movq $1, v} and the
  4239. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4240. no interference because $\ttm{v}$ is the destination of the move.}
  4241. %
  4242. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4243. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4244. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4245. %
  4246. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4247. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4248. $\ttm{x}$ interferes with \ttm{w}.}
  4249. %
  4250. \racket{The next instruction is \lstinline{movq x, y} and the
  4251. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4252. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4253. \ttm{x} because \ttm{x} is the source of the move and therefore
  4254. \ttm{x} and \ttm{y} hold the same value.}
  4255. %
  4256. \python{The next instruction is \lstinline{movq x, y} and the
  4257. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4258. applies, so \ttm{y} interferes with \ttm{w} but not
  4259. \ttm{x} because \ttm{x} is the source of the move and therefore
  4260. \ttm{x} and \ttm{y} hold the same value.}
  4261. %
  4262. Figure~\ref{fig:interference-results} lists the interference results
  4263. for all of the instructions and the resulting interference graph is
  4264. shown in Figure~\ref{fig:interfere}.
  4265. \begin{figure}[tbp]
  4266. \begin{quote}
  4267. {\if\edition\racketEd
  4268. \begin{tabular}{ll}
  4269. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4270. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4271. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4272. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4273. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4274. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4275. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4276. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4277. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4278. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4279. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4280. \lstinline!jmp conclusion!& no interference.
  4281. \end{tabular}
  4282. \fi}
  4283. {\if\edition\pythonEd
  4284. \begin{tabular}{ll}
  4285. \lstinline!movq $1, v!& no interference\\
  4286. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4287. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4288. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4289. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4290. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4291. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4292. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4293. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4294. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4295. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4296. \lstinline!movq tmp_1, %rdi! & no interference \\
  4297. \lstinline!callq print_int!& no interference.
  4298. \end{tabular}
  4299. \fi}
  4300. \end{quote}
  4301. \caption{Interference results for the running example.}
  4302. \label{fig:interference-results}
  4303. \end{figure}
  4304. \begin{figure}[tbp]
  4305. \large
  4306. {\if\edition\racketEd
  4307. \[
  4308. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4309. \node (rax) at (0,0) {$\ttm{rax}$};
  4310. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4311. \node (t1) at (0,2) {$\ttm{t}$};
  4312. \node (z) at (3,2) {$\ttm{z}$};
  4313. \node (x) at (6,2) {$\ttm{x}$};
  4314. \node (y) at (3,0) {$\ttm{y}$};
  4315. \node (w) at (6,0) {$\ttm{w}$};
  4316. \node (v) at (9,0) {$\ttm{v}$};
  4317. \draw (t1) to (rax);
  4318. \draw (t1) to (z);
  4319. \draw (z) to (y);
  4320. \draw (z) to (w);
  4321. \draw (x) to (w);
  4322. \draw (y) to (w);
  4323. \draw (v) to (w);
  4324. \draw (v) to (rsp);
  4325. \draw (w) to (rsp);
  4326. \draw (x) to (rsp);
  4327. \draw (y) to (rsp);
  4328. \path[-.,bend left=15] (z) edge node {} (rsp);
  4329. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4330. \draw (rax) to (rsp);
  4331. \end{tikzpicture}
  4332. \]
  4333. \fi}
  4334. {\if\edition\pythonEd
  4335. \[
  4336. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4337. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4338. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4339. \node (z) at (3,2) {$\ttm{z}$};
  4340. \node (x) at (6,2) {$\ttm{x}$};
  4341. \node (y) at (3,0) {$\ttm{y}$};
  4342. \node (w) at (6,0) {$\ttm{w}$};
  4343. \node (v) at (9,0) {$\ttm{v}$};
  4344. \draw (t0) to (t1);
  4345. \draw (t0) to (z);
  4346. \draw (z) to (y);
  4347. \draw (z) to (w);
  4348. \draw (x) to (w);
  4349. \draw (y) to (w);
  4350. \draw (v) to (w);
  4351. \end{tikzpicture}
  4352. \]
  4353. \fi}
  4354. \caption{The interference graph of the example program.}
  4355. \label{fig:interfere}
  4356. \end{figure}
  4357. %% Our next concern is to choose a data structure for representing the
  4358. %% interference graph. There are many choices for how to represent a
  4359. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4360. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4361. %% data structure is to study the algorithm that uses the data structure,
  4362. %% determine what operations need to be performed, and then choose the
  4363. %% data structure that provide the most efficient implementations of
  4364. %% those operations. Often times the choice of data structure can have an
  4365. %% effect on the time complexity of the algorithm, as it does here. If
  4366. %% you skim the next section, you will see that the register allocation
  4367. %% algorithm needs to ask the graph for all of its vertices and, given a
  4368. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4369. %% correct choice of graph representation is that of an adjacency
  4370. %% list. There are helper functions in \code{utilities.rkt} for
  4371. %% representing graphs using the adjacency list representation:
  4372. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4373. %% (Appendix~\ref{appendix:utilities}).
  4374. %% %
  4375. %% \margincomment{\footnotesize To do: change to use the
  4376. %% Racket graph library. \\ --Jeremy}
  4377. %% %
  4378. %% In particular, those functions use a hash table to map each vertex to
  4379. %% the set of adjacent vertices, and the sets are represented using
  4380. %% Racket's \key{set}, which is also a hash table.
  4381. \begin{exercise}\normalfont
  4382. \racket{Implement the compiler pass named \code{build\_interference} according
  4383. to the algorithm suggested above. We recommend using the Racket
  4384. \code{graph} package to create and inspect the interference graph.
  4385. The output graph of this pass should be stored in the $\itm{info}$ field of
  4386. the program, under the key \code{conflicts}.}
  4387. %
  4388. \python{Implement a function named \code{build\_interference}
  4389. according to the algorithm suggested above that
  4390. returns the interference graph.}
  4391. \end{exercise}
  4392. \section{Graph Coloring via Sudoku}
  4393. \label{sec:graph-coloring}
  4394. \index{subject}{graph coloring}
  4395. \index{subject}{Sudoku}
  4396. \index{subject}{color}
  4397. We come to the main event, mapping variables to registers and stack
  4398. locations. Variables that interfere with each other must be mapped to
  4399. different locations. In terms of the interference graph, this means
  4400. that adjacent vertices must be mapped to different locations. If we
  4401. think of locations as colors, the register allocation problem becomes
  4402. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4403. The reader may be more familiar with the graph coloring problem than he
  4404. or she realizes; the popular game of Sudoku is an instance of the
  4405. graph coloring problem. The following describes how to build a graph
  4406. out of an initial Sudoku board.
  4407. \begin{itemize}
  4408. \item There is one vertex in the graph for each Sudoku square.
  4409. \item There is an edge between two vertices if the corresponding squares
  4410. are in the same row, in the same column, or if the squares are in
  4411. the same $3\times 3$ region.
  4412. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4413. \item Based on the initial assignment of numbers to squares in the
  4414. Sudoku board, assign the corresponding colors to the corresponding
  4415. vertices in the graph.
  4416. \end{itemize}
  4417. If you can color the remaining vertices in the graph with the nine
  4418. colors, then you have also solved the corresponding game of Sudoku.
  4419. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4420. the corresponding graph with colored vertices. We map the Sudoku
  4421. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4422. sampling of the vertices (the colored ones) because showing edges for
  4423. all of the vertices would make the graph unreadable.
  4424. \begin{figure}[tbp]
  4425. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4426. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4427. \caption{A Sudoku game board and the corresponding colored graph.}
  4428. \label{fig:sudoku-graph}
  4429. \end{figure}
  4430. Some techniques for playing Sudoku correspond to heuristics used in
  4431. graph coloring algorithms. For example, one of the basic techniques
  4432. for Sudoku is called Pencil Marks. The idea is to use a process of
  4433. elimination to determine what numbers are no longer available for a
  4434. square and write down those numbers in the square (writing very
  4435. small). For example, if the number $1$ is assigned to a square, then
  4436. write the pencil mark $1$ in all the squares in the same row, column,
  4437. and region to indicate that $1$ is no longer an option for those other
  4438. squares.
  4439. %
  4440. The Pencil Marks technique corresponds to the notion of
  4441. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4442. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4443. are no longer available. In graph terminology, we have the following
  4444. definition:
  4445. \begin{equation*}
  4446. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4447. \text{ and } \mathrm{color}(v) = c \}
  4448. \end{equation*}
  4449. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4450. edge with $u$.
  4451. The Pencil Marks technique leads to a simple strategy for filling in
  4452. numbers: if there is a square with only one possible number left, then
  4453. choose that number! But what if there are no squares with only one
  4454. possibility left? One brute-force approach is to try them all: choose
  4455. the first one and if that ultimately leads to a solution, great. If
  4456. not, backtrack and choose the next possibility. One good thing about
  4457. Pencil Marks is that it reduces the degree of branching in the search
  4458. tree. Nevertheless, backtracking can be terribly time consuming. One
  4459. way to reduce the amount of backtracking is to use the
  4460. most-constrained-first heuristic (aka. minimum remaining
  4461. values)~\citep{Russell2003}. That is, when choosing a square, always
  4462. choose one with the fewest possibilities left (the vertex with the
  4463. highest saturation). The idea is that choosing highly constrained
  4464. squares earlier rather than later is better because later on there may
  4465. not be any possibilities left in the highly saturated squares.
  4466. However, register allocation is easier than Sudoku because the
  4467. register allocator can fall back to assigning variables to stack
  4468. locations when the registers run out. Thus, it makes sense to replace
  4469. backtracking with greedy search: make the best choice at the time and
  4470. keep going. We still wish to minimize the number of colors needed, so
  4471. we use the most-constrained-first heuristic in the greedy search.
  4472. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4473. algorithm for register allocation based on saturation and the
  4474. most-constrained-first heuristic. It is roughly equivalent to the
  4475. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4476. %,Gebremedhin:1999fk,Omari:2006uq
  4477. Just as in Sudoku, the algorithm represents colors with integers. The
  4478. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4479. for register allocation. The integers $k$ and larger correspond to
  4480. stack locations. The registers that are not used for register
  4481. allocation, such as \code{rax}, are assigned to negative integers. In
  4482. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4483. %% One might wonder why we include registers at all in the liveness
  4484. %% analysis and interference graph. For example, we never allocate a
  4485. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4486. %% leave them out. As we see in Chapter~\ref{ch:Lvec}, when we begin
  4487. %% to use register for passing arguments to functions, it will be
  4488. %% necessary for those registers to appear in the interference graph
  4489. %% because those registers will also be assigned to variables, and we
  4490. %% don't want those two uses to encroach on each other. Regarding
  4491. %% registers such as \code{rax} and \code{rsp} that are not used for
  4492. %% variables, we could omit them from the interference graph but that
  4493. %% would require adding special cases to our algorithm, which would
  4494. %% complicate the logic for little gain.
  4495. \begin{figure}[btp]
  4496. \centering
  4497. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4498. Algorithm: DSATUR
  4499. Input: a graph |$G$|
  4500. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4501. |$W \gets \mathrm{vertices}(G)$|
  4502. while |$W \neq \emptyset$| do
  4503. pick a vertex |$u$| from |$W$| with the highest saturation,
  4504. breaking ties randomly
  4505. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4506. |$\mathrm{color}[u] \gets c$|
  4507. |$W \gets W - \{u\}$|
  4508. \end{lstlisting}
  4509. \caption{The saturation-based greedy graph coloring algorithm.}
  4510. \label{fig:satur-algo}
  4511. \end{figure}
  4512. {\if\edition\racketEd
  4513. With the DSATUR algorithm in hand, let us return to the running
  4514. example and consider how to color the interference graph in
  4515. Figure~\ref{fig:interfere}.
  4516. %
  4517. We start by assigning the register nodes to their own color. For
  4518. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4519. assigned $-2$. The variables are not yet colored, so they are
  4520. annotated with a dash. We then update the saturation for vertices that
  4521. are adjacent to a register, obtaining the following annotated
  4522. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4523. it interferes with both \code{rax} and \code{rsp}.
  4524. \[
  4525. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4526. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4527. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4528. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4529. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4530. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4531. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4532. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4533. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4534. \draw (t1) to (rax);
  4535. \draw (t1) to (z);
  4536. \draw (z) to (y);
  4537. \draw (z) to (w);
  4538. \draw (x) to (w);
  4539. \draw (y) to (w);
  4540. \draw (v) to (w);
  4541. \draw (v) to (rsp);
  4542. \draw (w) to (rsp);
  4543. \draw (x) to (rsp);
  4544. \draw (y) to (rsp);
  4545. \path[-.,bend left=15] (z) edge node {} (rsp);
  4546. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4547. \draw (rax) to (rsp);
  4548. \end{tikzpicture}
  4549. \]
  4550. The algorithm says to select a maximally saturated vertex. So we pick
  4551. $\ttm{t}$ and color it with the first available integer, which is
  4552. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4553. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4554. \[
  4555. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4556. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4557. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4558. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4559. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4560. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4561. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4562. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4563. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4564. \draw (t1) to (rax);
  4565. \draw (t1) to (z);
  4566. \draw (z) to (y);
  4567. \draw (z) to (w);
  4568. \draw (x) to (w);
  4569. \draw (y) to (w);
  4570. \draw (v) to (w);
  4571. \draw (v) to (rsp);
  4572. \draw (w) to (rsp);
  4573. \draw (x) to (rsp);
  4574. \draw (y) to (rsp);
  4575. \path[-.,bend left=15] (z) edge node {} (rsp);
  4576. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4577. \draw (rax) to (rsp);
  4578. \end{tikzpicture}
  4579. \]
  4580. We repeat the process, selecting a maximally saturated vertex,
  4581. choosing is \code{z}, and color it with the first available number, which
  4582. is $1$. We add $1$ to the saturation for the neighboring vertices
  4583. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4584. \[
  4585. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4586. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4587. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4588. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4589. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4590. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4591. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4592. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4593. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4594. \draw (t1) to (rax);
  4595. \draw (t1) to (z);
  4596. \draw (z) to (y);
  4597. \draw (z) to (w);
  4598. \draw (x) to (w);
  4599. \draw (y) to (w);
  4600. \draw (v) to (w);
  4601. \draw (v) to (rsp);
  4602. \draw (w) to (rsp);
  4603. \draw (x) to (rsp);
  4604. \draw (y) to (rsp);
  4605. \path[-.,bend left=15] (z) edge node {} (rsp);
  4606. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4607. \draw (rax) to (rsp);
  4608. \end{tikzpicture}
  4609. \]
  4610. The most saturated vertices are now \code{w} and \code{y}. We color
  4611. \code{w} with the first available color, which is $0$.
  4612. \[
  4613. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4614. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4615. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4616. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4617. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4618. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4619. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4620. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4621. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4622. \draw (t1) to (rax);
  4623. \draw (t1) to (z);
  4624. \draw (z) to (y);
  4625. \draw (z) to (w);
  4626. \draw (x) to (w);
  4627. \draw (y) to (w);
  4628. \draw (v) to (w);
  4629. \draw (v) to (rsp);
  4630. \draw (w) to (rsp);
  4631. \draw (x) to (rsp);
  4632. \draw (y) to (rsp);
  4633. \path[-.,bend left=15] (z) edge node {} (rsp);
  4634. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4635. \draw (rax) to (rsp);
  4636. \end{tikzpicture}
  4637. \]
  4638. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4639. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4640. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4641. and \code{z}, whose colors are $0$ and $1$ respectively.
  4642. \[
  4643. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4644. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4645. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4646. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4647. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4648. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4649. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4650. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4651. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4652. \draw (t1) to (rax);
  4653. \draw (t1) to (z);
  4654. \draw (z) to (y);
  4655. \draw (z) to (w);
  4656. \draw (x) to (w);
  4657. \draw (y) to (w);
  4658. \draw (v) to (w);
  4659. \draw (v) to (rsp);
  4660. \draw (w) to (rsp);
  4661. \draw (x) to (rsp);
  4662. \draw (y) to (rsp);
  4663. \path[-.,bend left=15] (z) edge node {} (rsp);
  4664. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4665. \draw (rax) to (rsp);
  4666. \end{tikzpicture}
  4667. \]
  4668. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4669. \[
  4670. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4671. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4672. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4673. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4674. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4675. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4676. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4677. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4678. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4679. \draw (t1) to (rax);
  4680. \draw (t1) to (z);
  4681. \draw (z) to (y);
  4682. \draw (z) to (w);
  4683. \draw (x) to (w);
  4684. \draw (y) to (w);
  4685. \draw (v) to (w);
  4686. \draw (v) to (rsp);
  4687. \draw (w) to (rsp);
  4688. \draw (x) to (rsp);
  4689. \draw (y) to (rsp);
  4690. \path[-.,bend left=15] (z) edge node {} (rsp);
  4691. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4692. \draw (rax) to (rsp);
  4693. \end{tikzpicture}
  4694. \]
  4695. In the last step of the algorithm, we color \code{x} with $1$.
  4696. \[
  4697. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4698. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4699. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4700. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4701. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4702. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4703. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4704. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4705. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4706. \draw (t1) to (rax);
  4707. \draw (t1) to (z);
  4708. \draw (z) to (y);
  4709. \draw (z) to (w);
  4710. \draw (x) to (w);
  4711. \draw (y) to (w);
  4712. \draw (v) to (w);
  4713. \draw (v) to (rsp);
  4714. \draw (w) to (rsp);
  4715. \draw (x) to (rsp);
  4716. \draw (y) to (rsp);
  4717. \path[-.,bend left=15] (z) edge node {} (rsp);
  4718. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4719. \draw (rax) to (rsp);
  4720. \end{tikzpicture}
  4721. \]
  4722. So we obtain the following coloring:
  4723. \[
  4724. \{
  4725. \ttm{rax} \mapsto -1,
  4726. \ttm{rsp} \mapsto -2,
  4727. \ttm{t} \mapsto 0,
  4728. \ttm{z} \mapsto 1,
  4729. \ttm{x} \mapsto 1,
  4730. \ttm{y} \mapsto 2,
  4731. \ttm{w} \mapsto 0,
  4732. \ttm{v} \mapsto 1
  4733. \}
  4734. \]
  4735. \fi}
  4736. %
  4737. {\if\edition\pythonEd
  4738. %
  4739. With the DSATUR algorithm in hand, let us return to the running
  4740. example and consider how to color the interference graph in
  4741. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4742. to indicate that it has not yet been assigned a color. The saturation
  4743. sets are also shown for each node; all of them start as the empty set.
  4744. (We do not include the register nodes in the graph below because there
  4745. were no interference edges involving registers in this program, but in
  4746. general there can be.)
  4747. %
  4748. \[
  4749. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4750. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4751. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4752. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4753. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4754. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4755. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4756. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4757. \draw (t0) to (t1);
  4758. \draw (t0) to (z);
  4759. \draw (z) to (y);
  4760. \draw (z) to (w);
  4761. \draw (x) to (w);
  4762. \draw (y) to (w);
  4763. \draw (v) to (w);
  4764. \end{tikzpicture}
  4765. \]
  4766. The algorithm says to select a maximally saturated vertex, but they
  4767. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4768. then color it with the first available integer, which is $0$. We mark
  4769. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4770. they interfere with $\ttm{tmp\_0}$.
  4771. \[
  4772. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4773. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4774. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4775. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4776. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4777. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4778. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4779. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4780. \draw (t0) to (t1);
  4781. \draw (t0) to (z);
  4782. \draw (z) to (y);
  4783. \draw (z) to (w);
  4784. \draw (x) to (w);
  4785. \draw (y) to (w);
  4786. \draw (v) to (w);
  4787. \end{tikzpicture}
  4788. \]
  4789. We repeat the process. The most saturated vertices are \code{z} and
  4790. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4791. available number, which is $1$. We add $1$ to the saturation for the
  4792. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  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}: -, \{\}$};
  4799. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4800. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4801. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  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. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4812. \code{y}. We color \code{w} with the first available color, which
  4813. is $0$.
  4814. \[
  4815. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4816. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4817. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4818. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4819. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4820. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4821. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4822. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4823. \draw (t0) to (t1);
  4824. \draw (t0) to (z);
  4825. \draw (z) to (y);
  4826. \draw (z) to (w);
  4827. \draw (x) to (w);
  4828. \draw (y) to (w);
  4829. \draw (v) to (w);
  4830. \end{tikzpicture}
  4831. \]
  4832. Now \code{y} is the most saturated, so we color it with $2$.
  4833. \[
  4834. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4835. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4836. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4837. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4838. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4839. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4840. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4841. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4842. \draw (t0) to (t1);
  4843. \draw (t0) to (z);
  4844. \draw (z) to (y);
  4845. \draw (z) to (w);
  4846. \draw (x) to (w);
  4847. \draw (y) to (w);
  4848. \draw (v) to (w);
  4849. \end{tikzpicture}
  4850. \]
  4851. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  4852. We choose to color \code{v} with $1$.
  4853. \[
  4854. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4855. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4856. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4857. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4858. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4859. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4860. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4861. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4862. \draw (t0) to (t1);
  4863. \draw (t0) to (z);
  4864. \draw (z) to (y);
  4865. \draw (z) to (w);
  4866. \draw (x) to (w);
  4867. \draw (y) to (w);
  4868. \draw (v) to (w);
  4869. \end{tikzpicture}
  4870. \]
  4871. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4872. \[
  4873. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4874. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4875. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4876. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4877. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4878. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4879. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4880. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4881. \draw (t0) to (t1);
  4882. \draw (t0) to (z);
  4883. \draw (z) to (y);
  4884. \draw (z) to (w);
  4885. \draw (x) to (w);
  4886. \draw (y) to (w);
  4887. \draw (v) to (w);
  4888. \end{tikzpicture}
  4889. \]
  4890. So we obtain the following coloring:
  4891. \[
  4892. \{ \ttm{tmp\_0} \mapsto 0,
  4893. \ttm{tmp\_1} \mapsto 1,
  4894. \ttm{z} \mapsto 1,
  4895. \ttm{x} \mapsto 1,
  4896. \ttm{y} \mapsto 2,
  4897. \ttm{w} \mapsto 0,
  4898. \ttm{v} \mapsto 1 \}
  4899. \]
  4900. \fi}
  4901. We recommend creating an auxiliary function named \code{color\_graph}
  4902. that takes an interference graph and a list of all the variables in
  4903. the program. This function should return a mapping of variables to
  4904. their colors (represented as natural numbers). By creating this helper
  4905. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  4906. when we add support for functions.
  4907. To prioritize the processing of highly saturated nodes inside the
  4908. \code{color\_graph} function, we recommend using the priority queue
  4909. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  4910. addition, you will need to maintain a mapping from variables to their
  4911. ``handles'' in the priority queue so that you can notify the priority
  4912. queue when their saturation changes.}
  4913. {\if\edition\racketEd
  4914. \begin{figure}[tp]
  4915. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4916. \small
  4917. \begin{tcolorbox}[title=Priority Queue]
  4918. A \emph{priority queue} is a collection of items in which the
  4919. removal of items is governed by priority. In a ``min'' queue,
  4920. lower priority items are removed first. An implementation is in
  4921. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4922. queue} \index{subject}{minimum priority queue}
  4923. \begin{description}
  4924. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4925. priority queue that uses the $\itm{cmp}$ predicate to determine
  4926. whether its first argument has lower or equal priority to its
  4927. second argument.
  4928. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4929. items in the queue.
  4930. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4931. the item into the queue and returns a handle for the item in the
  4932. queue.
  4933. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4934. the lowest priority.
  4935. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4936. notifies the queue that the priority has decreased for the item
  4937. associated with the given handle.
  4938. \end{description}
  4939. \end{tcolorbox}
  4940. %\end{wrapfigure}
  4941. \caption{The priority queue data structure.}
  4942. \label{fig:priority-queue}
  4943. \end{figure}
  4944. \fi}
  4945. With the coloring complete, we finalize the assignment of variables to
  4946. registers and stack locations. We map the first $k$ colors to the $k$
  4947. registers and the rest of the colors to stack locations. Suppose for
  4948. the moment that we have just one register to use for register
  4949. allocation, \key{rcx}. Then we have the following map from colors to
  4950. locations.
  4951. \[
  4952. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4953. \]
  4954. Composing this mapping with the coloring, we arrive at the following
  4955. assignment of variables to locations.
  4956. {\if\edition\racketEd
  4957. \begin{gather*}
  4958. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4959. \ttm{w} \mapsto \key{\%rcx}, \,
  4960. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4961. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4962. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4963. \ttm{t} \mapsto \key{\%rcx} \}
  4964. \end{gather*}
  4965. \fi}
  4966. {\if\edition\pythonEd
  4967. \begin{gather*}
  4968. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4969. \ttm{w} \mapsto \key{\%rcx}, \,
  4970. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4971. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4972. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4973. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  4974. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  4975. \end{gather*}
  4976. \fi}
  4977. Adapt the code from the \code{assign\_homes} pass
  4978. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  4979. assigned location. Applying the above assignment to our running
  4980. example, on the left, yields the program on the right.
  4981. % why frame size of 32? -JGS
  4982. \begin{center}
  4983. {\if\edition\racketEd
  4984. \begin{minipage}{0.3\textwidth}
  4985. \begin{lstlisting}
  4986. movq $1, v
  4987. movq $42, w
  4988. movq v, x
  4989. addq $7, x
  4990. movq x, y
  4991. movq x, z
  4992. addq w, z
  4993. movq y, t
  4994. negq t
  4995. movq z, %rax
  4996. addq t, %rax
  4997. jmp conclusion
  4998. \end{lstlisting}
  4999. \end{minipage}
  5000. $\Rightarrow\qquad$
  5001. \begin{minipage}{0.45\textwidth}
  5002. \begin{lstlisting}
  5003. movq $1, -8(%rbp)
  5004. movq $42, %rcx
  5005. movq -8(%rbp), -8(%rbp)
  5006. addq $7, -8(%rbp)
  5007. movq -8(%rbp), -16(%rbp)
  5008. movq -8(%rbp), -8(%rbp)
  5009. addq %rcx, -8(%rbp)
  5010. movq -16(%rbp), %rcx
  5011. negq %rcx
  5012. movq -8(%rbp), %rax
  5013. addq %rcx, %rax
  5014. jmp conclusion
  5015. \end{lstlisting}
  5016. \end{minipage}
  5017. \fi}
  5018. {\if\edition\pythonEd
  5019. \begin{minipage}{0.3\textwidth}
  5020. \begin{lstlisting}
  5021. movq $1, v
  5022. movq $42, w
  5023. movq v, x
  5024. addq $7, x
  5025. movq x, y
  5026. movq x, z
  5027. addq w, z
  5028. movq y, tmp_0
  5029. negq tmp_0
  5030. movq z, tmp_1
  5031. addq tmp_0, tmp_1
  5032. movq tmp_1, %rdi
  5033. callq print_int
  5034. \end{lstlisting}
  5035. \end{minipage}
  5036. $\Rightarrow\qquad$
  5037. \begin{minipage}{0.45\textwidth}
  5038. \begin{lstlisting}
  5039. movq $1, -8(%rbp)
  5040. movq $42, %rcx
  5041. movq -8(%rbp), -8(%rbp)
  5042. addq $7, -8(%rbp)
  5043. movq -8(%rbp), -16(%rbp)
  5044. movq -8(%rbp), -8(%rbp)
  5045. addq %rcx, -8(%rbp)
  5046. movq -16(%rbp), %rcx
  5047. negq %rcx
  5048. movq -8(%rbp), -8(%rbp)
  5049. addq %rcx, -8(%rbp)
  5050. movq -8(%rbp), %rdi
  5051. callq print_int
  5052. \end{lstlisting}
  5053. \end{minipage}
  5054. \fi}
  5055. \end{center}
  5056. \begin{exercise}\normalfont
  5057. %
  5058. Implement the compiler pass \code{allocate\_registers}.
  5059. %
  5060. Create five programs that exercise all aspects of the register
  5061. allocation algorithm, including spilling variables to the stack.
  5062. %
  5063. \racket{Replace \code{assign\_homes} in the list of \code{passes} in the
  5064. \code{run-tests.rkt} script with the three new passes:
  5065. \code{uncover\_live}, \code{build\_interference}, and
  5066. \code{allocate\_registers}.
  5067. %
  5068. Temporarily remove the \code{print\_x86} pass from the list of passes
  5069. and the call to \code{compiler-tests}.
  5070. Run the script to test the register allocator.
  5071. }
  5072. %
  5073. \python{Run the \code{run-tests.py} script to to check whether the
  5074. output programs produce the same result as the input programs.}
  5075. \end{exercise}
  5076. \section{Patch Instructions}
  5077. \label{sec:patch-instructions}
  5078. The remaining step in the compilation to x86 is to ensure that the
  5079. instructions have at most one argument that is a memory access.
  5080. %
  5081. In the running example, the instruction \code{movq -8(\%rbp),
  5082. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  5083. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5084. then move \code{rax} into \code{-16(\%rbp)}.
  5085. %
  5086. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5087. problematic, but they can simply be deleted. In general, we recommend
  5088. deleting all the trivial moves whose source and destination are the
  5089. same location.
  5090. %
  5091. The following is the output of \code{patch\_instructions} on the
  5092. running example.
  5093. \begin{center}
  5094. {\if\edition\racketEd
  5095. \begin{minipage}{0.4\textwidth}
  5096. \begin{lstlisting}
  5097. movq $1, -8(%rbp)
  5098. movq $42, %rcx
  5099. movq -8(%rbp), -8(%rbp)
  5100. addq $7, -8(%rbp)
  5101. movq -8(%rbp), -16(%rbp)
  5102. movq -8(%rbp), -8(%rbp)
  5103. addq %rcx, -8(%rbp)
  5104. movq -16(%rbp), %rcx
  5105. negq %rcx
  5106. movq -8(%rbp), %rax
  5107. addq %rcx, %rax
  5108. jmp conclusion
  5109. \end{lstlisting}
  5110. \end{minipage}
  5111. $\Rightarrow\qquad$
  5112. \begin{minipage}{0.45\textwidth}
  5113. \begin{lstlisting}
  5114. movq $1, -8(%rbp)
  5115. movq $42, %rcx
  5116. addq $7, -8(%rbp)
  5117. movq -8(%rbp), %rax
  5118. movq %rax, -16(%rbp)
  5119. addq %rcx, -8(%rbp)
  5120. movq -16(%rbp), %rcx
  5121. negq %rcx
  5122. movq -8(%rbp), %rax
  5123. addq %rcx, %rax
  5124. jmp conclusion
  5125. \end{lstlisting}
  5126. \end{minipage}
  5127. \fi}
  5128. {\if\edition\pythonEd
  5129. \begin{minipage}{0.4\textwidth}
  5130. \begin{lstlisting}
  5131. movq $1, -8(%rbp)
  5132. movq $42, %rcx
  5133. movq -8(%rbp), -8(%rbp)
  5134. addq $7, -8(%rbp)
  5135. movq -8(%rbp), -16(%rbp)
  5136. movq -8(%rbp), -8(%rbp)
  5137. addq %rcx, -8(%rbp)
  5138. movq -16(%rbp), %rcx
  5139. negq %rcx
  5140. movq -8(%rbp), -8(%rbp)
  5141. addq %rcx, -8(%rbp)
  5142. movq -8(%rbp), %rdi
  5143. callq print_int
  5144. \end{lstlisting}
  5145. \end{minipage}
  5146. $\Rightarrow\qquad$
  5147. \begin{minipage}{0.45\textwidth}
  5148. \begin{lstlisting}
  5149. movq $1, -8(%rbp)
  5150. movq $42, %rcx
  5151. addq $7, -8(%rbp)
  5152. movq -8(%rbp), %rax
  5153. movq %rax, -16(%rbp)
  5154. addq %rcx, -8(%rbp)
  5155. movq -16(%rbp), %rcx
  5156. negq %rcx
  5157. addq %rcx, -8(%rbp)
  5158. movq -8(%rbp), %rdi
  5159. callq print_int
  5160. \end{lstlisting}
  5161. \end{minipage}
  5162. \fi}
  5163. \end{center}
  5164. \begin{exercise}\normalfont
  5165. %
  5166. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5167. %
  5168. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5169. %in the \code{run-tests.rkt} script.
  5170. %
  5171. Run the script to test the \code{patch\_instructions} pass.
  5172. \end{exercise}
  5173. \section{Prelude and Conclusion}
  5174. \label{sec:print-x86-reg-alloc}
  5175. \index{subject}{calling conventions}
  5176. \index{subject}{prelude}\index{subject}{conclusion}
  5177. Recall that this pass generates the prelude and conclusion
  5178. instructions to satisfy the x86 calling conventions
  5179. (Section~\ref{sec:calling-conventions}). With the addition of the
  5180. register allocator, the callee-saved registers used by the register
  5181. allocator must be saved in the prelude and restored in the conclusion.
  5182. In the \code{allocate\_registers} pass,
  5183. %
  5184. \racket{add an entry to the \itm{info}
  5185. of \code{X86Program} named \code{used\_callee}}
  5186. %
  5187. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5188. %
  5189. that stores the set of callee-saved registers that were assigned to
  5190. variables. The \code{prelude\_and\_conclusion} pass can then access
  5191. this information to decide which callee-saved registers need to be
  5192. saved and restored.
  5193. %
  5194. When calculating the size of the frame to adjust the \code{rsp} in the
  5195. prelude, make sure to take into account the space used for saving the
  5196. callee-saved registers. Also, don't forget that the frame needs to be
  5197. a multiple of 16 bytes!
  5198. \racket{An overview of all of the passes involved in register
  5199. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5200. {\if\edition\racketEd
  5201. \begin{figure}[tbp]
  5202. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5203. \node (Lvar) at (0,2) {\large \LangVar{}};
  5204. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5205. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  5206. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5207. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5208. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5209. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5210. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5211. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5212. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5213. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5214. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5215. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5216. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5217. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5218. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5219. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5220. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5221. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  5222. \end{tikzpicture}
  5223. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5224. \label{fig:reg-alloc-passes}
  5225. \end{figure}
  5226. \fi}
  5227. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5228. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5229. use of registers and the stack, we limit the register allocator for
  5230. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5231. the prelude\index{subject}{prelude} of the \code{main} function, we
  5232. push \code{rbx} onto the stack because it is a callee-saved register
  5233. and it was assigned to variable by the register allocator. We
  5234. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5235. reserve space for the one spilled variable. After that subtraction,
  5236. the \code{rsp} is aligned to 16 bytes.
  5237. Moving on to the program proper, we see how the registers were
  5238. allocated.
  5239. %
  5240. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5241. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5242. %
  5243. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5244. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5245. were assigned to \code{rbx}.}
  5246. %
  5247. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5248. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5249. callee-save register \code{rbx} onto the stack. The spilled variables
  5250. must be placed lower on the stack than the saved callee-save
  5251. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5252. \code{-16(\%rbp)}.
  5253. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5254. done in the prelude. We move the stack pointer up by \code{8} bytes
  5255. (the room for spilled variables), then we pop the old values of
  5256. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5257. \code{retq} to return control to the operating system.
  5258. \begin{figure}[tbp]
  5259. % var_test_28.rkt
  5260. % (use-minimal-set-of-registers! #t)
  5261. % and only rbx rcx
  5262. % tmp 0 rbx
  5263. % z 1 rcx
  5264. % y 0 rbx
  5265. % w 2 16(%rbp)
  5266. % v 0 rbx
  5267. % x 0 rbx
  5268. {\if\edition\racketEd
  5269. \begin{lstlisting}
  5270. start:
  5271. movq $1, %rbx
  5272. movq $42, -16(%rbp)
  5273. addq $7, %rbx
  5274. movq %rbx, %rcx
  5275. addq -16(%rbp), %rcx
  5276. negq %rbx
  5277. movq %rcx, %rax
  5278. addq %rbx, %rax
  5279. jmp conclusion
  5280. .globl main
  5281. main:
  5282. pushq %rbp
  5283. movq %rsp, %rbp
  5284. pushq %rbx
  5285. subq $8, %rsp
  5286. jmp start
  5287. conclusion:
  5288. addq $8, %rsp
  5289. popq %rbx
  5290. popq %rbp
  5291. retq
  5292. \end{lstlisting}
  5293. \fi}
  5294. {\if\edition\pythonEd
  5295. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5296. \begin{lstlisting}
  5297. .globl main
  5298. main:
  5299. pushq %rbp
  5300. movq %rsp, %rbp
  5301. pushq %rbx
  5302. subq $8, %rsp
  5303. movq $1, %rcx
  5304. movq $42, %rbx
  5305. addq $7, %rcx
  5306. movq %rcx, -16(%rbp)
  5307. addq %rbx, -16(%rbp)
  5308. negq %rcx
  5309. movq -16(%rbp), %rbx
  5310. addq %rcx, %rbx
  5311. movq %rbx, %rdi
  5312. callq print_int
  5313. addq $8, %rsp
  5314. popq %rbx
  5315. popq %rbp
  5316. retq
  5317. \end{lstlisting}
  5318. \fi}
  5319. \caption{The x86 output from the running example
  5320. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5321. and \code{rcx}.}
  5322. \label{fig:running-example-x86}
  5323. \end{figure}
  5324. \begin{exercise}\normalfont
  5325. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5326. %
  5327. \racket{
  5328. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5329. list of passes and the call to \code{compiler-tests}.}
  5330. %
  5331. Run the script to test the complete compiler for \LangVar{} that
  5332. performs register allocation.
  5333. \end{exercise}
  5334. \section{Challenge: Move Biasing}
  5335. \label{sec:move-biasing}
  5336. \index{subject}{move biasing}
  5337. This section describes an enhancement to the register allocator,
  5338. called move biasing, for students who are looking for an extra
  5339. challenge.
  5340. {\if\edition\racketEd
  5341. To motivate the need for move biasing we return to the running example
  5342. but this time use all of the general purpose registers. So we have
  5343. the following mapping of color numbers to registers.
  5344. \[
  5345. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  5346. \]
  5347. Using the same assignment of variables to color numbers that was
  5348. produced by the register allocator described in the last section, we
  5349. get the following program.
  5350. \begin{center}
  5351. \begin{minipage}{0.3\textwidth}
  5352. \begin{lstlisting}
  5353. movq $1, v
  5354. movq $42, w
  5355. movq v, x
  5356. addq $7, x
  5357. movq x, y
  5358. movq x, z
  5359. addq w, z
  5360. movq y, t
  5361. negq t
  5362. movq z, %rax
  5363. addq t, %rax
  5364. jmp conclusion
  5365. \end{lstlisting}
  5366. \end{minipage}
  5367. $\Rightarrow\qquad$
  5368. \begin{minipage}{0.45\textwidth}
  5369. \begin{lstlisting}
  5370. movq $1, %rdx
  5371. movq $42, %rcx
  5372. movq %rdx, %rdx
  5373. addq $7, %rdx
  5374. movq %rdx, %rsi
  5375. movq %rdx, %rdx
  5376. addq %rcx, %rdx
  5377. movq %rsi, %rcx
  5378. negq %rcx
  5379. movq %rdx, %rax
  5380. addq %rcx, %rax
  5381. jmp conclusion
  5382. \end{lstlisting}
  5383. \end{minipage}
  5384. \end{center}
  5385. In the above output code there are two \key{movq} instructions that
  5386. can be removed because their source and target are the same. However,
  5387. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5388. register, we could instead remove three \key{movq} instructions. We
  5389. can accomplish this by taking into account which variables appear in
  5390. \key{movq} instructions with which other variables.
  5391. \fi}
  5392. {\if\edition\pythonEd
  5393. %
  5394. To motivate the need for move biasing we return to the running example
  5395. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5396. remove three trivial move instructions from the running
  5397. example. However, we could remove another trivial move if we were able
  5398. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5399. We say that two variables $p$ and $q$ are \emph{move
  5400. related}\index{subject}{move related} if they participate together in
  5401. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5402. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5403. when there are multiple variables with the same saturation, prefer
  5404. variables that can be assigned to a color that is the same as the
  5405. color of a move related variable. Furthermore, when the register
  5406. allocator chooses a color for a variable, it should prefer a color
  5407. that has already been used for a move-related variable (assuming that
  5408. they do not interfere). Of course, this preference should not override
  5409. the preference for registers over stack locations. So this preference
  5410. should be used as a tie breaker when choosing between registers or
  5411. when choosing between stack locations.
  5412. We recommend representing the move relationships in a graph, similar
  5413. to how we represented interference. The following is the \emph{move
  5414. graph} for our running example.
  5415. {\if\edition\racketEd
  5416. \[
  5417. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5418. \node (rax) at (0,0) {$\ttm{rax}$};
  5419. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5420. \node (t) at (0,2) {$\ttm{t}$};
  5421. \node (z) at (3,2) {$\ttm{z}$};
  5422. \node (x) at (6,2) {$\ttm{x}$};
  5423. \node (y) at (3,0) {$\ttm{y}$};
  5424. \node (w) at (6,0) {$\ttm{w}$};
  5425. \node (v) at (9,0) {$\ttm{v}$};
  5426. \draw (v) to (x);
  5427. \draw (x) to (y);
  5428. \draw (x) to (z);
  5429. \draw (y) to (t);
  5430. \end{tikzpicture}
  5431. \]
  5432. \fi}
  5433. %
  5434. {\if\edition\pythonEd
  5435. \[
  5436. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5437. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5438. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5439. \node (z) at (3,2) {$\ttm{z}$};
  5440. \node (x) at (6,2) {$\ttm{x}$};
  5441. \node (y) at (3,0) {$\ttm{y}$};
  5442. \node (w) at (6,0) {$\ttm{w}$};
  5443. \node (v) at (9,0) {$\ttm{v}$};
  5444. \draw (y) to (t0);
  5445. \draw (z) to (x);
  5446. \draw (z) to (t1);
  5447. \draw (x) to (y);
  5448. \draw (x) to (v);
  5449. \end{tikzpicture}
  5450. \]
  5451. \fi}
  5452. {\if\edition\racketEd
  5453. Now we replay the graph coloring, pausing to see the coloring of
  5454. \code{y}. Recall the following configuration. The most saturated vertices
  5455. were \code{w} and \code{y}.
  5456. \[
  5457. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5458. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5459. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5460. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5461. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5462. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5463. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5464. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5465. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5466. \draw (t1) to (rax);
  5467. \draw (t1) to (z);
  5468. \draw (z) to (y);
  5469. \draw (z) to (w);
  5470. \draw (x) to (w);
  5471. \draw (y) to (w);
  5472. \draw (v) to (w);
  5473. \draw (v) to (rsp);
  5474. \draw (w) to (rsp);
  5475. \draw (x) to (rsp);
  5476. \draw (y) to (rsp);
  5477. \path[-.,bend left=15] (z) edge node {} (rsp);
  5478. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5479. \draw (rax) to (rsp);
  5480. \end{tikzpicture}
  5481. \]
  5482. %
  5483. Last time we chose to color \code{w} with $0$. But this time we see
  5484. that \code{w} is not move related to any vertex, but \code{y} is move
  5485. related to \code{t}. So we choose to color \code{y} the same color as
  5486. \code{t}, $0$.
  5487. \[
  5488. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5489. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5490. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5491. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5492. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5493. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5494. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5495. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5496. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5497. \draw (t1) to (rax);
  5498. \draw (t1) to (z);
  5499. \draw (z) to (y);
  5500. \draw (z) to (w);
  5501. \draw (x) to (w);
  5502. \draw (y) to (w);
  5503. \draw (v) to (w);
  5504. \draw (v) to (rsp);
  5505. \draw (w) to (rsp);
  5506. \draw (x) to (rsp);
  5507. \draw (y) to (rsp);
  5508. \path[-.,bend left=15] (z) edge node {} (rsp);
  5509. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5510. \draw (rax) to (rsp);
  5511. \end{tikzpicture}
  5512. \]
  5513. Now \code{w} is the most saturated, so we color it $2$.
  5514. \[
  5515. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5516. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5517. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5518. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5519. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5520. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5521. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5522. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5523. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5524. \draw (t1) to (rax);
  5525. \draw (t1) to (z);
  5526. \draw (z) to (y);
  5527. \draw (z) to (w);
  5528. \draw (x) to (w);
  5529. \draw (y) to (w);
  5530. \draw (v) to (w);
  5531. \draw (v) to (rsp);
  5532. \draw (w) to (rsp);
  5533. \draw (x) to (rsp);
  5534. \draw (y) to (rsp);
  5535. \path[-.,bend left=15] (z) edge node {} (rsp);
  5536. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5537. \draw (rax) to (rsp);
  5538. \end{tikzpicture}
  5539. \]
  5540. At this point, vertices \code{x} and \code{v} are most saturated, but
  5541. \code{x} is move related to \code{y} and \code{z}, so we color
  5542. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5543. \[
  5544. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5545. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5546. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5547. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5548. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5549. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5550. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5551. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5552. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5553. \draw (t1) to (rax);
  5554. \draw (t) to (z);
  5555. \draw (z) to (y);
  5556. \draw (z) to (w);
  5557. \draw (x) to (w);
  5558. \draw (y) to (w);
  5559. \draw (v) to (w);
  5560. \draw (v) to (rsp);
  5561. \draw (w) to (rsp);
  5562. \draw (x) to (rsp);
  5563. \draw (y) to (rsp);
  5564. \path[-.,bend left=15] (z) edge node {} (rsp);
  5565. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5566. \draw (rax) to (rsp);
  5567. \end{tikzpicture}
  5568. \]
  5569. \fi}
  5570. %
  5571. {\if\edition\pythonEd
  5572. Now we replay the graph coloring, pausing before the coloring of
  5573. \code{w}. Recall the following configuration. The most saturated vertices
  5574. were \code{tmp\_1}, \code{w}, and \code{y}.
  5575. \[
  5576. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5577. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5578. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5579. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5580. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5581. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5582. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5583. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5584. \draw (t0) to (t1);
  5585. \draw (t0) to (z);
  5586. \draw (z) to (y);
  5587. \draw (z) to (w);
  5588. \draw (x) to (w);
  5589. \draw (y) to (w);
  5590. \draw (v) to (w);
  5591. \end{tikzpicture}
  5592. \]
  5593. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5594. or \code{y}, but note that \code{w} is not move related to any
  5595. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5596. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5597. \code{y} and color it $0$, we can delete another move instruction.
  5598. \[
  5599. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5600. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5601. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5602. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5603. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5604. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5605. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5606. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5607. \draw (t0) to (t1);
  5608. \draw (t0) to (z);
  5609. \draw (z) to (y);
  5610. \draw (z) to (w);
  5611. \draw (x) to (w);
  5612. \draw (y) to (w);
  5613. \draw (v) to (w);
  5614. \end{tikzpicture}
  5615. \]
  5616. Now \code{w} is the most saturated, so we color it $2$.
  5617. \[
  5618. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5619. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5620. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5621. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5622. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5623. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5624. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5625. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5626. \draw (t0) to (t1);
  5627. \draw (t0) to (z);
  5628. \draw (z) to (y);
  5629. \draw (z) to (w);
  5630. \draw (x) to (w);
  5631. \draw (y) to (w);
  5632. \draw (v) to (w);
  5633. \end{tikzpicture}
  5634. \]
  5635. To finish the coloring, \code{x} and \code{v} get $0$ and
  5636. \code{tmp\_1} gets $1$.
  5637. \[
  5638. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5639. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5640. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5641. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5642. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5643. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5644. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5645. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5646. \draw (t0) to (t1);
  5647. \draw (t0) to (z);
  5648. \draw (z) to (y);
  5649. \draw (z) to (w);
  5650. \draw (x) to (w);
  5651. \draw (y) to (w);
  5652. \draw (v) to (w);
  5653. \end{tikzpicture}
  5654. \]
  5655. \fi}
  5656. So we have the following assignment of variables to registers.
  5657. {\if\edition\racketEd
  5658. \begin{gather*}
  5659. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5660. \ttm{w} \mapsto \key{\%rsi}, \,
  5661. \ttm{x} \mapsto \key{\%rcx}, \,
  5662. \ttm{y} \mapsto \key{\%rcx}, \,
  5663. \ttm{z} \mapsto \key{\%rdx}, \,
  5664. \ttm{t} \mapsto \key{\%rcx} \}
  5665. \end{gather*}
  5666. \fi}
  5667. {\if\edition\pythonEd
  5668. \begin{gather*}
  5669. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5670. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5671. \ttm{x} \mapsto \key{\%rcx}, \,
  5672. \ttm{y} \mapsto \key{\%rcx}, \\
  5673. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5674. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5675. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5676. \end{gather*}
  5677. \fi}
  5678. We apply this register assignment to the running example, on the left,
  5679. to obtain the code in the middle. The \code{patch\_instructions} then
  5680. deletes the trivial moves to obtain the code on the right.
  5681. {\if\edition\racketEd
  5682. \begin{minipage}{0.25\textwidth}
  5683. \begin{lstlisting}
  5684. movq $1, v
  5685. movq $42, w
  5686. movq v, x
  5687. addq $7, x
  5688. movq x, y
  5689. movq x, z
  5690. addq w, z
  5691. movq y, t
  5692. negq t
  5693. movq z, %rax
  5694. addq t, %rax
  5695. jmp conclusion
  5696. \end{lstlisting}
  5697. \end{minipage}
  5698. $\Rightarrow\qquad$
  5699. \begin{minipage}{0.25\textwidth}
  5700. \begin{lstlisting}
  5701. movq $1, %rcx
  5702. movq $42, %rsi
  5703. movq %rcx, %rcx
  5704. addq $7, %rcx
  5705. movq %rcx, %rcx
  5706. movq %rcx, %rdx
  5707. addq %rsi, %rdx
  5708. movq %rcx, %rcx
  5709. negq %rcx
  5710. movq %rdx, %rax
  5711. addq %rcx, %rax
  5712. jmp conclusion
  5713. \end{lstlisting}
  5714. \end{minipage}
  5715. $\Rightarrow\qquad$
  5716. \begin{minipage}{0.25\textwidth}
  5717. \begin{lstlisting}
  5718. movq $1, %rcx
  5719. movq $42, %rsi
  5720. addq $7, %rcx
  5721. movq %rcx, %rdx
  5722. addq %rsi, %rdx
  5723. negq %rcx
  5724. movq %rdx, %rax
  5725. addq %rcx, %rax
  5726. jmp conclusion
  5727. \end{lstlisting}
  5728. \end{minipage}
  5729. \fi}
  5730. {\if\edition\pythonEd
  5731. \begin{minipage}{0.20\textwidth}
  5732. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5733. movq $1, v
  5734. movq $42, w
  5735. movq v, x
  5736. addq $7, x
  5737. movq x, y
  5738. movq x, z
  5739. addq w, z
  5740. movq y, tmp_0
  5741. negq tmp_0
  5742. movq z, tmp_1
  5743. addq tmp_0, tmp_1
  5744. movq tmp_1, %rdi
  5745. callq _print_int
  5746. \end{lstlisting}
  5747. \end{minipage}
  5748. ${\Rightarrow\qquad}$
  5749. \begin{minipage}{0.30\textwidth}
  5750. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5751. movq $1, %rcx
  5752. movq $42, -16(%rbp)
  5753. movq %rcx, %rcx
  5754. addq $7, %rcx
  5755. movq %rcx, %rcx
  5756. movq %rcx, -8(%rbp)
  5757. addq -16(%rbp), -8(%rbp)
  5758. movq %rcx, %rcx
  5759. negq %rcx
  5760. movq -8(%rbp), -8(%rbp)
  5761. addq %rcx, -8(%rbp)
  5762. movq -8(%rbp), %rdi
  5763. callq _print_int
  5764. \end{lstlisting}
  5765. \end{minipage}
  5766. ${\Rightarrow\qquad}$
  5767. \begin{minipage}{0.20\textwidth}
  5768. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5769. movq $1, %rcx
  5770. movq $42, -16(%rbp)
  5771. addq $7, %rcx
  5772. movq %rcx, -8(%rbp)
  5773. movq -16(%rbp), %rax
  5774. addq %rax, -8(%rbp)
  5775. negq %rcx
  5776. addq %rcx, -8(%rbp)
  5777. movq -8(%rbp), %rdi
  5778. callq print_int
  5779. \end{lstlisting}
  5780. \end{minipage}
  5781. \fi}
  5782. \begin{exercise}\normalfont
  5783. Change your implementation of \code{allocate\_registers} to take move
  5784. biasing into account. Create two new tests that include at least one
  5785. opportunity for move biasing and visually inspect the output x86
  5786. programs to make sure that your move biasing is working properly. Make
  5787. sure that your compiler still passes all of the tests.
  5788. \end{exercise}
  5789. %To do: another neat challenge would be to do
  5790. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5791. %% \subsection{Output of the Running Example}
  5792. %% \label{sec:reg-alloc-output}
  5793. % challenge: prioritize variables based on execution frequencies
  5794. % and the number of uses of a variable
  5795. % challenge: enhance the coloring algorithm using Chaitin's
  5796. % approach of prioritizing high-degree variables
  5797. % by removing low-degree variables (coloring them later)
  5798. % from the interference graph
  5799. \section{Further Reading}
  5800. \label{sec:register-allocation-further-reading}
  5801. Early register allocation algorithms were developed for Fortran
  5802. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5803. of graph coloring began in the late 1970s and early 1980s with the
  5804. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5805. algorithm is based on the following observation of
  5806. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5807. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5808. $v$ removed is also $k$ colorable. To see why, suppose that the
  5809. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5810. different colors, but since there are less than $k$ neighbors, there
  5811. will be one or more colors left over to use for coloring $v$ in $G$.
  5812. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5813. less than $k$ from the graph and recursively colors the rest of the
  5814. graph. Upon returning from the recursion, it colors $v$ with one of
  5815. the available colors and returns. \citet{Chaitin:1982vn} augments
  5816. this algorithm to handle spilling as follows. If there are no vertices
  5817. of degree lower than $k$ then pick a vertex at random, spill it,
  5818. remove it from the graph, and proceed recursively to color the rest of
  5819. the graph.
  5820. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5821. move-related and that don't interfere with each other, a process
  5822. called \emph{coalescing}. While coalescing decreases the number of
  5823. moves, it can make the graph more difficult to
  5824. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5825. which two variables are merged only if they have fewer than $k$
  5826. neighbors of high degree. \citet{George:1996aa} observe that
  5827. conservative coalescing is sometimes too conservative and make it more
  5828. aggressive by iterating the coalescing with the removal of low-degree
  5829. vertices.
  5830. %
  5831. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5832. also propose \emph{biased coloring} in which a variable is assigned to
  5833. the same color as another move-related variable if possible, as
  5834. discussed in Section~\ref{sec:move-biasing}.
  5835. %
  5836. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5837. performs coalescing, graph coloring, and spill code insertion until
  5838. all variables have been assigned a location.
  5839. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5840. spills variables that don't have to be: a high-degree variable can be
  5841. colorable if many of its neighbors are assigned the same color.
  5842. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5843. high-degree vertex is not immediately spilled. Instead the decision is
  5844. deferred until after the recursive call, at which point it is apparent
  5845. whether there is actually an available color or not. We observe that
  5846. this algorithm is equivalent to the smallest-last ordering
  5847. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5848. be registers and the rest to be stack locations.
  5849. %% biased coloring
  5850. Earlier editions of the compiler course at Indiana University
  5851. \citep{Dybvig:2010aa} were based on the algorithm of
  5852. \citet{Briggs:1994kx}.
  5853. The smallest-last ordering algorithm is one of many \emph{greedy}
  5854. coloring algorithms. A greedy coloring algorithm visits all the
  5855. vertices in a particular order and assigns each one the first
  5856. available color. An \emph{offline} greedy algorithm chooses the
  5857. ordering up-front, prior to assigning colors. The algorithm of
  5858. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5859. ordering does not depend on the colors assigned. Other orderings are
  5860. possible. For example, \citet{Chow:1984ys} order variables according
  5861. to an estimate of runtime cost.
  5862. An \emph{online} greedy coloring algorithm uses information about the
  5863. current assignment of colors to influence the order in which the
  5864. remaining vertices are colored. The saturation-based algorithm
  5865. described in this chapter is one such algorithm. We choose to use
  5866. saturation-based coloring because it is fun to introduce graph
  5867. coloring via Sudoku!
  5868. A register allocator may choose to map each variable to just one
  5869. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5870. variable to one or more locations. The later can be achieved by
  5871. \emph{live range splitting}, where a variable is replaced by several
  5872. variables that each handle part of its live
  5873. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5874. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5875. %% replacement algorithm, bottom-up local
  5876. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5877. %% Cooper: top-down (priority bassed), bottom-up
  5878. %% top-down
  5879. %% order variables by priority (estimated cost)
  5880. %% caveat: split variables into two groups:
  5881. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5882. %% color the constrained ones first
  5883. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5884. %% cite J. Cocke for an algorithm that colors variables
  5885. %% in a high-degree first ordering
  5886. %Register Allocation via Usage Counts, Freiburghouse CACM
  5887. \citet{Palsberg:2007si} observe that many of the interference graphs
  5888. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5889. that is, every cycle with four or more edges has an edge which is not
  5890. part of the cycle but which connects two vertices on the cycle. Such
  5891. graphs can be optimally colored by the greedy algorithm with a vertex
  5892. ordering determined by maximum cardinality search.
  5893. In situations where compile time is of utmost importance, such as in
  5894. just-in-time compilers, graph coloring algorithms can be too expensive
  5895. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  5896. appropriate.
  5897. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5898. \chapter{Booleans and Conditionals}
  5899. \label{ch:Lif}
  5900. \index{subject}{Boolean}
  5901. \index{subject}{control flow}
  5902. \index{subject}{conditional expression}
  5903. The \LangInt{} and \LangVar{} languages only have a single kind of
  5904. value, the integers. In this chapter we add a second kind of value,
  5905. the Booleans, to create the \LangIf{} language. The Boolean values
  5906. \emph{true} and \emph{false} are written \TRUE{} and \FALSE{}
  5907. respectively in \racket{Racket}\python{Python}. The \LangIf{}
  5908. language includes several operations that involve Booleans (\key{and},
  5909. \key{not}, \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the
  5910. \key{if} expression \python{and statement}. With the addition of
  5911. \key{if}, programs can have non-trivial control flow which
  5912. %
  5913. \racket{impacts \code{explicate\_control} and liveness analysis}
  5914. %
  5915. \python{impacts liveness analysis and motivates a new pass named
  5916. \code{explicate\_control}}.
  5917. %
  5918. Also, because we now have two kinds of values, we need to handle
  5919. programs that apply an operation to the wrong kind of value, such as
  5920. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5921. There are two language design options for such situations. One option
  5922. is to signal an error and the other is to provide a wider
  5923. interpretation of the operation. \racket{The Racket
  5924. language}\python{Python} uses a mixture of these two options,
  5925. depending on the operation and the kind of value. For example, the
  5926. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  5927. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  5928. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  5929. %
  5930. \racket{On the other hand, \code{(car 1)} results in a run-time error
  5931. in Racket because \code{car} expects a pair.}
  5932. %
  5933. \python{On the other hand, \code{1[0]} results in a run-time error
  5934. in Python because an ``\code{int} object is not subscriptable''.}
  5935. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  5936. design choices as \racket{Racket}\python{Python}, except much of the
  5937. error detection happens at compile time instead of run
  5938. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  5939. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  5940. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  5941. Racket}\python{MyPy} reports a compile-time error
  5942. %
  5943. \racket{because Racket expects the type of the argument to be of the form
  5944. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  5945. %
  5946. \python{stating that a ``value of type \code{int} is not indexable''.}
  5947. The \LangIf{} language performs type checking during compilation like
  5948. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Rdyn} we study the
  5949. alternative choice, that is, a dynamically typed language like
  5950. \racket{Racket}\python{Python}.
  5951. The \LangIf{} language is a subset of \racket{Typed Racket}\python{MyPy};
  5952. for some operations we are more restrictive, for example, rejecting
  5953. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5954. This chapter is organized as follows. We begin by defining the syntax
  5955. and interpreter for the \LangIf{} language
  5956. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  5957. checking and define a type checker for \LangIf{}
  5958. (Section~\ref{sec:type-check-Lif}).
  5959. %
  5960. \racket{To compile \LangIf{} we need to enlarge the intermediate
  5961. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  5962. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  5963. %
  5964. The remaining sections of this chapter discuss how the addition of
  5965. Booleans and conditional control flow to the language requires changes
  5966. to the existing compiler passes and the addition of new ones. In
  5967. particular, we introduce the \code{shrink} pass to translates some
  5968. operators into others, thereby reducing the number of operators that
  5969. need to be handled in later passes.
  5970. %
  5971. The main event of this chapter is the \code{explicate\_control} pass
  5972. that is responsible for translating \code{if}'s into conditional
  5973. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  5974. %
  5975. Regarding register allocation, there is the interesting question of
  5976. how to handle conditional \code{goto}'s during liveness analysis.
  5977. \section{The \LangIf{} Language}
  5978. \label{sec:lang-if}
  5979. The concrete and abstract syntax of the \LangIf{} language are defined in
  5980. Figures~\ref{fig:Lif-concrete-syntax} and~\ref{fig:Lif-syntax},
  5981. respectively. The \LangIf{} language includes all of
  5982. \LangVar{} {(shown in gray)}, the Boolean literals \TRUE{} and
  5983. \FALSE{},\racket{ and} the \code{if} expression\python{, and the
  5984. \code{if} statement}. We expand the set of operators to include
  5985. \begin{enumerate}
  5986. \item subtraction on integers,
  5987. \item the logical operators \key{and}, \key{or}, and \key{not},
  5988. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  5989. for comparing integers or Booleans for equality, and
  5990. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  5991. comparing integers.
  5992. \end{enumerate}
  5993. \racket{We reorganize the abstract syntax for the primitive
  5994. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  5995. rule for all of them. This means that the grammar no longer checks
  5996. whether the arity of an operators matches the number of
  5997. arguments. That responsibility is moved to the type checker for
  5998. \LangIf{}, which we introduce in Section~\ref{sec:type-check-Lif}.}
  5999. \newcommand{\LifGrammarRacket}{
  6000. \begin{array}{lcl}
  6001. \Type &::=& \key{Boolean} \\
  6002. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6003. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6004. \Exp &::=& \CSUB{\Exp}{\Exp} \MID \itm{bool}
  6005. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6006. \MID (\key{not}\;\Exp) \\
  6007. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6008. \end{array}
  6009. }
  6010. \newcommand{\LifASTRacket}{
  6011. \begin{array}{lcl}
  6012. \Type &::=& \key{Boolean} \\
  6013. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6014. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6015. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6016. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6017. \end{array}
  6018. }
  6019. \newcommand{\LintOpAST}{
  6020. \begin{array}{rcl}
  6021. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6022. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6023. \end{array}
  6024. }
  6025. \newcommand{\LifGrammarPython}{
  6026. \begin{array}{rcl}
  6027. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6028. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6029. \MID \key{not}~\Exp \\
  6030. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6031. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6032. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6033. \end{array}
  6034. }
  6035. \newcommand{\LifASTPython}{
  6036. \begin{array}{lcl}
  6037. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6038. \itm{unaryop} &::=& \code{Not()} \\
  6039. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6040. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6041. \Exp &::=& \BOOL{\itm{bool}}
  6042. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6043. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6044. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6045. \end{array}
  6046. }
  6047. \begin{figure}[tp]
  6048. \centering
  6049. \fbox{
  6050. \begin{minipage}{0.96\textwidth}
  6051. {\if\edition\racketEd
  6052. \[
  6053. \begin{array}{l}
  6054. \gray{\LintGrammarRacket{}} \\ \hline
  6055. \gray{\LvarGrammarRacket{}} \\ \hline
  6056. \LifGrammarRacket{} \\
  6057. \begin{array}{lcl}
  6058. \LangIfM{} &::=& \Exp
  6059. \end{array}
  6060. \end{array}
  6061. \]
  6062. \fi}
  6063. {\if\edition\pythonEd
  6064. \[
  6065. \begin{array}{l}
  6066. \gray{\LintGrammarPython} \\ \hline
  6067. \gray{\LvarGrammarPython} \\ \hline
  6068. \LifGrammarPython \\
  6069. \begin{array}{rcl}
  6070. \LangIfM{} &::=& \Stmt^{*}
  6071. \end{array}
  6072. \end{array}
  6073. \]
  6074. \fi}
  6075. \end{minipage}
  6076. }
  6077. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6078. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6079. \label{fig:Lif-concrete-syntax}
  6080. \end{figure}
  6081. \begin{figure}[tp]
  6082. \centering
  6083. \fbox{
  6084. \begin{minipage}{0.96\textwidth}
  6085. {\if\edition\racketEd
  6086. \[
  6087. \begin{array}{l}
  6088. \gray{\LintOpAST} \\ \hline
  6089. \gray{\LvarASTRacket{}} \\ \hline
  6090. \LifASTRacket{} \\
  6091. \begin{array}{lcl}
  6092. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6093. \end{array}
  6094. \end{array}
  6095. \]
  6096. \fi}
  6097. {\if\edition\pythonEd
  6098. \[
  6099. \begin{array}{l}
  6100. \gray{\LintASTPython} \\ \hline
  6101. \gray{\LvarASTPython} \\ \hline
  6102. \LifASTPython \\
  6103. \begin{array}{lcl}
  6104. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6105. \end{array}
  6106. \end{array}
  6107. \]
  6108. \fi}
  6109. \end{minipage}
  6110. }
  6111. \caption{The abstract syntax of \LangIf{}.}
  6112. \label{fig:Lif-syntax}
  6113. \end{figure}
  6114. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  6115. which inherits from the interpreter for \LangVar{}
  6116. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6117. evaluate to the corresponding Boolean values. The conditional
  6118. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  6119. and then either evaluates $e_2$ or $e_3$ depending on whether
  6120. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  6121. \code{and}, \code{or}, and \code{not} behave according to
  6122. propositional logic. In addition, the \code{and} and \code{or}
  6123. operations perform \emph{short-circuit evaluation}.
  6124. %
  6125. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6126. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6127. %
  6128. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6129. evaluated if $e_1$ evaluates to \TRUE{}.
  6130. \racket{With the increase in the number of primitive operations, the
  6131. interpreter would become repetitive without some care. We refactor
  6132. the case for \code{Prim}, moving the code that differs with each
  6133. operation into the \code{interp\_op} method shown in in
  6134. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6135. \code{or} operations separately because of their short-circuiting
  6136. behavior.}
  6137. \begin{figure}[tbp]
  6138. {\if\edition\racketEd
  6139. \begin{lstlisting}
  6140. (define interp_Lif_class
  6141. (class interp_Lvar_class
  6142. (super-new)
  6143. (define/public (interp_op op) ...)
  6144. (define/override ((interp_exp env) e)
  6145. (define recur (interp_exp env))
  6146. (match e
  6147. [(Bool b) b]
  6148. [(If cnd thn els)
  6149. (match (recur cnd)
  6150. [#t (recur thn)]
  6151. [#f (recur els)])]
  6152. [(Prim 'and (list e1 e2))
  6153. (match (recur e1)
  6154. [#t (match (recur e2) [#t #t] [#f #f])]
  6155. [#f #f])]
  6156. [(Prim 'or (list e1 e2))
  6157. (define v1 (recur e1))
  6158. (match v1
  6159. [#t #t]
  6160. [#f (match (recur e2) [#t #t] [#f #f])])]
  6161. [(Prim op args)
  6162. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6163. [else ((super interp_exp env) e)]))
  6164. ))
  6165. (define (interp_Lif p)
  6166. (send (new interp_Lif_class) interp_program p))
  6167. \end{lstlisting}
  6168. \fi}
  6169. {\if\edition\pythonEd
  6170. \begin{lstlisting}
  6171. class InterpLif(InterpLvar):
  6172. def interp_exp(self, e, env):
  6173. match e:
  6174. case IfExp(test, body, orelse):
  6175. if self.interp_exp(test, env):
  6176. return self.interp_exp(body, env)
  6177. else:
  6178. return self.interp_exp(orelse, env)
  6179. case BinOp(left, Sub(), right):
  6180. return self.interp_exp(left, env) - self.interp_exp(right, env)
  6181. case UnaryOp(Not(), v):
  6182. return not self.interp_exp(v, env)
  6183. case BoolOp(And(), values):
  6184. if self.interp_exp(values[0], env):
  6185. return self.interp_exp(values[1], env)
  6186. else:
  6187. return False
  6188. case BoolOp(Or(), values):
  6189. if self.interp_exp(values[0], env):
  6190. return True
  6191. else:
  6192. return self.interp_exp(values[1], env)
  6193. case Compare(left, [cmp], [right]):
  6194. l = self.interp_exp(left, env)
  6195. r = self.interp_exp(right, env)
  6196. return self.interp_cmp(cmp)(l, r)
  6197. case _:
  6198. return super().interp_exp(e, env)
  6199. def interp_stmts(self, ss, env):
  6200. if len(ss) == 0:
  6201. return
  6202. match ss[0]:
  6203. case If(test, body, orelse):
  6204. if self.interp_exp(test, env):
  6205. return self.interp_stmts(body + ss[1:], env)
  6206. else:
  6207. return self.interp_stmts(orelse + ss[1:], env)
  6208. case _:
  6209. return super().interp_stmts(ss, env)
  6210. ...
  6211. \end{lstlisting}
  6212. \fi}
  6213. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6214. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6215. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6216. \label{fig:interp-Lif}
  6217. \end{figure}
  6218. {\if\edition\racketEd
  6219. \begin{figure}[tbp]
  6220. \begin{lstlisting}
  6221. (define/public (interp_op op)
  6222. (match op
  6223. ['+ fx+]
  6224. ['- fx-]
  6225. ['read read-fixnum]
  6226. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6227. ['eq? (lambda (v1 v2)
  6228. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6229. (and (boolean? v1) (boolean? v2))
  6230. (and (vector? v1) (vector? v2)))
  6231. (eq? v1 v2)]))]
  6232. ['< (lambda (v1 v2)
  6233. (cond [(and (fixnum? v1) (fixnum? v2))
  6234. (< v1 v2)]))]
  6235. ['<= (lambda (v1 v2)
  6236. (cond [(and (fixnum? v1) (fixnum? v2))
  6237. (<= v1 v2)]))]
  6238. ['> (lambda (v1 v2)
  6239. (cond [(and (fixnum? v1) (fixnum? v2))
  6240. (> v1 v2)]))]
  6241. ['>= (lambda (v1 v2)
  6242. (cond [(and (fixnum? v1) (fixnum? v2))
  6243. (>= v1 v2)]))]
  6244. [else (error 'interp_op "unknown operator")]))
  6245. \end{lstlisting}
  6246. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6247. \label{fig:interp-op-Lif}
  6248. \end{figure}
  6249. \fi}
  6250. {\if\edition\pythonEd
  6251. \begin{figure}
  6252. \begin{lstlisting}
  6253. class InterpLif(InterpLvar):
  6254. ...
  6255. def interp_cmp(self, cmp):
  6256. match cmp:
  6257. case Lt():
  6258. return lambda x, y: x < y
  6259. case LtE():
  6260. return lambda x, y: x <= y
  6261. case Gt():
  6262. return lambda x, y: x > y
  6263. case GtE():
  6264. return lambda x, y: x >= y
  6265. case Eq():
  6266. return lambda x, y: x == y
  6267. case NotEq():
  6268. return lambda x, y: x != y
  6269. \end{lstlisting}
  6270. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6271. \label{fig:interp-cmp-Lif}
  6272. \end{figure}
  6273. \fi}
  6274. \section{Type Checking \LangIf{} Programs}
  6275. \label{sec:type-check-Lif}
  6276. \index{subject}{type checking}
  6277. \index{subject}{semantic analysis}
  6278. It is helpful to think about type checking in two complementary
  6279. ways. A type checker predicts the type of value that will be produced
  6280. by each expression in the program. For \LangIf{}, we have just two types,
  6281. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6282. {\if\edition\racketEd
  6283. \begin{lstlisting}
  6284. (+ 10 (- (+ 12 20)))
  6285. \end{lstlisting}
  6286. \fi}
  6287. {\if\edition\pythonEd
  6288. \begin{lstlisting}
  6289. 10 + -(12 + 20)
  6290. \end{lstlisting}
  6291. \fi}
  6292. \noindent produces a value of type \INTTY{} while
  6293. {\if\edition\racketEd
  6294. \begin{lstlisting}
  6295. (and (not #f) #t)
  6296. \end{lstlisting}
  6297. \fi}
  6298. {\if\edition\pythonEd
  6299. \begin{lstlisting}
  6300. (not False) and True
  6301. \end{lstlisting}
  6302. \fi}
  6303. \noindent produces a value of type \BOOLTY{}.
  6304. A second way to think about type checking is that it enforces a set of
  6305. rules about which operators can be applied to which kinds of
  6306. values. For example, our type checker for \LangIf{} signals an error
  6307. for the below expression {\if\edition\racketEd
  6308. \begin{lstlisting}
  6309. (not (+ 10 (- (+ 12 20))))
  6310. \end{lstlisting}
  6311. \fi}
  6312. {\if\edition\pythonEd
  6313. \begin{lstlisting}
  6314. not (10 + -(12 + 20))
  6315. \end{lstlisting}
  6316. \fi}
  6317. The subexpression
  6318. \racket{\code{(+ 10 (- (+ 12 20)))}}\python{\code{(10 + -(12 + 20))}}
  6319. has type \INTTY{} but the type checker enforces the rule that the argument of
  6320. \code{not} must be an expression of type \BOOLTY{}.
  6321. We implement type checking using classes and methods because they
  6322. provide the open recursion needed to reuse code as we extend the type
  6323. checker in later chapters, analogous to the use of classes and methods
  6324. for the interpreters (Section~\ref{sec:extensible-interp}).
  6325. We separate the type checker for the \LangVar{} subset into its own
  6326. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6327. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6328. from the type checker for \LangVar{}. These type checkers are in the
  6329. files
  6330. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6331. and
  6332. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6333. of the support code.
  6334. %
  6335. Each type checker is a structurally recursive function over the AST.
  6336. Given an input expression \code{e}, the type checker either signals an
  6337. error or returns \racket{an expression and} its type (\INTTY{} or
  6338. \BOOLTY{}).
  6339. %
  6340. \racket{It returns an expression because there are situations in which
  6341. we want to change or update the expression.}
  6342. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6343. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6344. \INTTY{}. To handle variables, the type checker uses the environment
  6345. \code{env} to map variables to types.
  6346. %
  6347. \racket{Consider the case for \key{let}. We type check the
  6348. initializing expression to obtain its type \key{T} and then
  6349. associate type \code{T} with the variable \code{x} in the
  6350. environment used to type check the body of the \key{let}. Thus,
  6351. when the type checker encounters a use of variable \code{x}, it can
  6352. find its type in the environment.}
  6353. %
  6354. \python{Consider the case for assignment. We type check the
  6355. initializing expression to obtain its type \key{t}. If the variable
  6356. \code{lhs.id} is already in the environment because there was a
  6357. prior assignment, we check that this initializer has the same type
  6358. as the prior one. If this is the first assignment to the variable,
  6359. we associate type \code{t} with the variable \code{lhs.id} in the
  6360. environment. Thus, when the type checker encounters a use of
  6361. variable \code{x}, it can find its type in the environment.}
  6362. %
  6363. \racket{Regarding primitive operators, we recursively analyze the
  6364. arguments and then invoke \code{type\_check\_op} to check whether
  6365. the argument types are allowed.}
  6366. %
  6367. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  6368. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  6369. \racket{Several auxiliary methods are used in the type checker. The
  6370. method \code{operator-types} defines a dictionary that maps the
  6371. operator names to their parameter and return types. The
  6372. \code{type-equal?} method determines whether two types are equal,
  6373. which for now simply dispatches to \code{equal?} (deep
  6374. equality). The \code{check-type-equal?} method triggers an error if
  6375. the two types are not equal. The \code{type-check-op} method looks
  6376. up the operator in the \code{operator-types} dictionary and then
  6377. checks whether the argument types are equal to the parameter types.
  6378. The result is the return type of the operator.}
  6379. %
  6380. \python{The auxiliary method \code{check\_type\_equal} triggers
  6381. an error if the two types are not equal.}
  6382. \begin{figure}[tbp]
  6383. {\if\edition\racketEd
  6384. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6385. (define type-check-Lvar_class
  6386. (class object%
  6387. (super-new)
  6388. (define/public (operator-types)
  6389. '((+ . ((Integer Integer) . Integer))
  6390. (- . ((Integer) . Integer))
  6391. (read . (() . Integer))))
  6392. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6393. (define/public (check-type-equal? t1 t2 e)
  6394. (unless (type-equal? t1 t2)
  6395. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6396. (define/public (type-check-op op arg-types e)
  6397. (match (dict-ref (operator-types) op)
  6398. [`(,param-types . ,return-type)
  6399. (for ([at arg-types] [pt param-types])
  6400. (check-type-equal? at pt e))
  6401. return-type]
  6402. [else (error 'type-check-op "unrecognized ~a" op)]))
  6403. (define/public (type-check-exp env)
  6404. (lambda (e)
  6405. (match e
  6406. [(Int n) (values (Int n) 'Integer)]
  6407. [(Var x) (values (Var x) (dict-ref env x))]
  6408. [(Let x e body)
  6409. (define-values (e^ Te) ((type-check-exp env) e))
  6410. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6411. (values (Let x e^ b) Tb)]
  6412. [(Prim op es)
  6413. (define-values (new-es ts)
  6414. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6415. (values (Prim op new-es) (type-check-op op ts e))]
  6416. [else (error 'type-check-exp "couldn't match" e)])))
  6417. (define/public (type-check-program e)
  6418. (match e
  6419. [(Program info body)
  6420. (define-values (body^ Tb) ((type-check-exp '()) body))
  6421. (check-type-equal? Tb 'Integer body)
  6422. (Program info body^)]
  6423. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6424. ))
  6425. (define (type-check-Lvar p)
  6426. (send (new type-check-Lvar_class) type-check-program p))
  6427. \end{lstlisting}
  6428. \fi}
  6429. {\if\edition\pythonEd
  6430. \begin{lstlisting}[escapechar=`]
  6431. class TypeCheckLvar:
  6432. def check_type_equal(self, t1, t2, e):
  6433. if t1 != t2:
  6434. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6435. raise Exception(msg)
  6436. def type_check_exp(self, e, env):
  6437. match e:
  6438. case BinOp(left, (Add() | Sub()), right):
  6439. l = self.type_check_exp(left, env)
  6440. check_type_equal(l, int, left)
  6441. r = self.type_check_exp(right, env)
  6442. check_type_equal(r, int, right)
  6443. return int
  6444. case UnaryOp(USub(), v):
  6445. t = self.type_check_exp(v, env)
  6446. check_type_equal(t, int, v)
  6447. return int
  6448. case Name(id):
  6449. return env[id]
  6450. case Constant(value) if isinstance(value, int):
  6451. return int
  6452. case Call(Name('input_int'), []):
  6453. return int
  6454. def type_check_stmts(self, ss, env):
  6455. if len(ss) == 0:
  6456. return
  6457. match ss[0]:
  6458. case Assign([lhs], value):
  6459. t = self.type_check_exp(value, env)
  6460. if lhs.id in env:
  6461. check_type_equal(env[lhs.id], t, value)
  6462. else:
  6463. env[lhs.id] = t
  6464. return self.type_check_stmts(ss[1:], env)
  6465. case Expr(Call(Name('print'), [arg])):
  6466. t = self.type_check_exp(arg, env)
  6467. check_type_equal(t, int, arg)
  6468. return self.type_check_stmts(ss[1:], env)
  6469. case Expr(value):
  6470. self.type_check_exp(value, env)
  6471. return self.type_check_stmts(ss[1:], env)
  6472. def type_check_P(self, p):
  6473. match p:
  6474. case Module(body):
  6475. self.type_check_stmts(body, {})
  6476. \end{lstlisting}
  6477. \fi}
  6478. \caption{Type checker for the \LangVar{} language.}
  6479. \label{fig:type-check-Lvar}
  6480. \end{figure}
  6481. \begin{figure}[tbp]
  6482. {\if\edition\racketEd
  6483. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6484. (define type-check-Lif_class
  6485. (class type-check-Lvar_class
  6486. (super-new)
  6487. (inherit check-type-equal?)
  6488. (define/override (operator-types)
  6489. (append '((- . ((Integer Integer) . Integer))
  6490. (and . ((Boolean Boolean) . Boolean))
  6491. (or . ((Boolean Boolean) . Boolean))
  6492. (< . ((Integer Integer) . Boolean))
  6493. (<= . ((Integer Integer) . Boolean))
  6494. (> . ((Integer Integer) . Boolean))
  6495. (>= . ((Integer Integer) . Boolean))
  6496. (not . ((Boolean) . Boolean))
  6497. )
  6498. (super operator-types)))
  6499. (define/override (type-check-exp env)
  6500. (lambda (e)
  6501. (match e
  6502. [(Bool b) (values (Bool b) 'Boolean)]
  6503. [(Prim 'eq? (list e1 e2))
  6504. (define-values (e1^ T1) ((type-check-exp env) e1))
  6505. (define-values (e2^ T2) ((type-check-exp env) e2))
  6506. (check-type-equal? T1 T2 e)
  6507. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6508. [(If cnd thn els)
  6509. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6510. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6511. (define-values (els^ Te) ((type-check-exp env) els))
  6512. (check-type-equal? Tc 'Boolean e)
  6513. (check-type-equal? Tt Te e)
  6514. (values (If cnd^ thn^ els^) Te)]
  6515. [else ((super type-check-exp env) e)])))
  6516. ))
  6517. (define (type-check-Lif p)
  6518. (send (new type-check-Lif_class) type-check-program p))
  6519. \end{lstlisting}
  6520. \fi}
  6521. {\if\edition\pythonEd
  6522. \begin{lstlisting}
  6523. class TypeCheckLif(TypeCheckLvar):
  6524. def type_check_exp(self, e, env):
  6525. match e:
  6526. case Constant(value) if isinstance(value, bool):
  6527. return bool
  6528. case BinOp(left, Sub(), right):
  6529. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6530. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6531. return int
  6532. case UnaryOp(Not(), v):
  6533. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6534. return bool
  6535. case BoolOp(op, values):
  6536. left = values[0] ; right = values[1]
  6537. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6538. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6539. return bool
  6540. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6541. or isinstance(cmp, NotEq):
  6542. l = self.type_check_exp(left, env)
  6543. r = self.type_check_exp(right, env)
  6544. check_type_equal(l, r, e)
  6545. return bool
  6546. case Compare(left, [cmp], [right]):
  6547. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6548. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6549. return bool
  6550. case IfExp(test, body, orelse):
  6551. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6552. b = self.type_check_exp(body, env)
  6553. o = self.type_check_exp(orelse, env)
  6554. check_type_equal(b, o, e)
  6555. return b
  6556. case _:
  6557. return super().type_check_exp(e, env)
  6558. def type_check_stmts(self, ss, env):
  6559. if len(ss) == 0:
  6560. return
  6561. match ss[0]:
  6562. case If(test, body, orelse):
  6563. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6564. b = self.type_check_stmts(body, env)
  6565. o = self.type_check_stmts(orelse, env)
  6566. check_type_equal(b, o, ss[0])
  6567. return self.type_check_stmts(ss[1:], env)
  6568. case _:
  6569. return super().type_check_stmts(ss, env)
  6570. \end{lstlisting}
  6571. \fi}
  6572. \caption{Type checker for the \LangIf{} language.}
  6573. \label{fig:type-check-Lif}
  6574. \end{figure}
  6575. We shift our focus to Figure~\ref{fig:type-check-Lif}, the type
  6576. checker for \LangIf{}.
  6577. %
  6578. The type of a Boolean constant is \BOOLTY{}.
  6579. %
  6580. \racket{The \code{operator-types} function adds dictionary entries for
  6581. the other new operators.}
  6582. %
  6583. \python{Logical not requires its argument to be a \BOOLTY{} and
  6584. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6585. %
  6586. The equality operators require the two arguments to have the same
  6587. type.
  6588. %
  6589. \python{The other comparisons (less-than, etc.) require their
  6590. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6591. %
  6592. The condition of an \code{if} must
  6593. be of \BOOLTY{} type and the two branches must have the same type.
  6594. \begin{exercise}\normalfont
  6595. Create 10 new test programs in \LangIf{}. Half of the programs should
  6596. have a type error. For those programs, create an empty file with the
  6597. same base name but with file extension \code{.tyerr}. For example, if
  6598. the test
  6599. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6600. is expected to error, then create
  6601. an empty file named \code{cond\_test\_14.tyerr}.
  6602. %
  6603. \racket{This indicates to \code{interp-tests} and
  6604. \code{compiler-tests} that a type error is expected. }
  6605. %
  6606. \racket{This indicates to the \code{run-tests.rkt} scripts that a type
  6607. error is expected.}
  6608. %
  6609. The other half of the test programs should not have type errors.
  6610. %
  6611. \racket{In the \code{run-tests.rkt} script, change the second argument
  6612. of \code{interp-tests} and \code{compiler-tests} to
  6613. \code{type-check-Lif}, which causes the type checker to run prior to
  6614. the compiler passes. Temporarily change the \code{passes} to an
  6615. empty list and run the script, thereby checking that the new test
  6616. programs either type check or not as intended.}
  6617. %
  6618. Run the test script to check that these test programs type check as
  6619. expected.
  6620. \end{exercise}
  6621. \clearpage
  6622. \section{The \LangCIf{} Intermediate Language}
  6623. \label{sec:Cif}
  6624. {\if\edition\racketEd
  6625. %
  6626. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6627. \LangCIf{} intermediate language and Figure~\ref{fig:c1-syntax}
  6628. defines its abstract syntax. Compared to \LangCVar{}, the \LangCIf{}
  6629. language adds logical and comparison operators to the \Exp{}
  6630. non-terminal and the literals \TRUE{} and \FALSE{} to the \Arg{}
  6631. non-terminal.
  6632. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  6633. statements to the \Tail{} non-terminal. The condition of an \code{if}
  6634. statement is a comparison operation and the branches are \code{goto}
  6635. statements, making it straightforward to compile \code{if} statements
  6636. to x86.
  6637. %
  6638. \fi}
  6639. %
  6640. {\if\edition\pythonEd
  6641. %
  6642. The output of \key{explicate\_control} is a language similar to the
  6643. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6644. \code{goto} statements, so we name it \LangCIf{}. The
  6645. concrete syntax for \LangCIf{} is defined in
  6646. Figure~\ref{fig:c1-concrete-syntax}
  6647. and the abstract syntax is defined in Figure~\ref{fig:c1-syntax}.
  6648. %
  6649. The \LangCIf{} language supports the same operators as \LangIf{} but
  6650. the arguments of operators are restricted to atomic expressions. The
  6651. \LangCIf{} language does not include \code{if} expressions but it does
  6652. include a restricted form of \code{if} statment. The condition must be
  6653. a comparison and the two branches may only contain \code{goto}
  6654. statements. These restrictions make it easier to translate \code{if}
  6655. statements to x86.
  6656. %
  6657. \fi}
  6658. %
  6659. Besides the \code{goto} statement, \LangCIf{}, also adds a
  6660. \code{return} statement to finish a function call with a specified value.
  6661. %
  6662. The \key{CProgram} construct contains
  6663. %
  6664. \racket{an alist}\python{a dictionary}
  6665. %
  6666. mapping labels to
  6667. \racket{$\Tail$ expressions, which can be \code{return} statements,
  6668. an assignment statement followed by a $\Tail$ expression, a
  6669. \code{goto}, or a conditional \code{goto}.}
  6670. \python{lists of statements, which comprise of assignment statements
  6671. and end in a \code{return} statement, a \code{goto}, or a
  6672. conditional \code{goto}.
  6673. \index{subject}{basic block}
  6674. Statement lists of this form are called
  6675. \emph{basic blocks}: there is a control transfer at the end and
  6676. control only enters at the beginning of the list, which is marked by
  6677. the label. }
  6678. \newcommand{\CifGrammarRacket}{
  6679. \begin{array}{lcl}
  6680. \Atm &::=& \itm{bool} \\
  6681. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6682. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6683. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  6684. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  6685. \end{array}
  6686. }
  6687. \newcommand{\CifASTRacket}{
  6688. \begin{array}{lcl}
  6689. \Atm &::=& \BOOL{\itm{bool}} \\
  6690. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6691. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6692. \Tail &::= & \GOTO{\itm{label}} \\
  6693. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  6694. \end{array}
  6695. }
  6696. \newcommand{\CifGrammarPython}{
  6697. \begin{array}{lcl}
  6698. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  6699. \Exp &::= & \Atm \MID \CREAD{}
  6700. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  6701. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  6702. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  6703. \Stmt &::=& \CPRINT{\Exp} \MID \Exp \\
  6704. &\MID& \CASSIGN{\Var}{\Exp}
  6705. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  6706. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  6707. \end{array}
  6708. }
  6709. \newcommand{\CifASTPython}{
  6710. \begin{array}{lcl}
  6711. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6712. \Exp &::= & \Atm \MID \READ{} \\
  6713. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6714. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6715. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  6716. \Stmt &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  6717. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6718. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6719. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  6720. \end{array}
  6721. }
  6722. \begin{figure}[tbp]
  6723. \fbox{
  6724. \begin{minipage}{0.96\textwidth}
  6725. \small
  6726. {\if\edition\racketEd
  6727. \[
  6728. \begin{array}{l}
  6729. \gray{\CvarGrammarRacket} \\ \hline
  6730. \CifGrammarRacket \\
  6731. \begin{array}{lcl}
  6732. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  6733. \end{array}
  6734. \end{array}
  6735. \]
  6736. \fi}
  6737. {\if\edition\pythonEd
  6738. \[
  6739. \begin{array}{l}
  6740. \CifGrammarPython \\
  6741. \begin{array}{lcl}
  6742. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  6743. \end{array}
  6744. \end{array}
  6745. \]
  6746. \fi}
  6747. \end{minipage}
  6748. }
  6749. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  6750. \label{fig:c1-concrete-syntax}
  6751. \end{figure}
  6752. \begin{figure}[tp]
  6753. \fbox{
  6754. \begin{minipage}{0.96\textwidth}
  6755. \small
  6756. {\if\edition\racketEd
  6757. \[
  6758. \begin{array}{l}
  6759. \gray{\CvarASTRacket} \\ \hline
  6760. \CifASTRacket \\
  6761. \begin{array}{lcl}
  6762. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  6763. \end{array}
  6764. \end{array}
  6765. \]
  6766. \fi}
  6767. {\if\edition\pythonEd
  6768. \[
  6769. \begin{array}{l}
  6770. \CifASTPython \\
  6771. \begin{array}{lcl}
  6772. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  6773. \end{array}
  6774. \end{array}
  6775. \]
  6776. \fi}
  6777. \end{minipage}
  6778. }
  6779. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6780. (Figure~\ref{fig:c0-syntax})}.}
  6781. \label{fig:c1-syntax}
  6782. \end{figure}
  6783. \section{The \LangXIf{} Language}
  6784. \label{sec:x86-if}
  6785. \index{subject}{x86} To implement the new logical operations, the comparison
  6786. operations, and the \key{if} expression\python{ and statement}, we need to delve further into
  6787. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  6788. define the concrete and abstract syntax for the \LangXIf{} subset
  6789. of x86, which includes instructions for logical operations,
  6790. comparisons, and \racket{conditional} jumps.
  6791. One challenge is that x86 does not provide an instruction that
  6792. directly implements logical negation (\code{not} in \LangIf{} and
  6793. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6794. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6795. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6796. bit of its arguments, and writes the results into its second argument.
  6797. Recall the truth table for exclusive-or:
  6798. \begin{center}
  6799. \begin{tabular}{l|cc}
  6800. & 0 & 1 \\ \hline
  6801. 0 & 0 & 1 \\
  6802. 1 & 1 & 0
  6803. \end{tabular}
  6804. \end{center}
  6805. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6806. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6807. for the bit $1$, the result is the opposite of the second bit. Thus,
  6808. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6809. the first argument as follows, where $\Arg$ is the translation of
  6810. $\Atm$.
  6811. \[
  6812. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  6813. \qquad\Rightarrow\qquad
  6814. \begin{array}{l}
  6815. \key{movq}~ \Arg\key{,} \Var\\
  6816. \key{xorq}~ \key{\$1,} \Var
  6817. \end{array}
  6818. \]
  6819. \begin{figure}[tp]
  6820. \fbox{
  6821. \begin{minipage}{0.96\textwidth}
  6822. \[
  6823. \begin{array}{lcl}
  6824. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6825. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6826. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  6827. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6828. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  6829. \key{subq} \; \Arg\key{,} \Arg \MID
  6830. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  6831. && \gray{ \key{callq} \; \itm{label} \MID
  6832. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \racket{\key{jmp}\,\itm{label} \MID} } \python{\key{jmp}\,\itm{label} \MID} \\
  6833. && \racket{\gray{ \itm{label}\key{:}\; \Instr }}\python{\itm{label}\key{:}\; \Instr}
  6834. \MID \key{xorq}~\Arg\key{,}~\Arg
  6835. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  6836. && \key{set}cc~\Arg
  6837. \MID \key{movzbq}~\Arg\key{,}~\Arg
  6838. \MID \key{j}cc~\itm{label}
  6839. \\
  6840. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  6841. & & \gray{ \key{main:} \; \Instr\ldots }
  6842. \end{array}
  6843. \]
  6844. \end{minipage}
  6845. }
  6846. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6847. \label{fig:x86-1-concrete}
  6848. \end{figure}
  6849. \begin{figure}[tp]
  6850. \fbox{
  6851. \begin{minipage}{0.98\textwidth}
  6852. \small
  6853. {\if\edition\racketEd
  6854. \[
  6855. \begin{array}{lcl}
  6856. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6857. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6858. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6859. \MID \BYTEREG{\itm{bytereg}} \\
  6860. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6861. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6862. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6863. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  6864. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6865. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6866. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6867. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6868. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6869. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6870. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6871. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}} \\
  6872. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  6873. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  6874. \end{array}
  6875. \]
  6876. \fi}
  6877. %
  6878. {\if\edition\pythonEd
  6879. \[
  6880. \begin{array}{lcl}
  6881. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  6882. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  6883. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6884. \MID \BYTEREG{\itm{bytereg}} \\
  6885. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6886. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  6887. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  6888. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  6889. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  6890. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6891. \MID \PUSHQ{\Arg}} \\
  6892. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  6893. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  6894. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  6895. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  6896. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  6897. &\MID& \JMPIF{\key{'}\itm{cc}\key{'}}{\itm{label}} \\
  6898. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Instr^{*} \key{,} \ldots \RC }
  6899. \end{array}
  6900. \]
  6901. \fi}
  6902. \end{minipage}
  6903. }
  6904. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  6905. \label{fig:x86-1}
  6906. \end{figure}
  6907. Next we consider the x86 instructions that are relevant for compiling
  6908. the comparison operations. The \key{cmpq} instruction compares its two
  6909. arguments to determine whether one argument is less than, equal, or
  6910. greater than the other argument. The \key{cmpq} instruction is unusual
  6911. regarding the order of its arguments and where the result is
  6912. placed. The argument order is backwards: if you want to test whether
  6913. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  6914. \key{cmpq} is placed in the special EFLAGS register. This register
  6915. cannot be accessed directly but it can be queried by a number of
  6916. instructions, including the \key{set} instruction. The instruction
  6917. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  6918. depending on whether the comparison comes out according to the
  6919. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  6920. for less-or-equal, \key{g} for greater, \key{ge} for
  6921. greater-or-equal). The \key{set} instruction has a quirk in
  6922. that its destination argument must be single byte register, such as
  6923. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  6924. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  6925. instruction can be used to move from a single byte register to a
  6926. normal 64-bit register. The abstract syntax for the \code{set}
  6927. instruction differs from the concrete syntax in that it separates the
  6928. instruction name from the condition code.
  6929. \python{The x86 instructions for jumping are relevant to the
  6930. compilation of \key{if} expressions.}
  6931. %
  6932. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  6933. counter to the address of the instruction after the specified
  6934. label.}
  6935. %
  6936. \racket{The x86 instruction for conditional jump is relevant to the
  6937. compilation of \key{if} expressions.}
  6938. %
  6939. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  6940. counter to point to the instruction after \itm{label} depending on
  6941. whether the result in the EFLAGS register matches the condition code
  6942. \itm{cc}, otherwise the jump instruction falls through to the next
  6943. instruction. Like the abstract syntax for \code{set}, the abstract
  6944. syntax for conditional jump separates the instruction name from the
  6945. condition code. For example, \JMPIF{\key{'le'}}{\key{foo}} corresponds
  6946. to \code{jle foo}. Because the conditional jump instruction relies on
  6947. the EFLAGS register, it is common for it to be immediately preceded by
  6948. a \key{cmpq} instruction to set the EFLAGS register.
  6949. \section{Shrink the \LangIf{} Language}
  6950. \label{sec:shrink-Lif}
  6951. The \LangIf{} language includes several features that are easily
  6952. expressible with other features. For example, \code{and} and \code{or}
  6953. are expressible using \code{if} as follows.
  6954. \begin{align*}
  6955. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  6956. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  6957. \end{align*}
  6958. By performing these translations in the front-end of the compiler,
  6959. subsequent passes of the compiler do not need to deal with these features,
  6960. making the passes shorter.
  6961. %% For example, subtraction is
  6962. %% expressible using addition and negation.
  6963. %% \[
  6964. %% \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  6965. %% \]
  6966. %% Several of the comparison operations are expressible using less-than
  6967. %% and logical negation.
  6968. %% \[
  6969. %% \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  6970. %% \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  6971. %% \]
  6972. %% The \key{let} is needed in the above translation to ensure that
  6973. %% expression $e_1$ is evaluated before $e_2$.
  6974. On the other hand, sometimes translations reduce the efficiency of the
  6975. generated code by increasing the number of instructions. For example,
  6976. expressing subtraction in terms of negation
  6977. \[
  6978. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  6979. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  6980. \]
  6981. produces code with two x86 instructions (\code{negq} and \code{addq})
  6982. instead of just one (\code{subq}).
  6983. %% However,
  6984. %% these differences typically do not affect the number of accesses to
  6985. %% memory, which is the primary factor that determines execution time on
  6986. %% modern computer architectures.
  6987. \begin{exercise}\normalfont
  6988. %
  6989. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  6990. the language by translating them to \code{if} expressions in \LangIf{}.
  6991. %
  6992. Create four test programs that involve these operators.
  6993. %
  6994. {\if\edition\racketEd
  6995. In the \code{run-tests.rkt} script, add the following entry for
  6996. \code{shrink} to the list of passes (it should be the only pass at
  6997. this point).
  6998. \begin{lstlisting}
  6999. (list "shrink" shrink interp_Lif type-check-Lif)
  7000. \end{lstlisting}
  7001. This instructs \code{interp-tests} to run the intepreter
  7002. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7003. output of \code{shrink}.
  7004. \fi}
  7005. %
  7006. Run the script to test your compiler on all the test programs.
  7007. \end{exercise}
  7008. {\if\edition\racketEd
  7009. \section{Uniquify Variables}
  7010. \label{sec:uniquify-Lif}
  7011. Add cases to \code{uniquify-exp} to handle Boolean constants and
  7012. \code{if} expressions.
  7013. \begin{exercise}\normalfont
  7014. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  7015. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  7016. \begin{lstlisting}
  7017. (list "uniquify" uniquify interp_Lif type_check_Lif)
  7018. \end{lstlisting}
  7019. Run the script to test your compiler.
  7020. \end{exercise}
  7021. \fi}
  7022. \section{Remove Complex Operands}
  7023. \label{sec:remove-complex-opera-Lif}
  7024. The output language of \code{remove\_complex\_operands} is
  7025. \LangIfANF{} (Figure~\ref{fig:Lif-anf-syntax}), the administrative
  7026. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  7027. but the \code{if} expression is not. All three sub-expressions of an
  7028. \code{if} are allowed to be complex expressions but the operands of
  7029. \code{not} and the comparisons must be atomic.
  7030. %
  7031. \python{We add a new language form, the \code{Let} expression, to aid
  7032. in the translation of \code{if} expressions. When we recursively
  7033. process the two branches of the \code{if}, we generate temporary
  7034. variables and their initializing expressions. However, these
  7035. expressions may contain side effects and should only be executed
  7036. when the condition of the \code{if} is true (for the ``then''
  7037. branch) or false (for the ``else'' branch). The \code{Let} provides
  7038. a way to initialize the temporary variables within the two branches
  7039. of the \code{if} expression. In general, the $\LET{x}{e_1}{e_2}$
  7040. form assigns the result of $e_1$ to the variable $x$, and then
  7041. evaluates $e_2$, which may reference $x$.}
  7042. Add cases for Boolean constants, \python{comparisons,} and \code{if}
  7043. expressions to the \code{rco\_exp} and \code{rco\_atom} functions
  7044. according to whether the output needs to be \Exp{} or \Atm{} as
  7045. specified in the grammar for \LangIfANF{}. Regarding \code{if}, it is
  7046. particularly important to \textbf{not} replace its condition with a
  7047. temporary variable because that would interfere with the generation of
  7048. high-quality output in the \code{explicate\_control} pass.
  7049. \newcommand{\LifASTMonadPython}{
  7050. \begin{array}{rcl}
  7051. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7052. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7053. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7054. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7055. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  7056. \Exp &::=& \Atm \MID \READ{} \\
  7057. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  7058. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7059. &\MID& \LET{\Var}{\Exp}{\Exp}\\
  7060. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7061. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}\\
  7062. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7063. \end{array}
  7064. }
  7065. \begin{figure}[tp]
  7066. \centering
  7067. \fbox{
  7068. \begin{minipage}{0.96\textwidth}
  7069. {\if\edition\racketEd
  7070. \[
  7071. \begin{array}{rcl}
  7072. Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  7073. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  7074. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  7075. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7076. &\MID& \UNIOP{\key{not}}{\Atm} \\
  7077. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7078. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7079. \end{array}
  7080. \]
  7081. \fi}
  7082. {\if\edition\pythonEd
  7083. \[
  7084. \begin{array}{l}
  7085. \LifASTMonadPython \\
  7086. % \begin{array}{rcl}
  7087. % \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7088. % \end{array}
  7089. \end{array}
  7090. \]
  7091. \fi}
  7092. \end{minipage}
  7093. }
  7094. \caption{\LangIfANF{} is \LangIf{} in monadic normal form.}
  7095. \label{fig:Lif-anf-syntax}
  7096. \end{figure}
  7097. \begin{exercise}\normalfont
  7098. %
  7099. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7100. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7101. %
  7102. Create three new \LangIf{} programs that exercise the interesting
  7103. code in this pass.
  7104. %
  7105. {\if\edition\racketEd
  7106. In the \code{run-tests.rkt} script, add the following entry to the
  7107. list of \code{passes} and then run the script to test your compiler.
  7108. \begin{lstlisting}
  7109. (list "remove-complex" remove-complex-opera* interp-Lif type-check-Lif)
  7110. \end{lstlisting}
  7111. \fi}
  7112. \end{exercise}
  7113. \section{Explicate Control}
  7114. \label{sec:explicate-control-Lif}
  7115. \racket{Recall that the purpose of \code{explicate\_control} is to
  7116. make the order of evaluation explicit in the syntax of the program.
  7117. With the addition of \key{if} this get more interesting.}
  7118. %
  7119. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7120. %
  7121. The main challenge to overcome is that the condition of an \key{if}
  7122. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  7123. condition must be a comparison.
  7124. As a motivating example, consider the following program that has an
  7125. \key{if} expression nested in the condition of another \key{if}.%
  7126. \python{\footnote{Programmers rarely write nested \code{if}
  7127. expressions, but it is not uncommon for the condition of an
  7128. \code{if} statement to be a call of a function that also contains an
  7129. \code{if} statement. When such a function is inlined, the result is
  7130. a nested \code{if} that requires the techniques discussed in this
  7131. section.}}
  7132. % cond_test_41.rkt, if_lt_eq.py
  7133. \begin{center}
  7134. \begin{minipage}{0.96\textwidth}
  7135. {\if\edition\racketEd
  7136. \begin{lstlisting}
  7137. (let ([x (read)])
  7138. (let ([y (read)])
  7139. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7140. (+ y 2)
  7141. (+ y 10))))
  7142. \end{lstlisting}
  7143. \fi}
  7144. {\if\edition\pythonEd
  7145. \begin{lstlisting}
  7146. x = input_int()
  7147. y = input_int()
  7148. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7149. \end{lstlisting}
  7150. \fi}
  7151. \end{minipage}
  7152. \end{center}
  7153. %
  7154. The naive way to compile \key{if} and the comparison operations would
  7155. be to handle each of them in isolation, regardless of their context.
  7156. Each comparison would be translated into a \key{cmpq} instruction
  7157. followed by several instructions to move the result from the EFLAGS
  7158. register into a general purpose register or stack location. Each
  7159. \key{if} would be translated into a \key{cmpq} instruction followed by
  7160. a conditional jump. The generated code for the inner \key{if} in the
  7161. above example would be as follows.
  7162. \begin{center}
  7163. \begin{minipage}{0.96\textwidth}
  7164. \begin{lstlisting}
  7165. cmpq $1, x
  7166. setl %al
  7167. movzbq %al, tmp
  7168. cmpq $1, tmp
  7169. je then_branch_1
  7170. jmp else_branch_1
  7171. \end{lstlisting}
  7172. \end{minipage}
  7173. \end{center}
  7174. However, if we take context into account we can do better and reduce
  7175. the use of \key{cmpq} instructions for accessing the EFLAG register.
  7176. Our goal will be to compile \key{if} expressions so that the relevant
  7177. comparison instruction appears directly before the conditional jump.
  7178. For example, we want to generate the following code for the inner
  7179. \code{if}.
  7180. \begin{center}
  7181. \begin{minipage}{0.96\textwidth}
  7182. \begin{lstlisting}
  7183. cmpq $1, x
  7184. jl then_branch_1
  7185. jmp else_branch_1
  7186. \end{lstlisting}
  7187. \end{minipage}
  7188. \end{center}
  7189. One way to achieve this goal is to reorganize the code at the level of
  7190. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7191. the following code.
  7192. \begin{center}
  7193. \begin{minipage}{0.96\textwidth}
  7194. {\if\edition\racketEd
  7195. \begin{lstlisting}
  7196. (let ([x (read)])
  7197. (let ([y (read)])
  7198. (if (< x 1)
  7199. (if (eq? x 0)
  7200. (+ y 2)
  7201. (+ y 10))
  7202. (if (eq? x 2)
  7203. (+ y 2)
  7204. (+ y 10)))))
  7205. \end{lstlisting}
  7206. \fi}
  7207. {\if\edition\pythonEd
  7208. \begin{lstlisting}
  7209. x = input_int()
  7210. y = intput_int()
  7211. print(((y + 2) if x == 0 else (y + 10)) \
  7212. if (x < 1) \
  7213. else ((y + 2) if (x == 2) else (y + 10)))
  7214. \end{lstlisting}
  7215. \fi}
  7216. \end{minipage}
  7217. \end{center}
  7218. Unfortunately, this approach duplicates the two branches from the
  7219. outer \code{if} and a compiler must never duplicate code! After all,
  7220. the two branches could have been very large expressions.
  7221. We need a way to perform the above transformation but without
  7222. duplicating code. That is, we need a way for different parts of a
  7223. program to refer to the same piece of code.
  7224. %
  7225. Put another way, we need to move away from abstract syntax
  7226. \emph{trees} and instead use \emph{graphs}.
  7227. %
  7228. At the level of x86 assembly this is straightforward because we can
  7229. label the code for each branch and insert jumps in all the places that
  7230. need to execute the branch.
  7231. %
  7232. Likewise, our language \LangCIf{} provides the ability to label a
  7233. sequence of code and to jump to a label via \code{goto}.
  7234. %
  7235. %% In particular, we use a standard program representation called a
  7236. %% \emph{control flow graph} (CFG), due to Frances Elizabeth
  7237. %% \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex
  7238. %% is a labeled sequence of code, called a \emph{basic block}, and each
  7239. %% edge represents a jump to another block.
  7240. %
  7241. %% The nice thing about the output of \code{explicate\_control} is that
  7242. %% there are no unnecessary comparisons and every comparison is part of a
  7243. %% conditional jump.
  7244. %% The down-side of this output is that it includes
  7245. %% trivial blocks, such as the blocks labeled \code{block92} through
  7246. %% \code{block95}, that only jump to another block. We discuss a solution
  7247. %% to this problem in Section~\ref{sec:opt-jumps}.
  7248. {\if\edition\racketEd
  7249. %
  7250. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  7251. \code{explicate\_control} for \LangVar{} using two mutually recursive
  7252. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7253. former function translates expressions in tail position whereas the
  7254. later function translates expressions on the right-hand-side of a
  7255. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  7256. have a new kind of position to deal with: the predicate position of
  7257. the \key{if}. We need another function, \code{explicate\_pred}, that
  7258. decides how to compile an \key{if} by analyzing its predicate. So
  7259. \code{explicate\_pred} takes an \LangIf{} expression and two \LangCIf{}
  7260. tails for the then-branch and else-branch and outputs a tail. In the
  7261. following paragraphs we discuss specific cases in the
  7262. \code{explicate\_tail}, \code{explicate\_assign}, and
  7263. \code{explicate\_pred} functions.
  7264. %
  7265. \fi}
  7266. %
  7267. {\if\edition\pythonEd
  7268. %
  7269. We recommend implementing \code{explicate\_control} using the
  7270. following four auxiliary functions.
  7271. \begin{description}
  7272. \item[\code{explicate\_effect}] generates code for expressions as
  7273. statements, so their result is ignored and only their side effects
  7274. matter.
  7275. \item[\code{explicate\_assign}] generates code for expressions
  7276. on the right-hand side of an assignment.
  7277. \item[\code{explicate\_pred}] generates code for an \code{if}
  7278. expression or statement by analyzing the condition expression.
  7279. \item[\code{explicate\_stmt}] generates code for statements.
  7280. \end{description}
  7281. These four functions should build the dictionary of basic blocks. The
  7282. following auxiliary function can be used to create a new basic block
  7283. from a list of statements. It returns a \code{goto} statement that
  7284. jumps to the new basic block.
  7285. \begin{center}
  7286. \begin{minipage}{\textwidth}
  7287. \begin{lstlisting}
  7288. def create_block(stmts, basic_blocks):
  7289. label = label_name(generate_name('block'))
  7290. basic_blocks[label] = stmts
  7291. return Goto(label)
  7292. \end{lstlisting}
  7293. \end{minipage}
  7294. \end{center}
  7295. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7296. \code{explicate\_control} pass.
  7297. The \code{explicate\_effect} function has three parameters: 1) the
  7298. expression to be compiled, 2) the already-compiled code for this
  7299. expression's \emph{continuation}, that is, the list of statements that
  7300. should execute after this expression, and 3) the dictionary of
  7301. generated basic blocks. The \code{explicate\_effect} function returns
  7302. a list of \LangCIf{} statements and it may add to the dictionary of
  7303. basic blocks.
  7304. %
  7305. Let's consider a few of the cases for the expression to be compiled.
  7306. If the expression to be compiled is a constant, then it can be
  7307. discarded because it has no side effects. If it's a \CREAD{}, then it
  7308. has a side-effect and should be preserved. So the expression should be
  7309. translated into a statement using the \code{Expr} AST class. If the
  7310. expression to be compiled is an \code{if} expression, we translate the
  7311. two branches using \code{explicate\_effect} and then translate the
  7312. condition expression using \code{explicate\_pred}, which generates
  7313. code for the entire \code{if}.
  7314. The \code{explicate\_assign} function has four parameters: 1) the
  7315. right-hand-side of the assignment, 2) the left-hand-side of the
  7316. assignment (the variable), 3) the continuation, and 4) the dictionary
  7317. of basic blocks. The \code{explicate\_assign} function returns a list
  7318. of \LangCIf{} statements and it may add to the dictionary of basic
  7319. blocks.
  7320. When the right-hand-side is an \code{if} expression, there is some
  7321. work to do. In particular, the two branches should be translated using
  7322. \code{explicate\_assign} and the condition expression should be
  7323. translated using \code{explicate\_pred}. Otherwise we can simply
  7324. generate an assignment statement, with the given left and right-hand
  7325. sides, concatenated with its continuation.
  7326. \begin{figure}[tbp]
  7327. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7328. def explicate_effect(e, cont, basic_blocks):
  7329. match e:
  7330. case IfExp(test, body, orelse):
  7331. ...
  7332. case Call(func, args):
  7333. ...
  7334. case Let(var, rhs, body):
  7335. ...
  7336. case _:
  7337. ...
  7338. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7339. match rhs:
  7340. case IfExp(test, body, orelse):
  7341. ...
  7342. case Let(var, rhs, body):
  7343. ...
  7344. case _:
  7345. return [Assign([lhs], rhs)] + cont
  7346. def explicate_pred(cnd, thn, els, basic_blocks):
  7347. match cnd:
  7348. case Compare(left, [op], [right]):
  7349. goto_thn = create_block(thn, basic_blocks)
  7350. goto_els = create_block(els, basic_blocks)
  7351. return [If(cnd, [goto_thn], [goto_els])]
  7352. case Constant(True):
  7353. return thn;
  7354. case Constant(False):
  7355. return els;
  7356. case UnaryOp(Not(), operand):
  7357. ...
  7358. case IfExp(test, body, orelse):
  7359. ...
  7360. case Let(var, rhs, body):
  7361. ...
  7362. case _:
  7363. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7364. [create_block(els, basic_blocks)],
  7365. [create_block(thn, basic_blocks)])]
  7366. def explicate_stmt(s, cont, basic_blocks):
  7367. match s:
  7368. case Assign([lhs], rhs):
  7369. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7370. case Expr(value):
  7371. return explicate_effect(value, cont, basic_blocks)
  7372. case If(test, body, orelse):
  7373. ...
  7374. def explicate_control(p):
  7375. match p:
  7376. case Module(body):
  7377. new_body = [Return(Constant(0))]
  7378. basic_blocks = {}
  7379. for s in reversed(body):
  7380. new_body = explicate_stmt(s, new_body, basic_blocks)
  7381. basic_blocks[label_name('start')] = new_body
  7382. return CProgram(basic_blocks)
  7383. \end{lstlisting}
  7384. \caption{Skeleton for the \code{explicate\_control} pass.}
  7385. \label{fig:explicate-control-Lif}
  7386. \end{figure}
  7387. \fi}
  7388. {\if\edition\racketEd
  7389. %
  7390. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7391. additional cases for Boolean constants and \key{if}. The cases for
  7392. \code{if} should recursively compile the two branches using either
  7393. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7394. cases should then invoke \code{explicate\_pred} on the condition
  7395. expression, passing in the generated code for the two branches. For
  7396. example, consider the following program with an \code{if} in tail
  7397. position.
  7398. \begin{lstlisting}
  7399. (let ([x (read)])
  7400. (if (eq? x 0) 42 777))
  7401. \end{lstlisting}
  7402. The two branches are recursively compiled to \code{return 42;} and
  7403. \code{return 777;}. We then delegate to \code{explicate\_pred},
  7404. passing the condition \code{(eq? x 0)} and the two return statements, which is
  7405. used as the result for \code{explicate\_tail}.
  7406. Next let us consider a program with an \code{if} on the right-hand
  7407. side of a \code{let}.
  7408. \begin{lstlisting}
  7409. (let ([y (read)])
  7410. (let ([x (if (eq? y 0) 40 777)])
  7411. (+ x 2)))
  7412. \end{lstlisting}
  7413. Note that the body of the inner \code{let} will have already been
  7414. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7415. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7416. to recursively process both branches of the \code{if}, so we generate
  7417. the following block using an auxiliary function named \code{create\_block}.
  7418. \begin{lstlisting}
  7419. block_6:
  7420. return (+ x 2)
  7421. \end{lstlisting}
  7422. and use \code{goto block\_6;} as the \code{cont} argument for
  7423. compiling the branches. So the two branches compile to
  7424. \begin{lstlisting}
  7425. x = 40;
  7426. goto block_6;
  7427. \end{lstlisting}
  7428. and
  7429. \begin{lstlisting}
  7430. x = 777;
  7431. goto block_6;
  7432. \end{lstlisting}
  7433. We then delegate to \code{explicate\_pred}, passing the condition \code{(eq? y
  7434. 0)} and the above code for the branches.
  7435. \fi}
  7436. {\if\edition\racketEd
  7437. \begin{figure}[tbp]
  7438. \begin{lstlisting}
  7439. (define (explicate_pred cnd thn els)
  7440. (match cnd
  7441. [(Var x) ___]
  7442. [(Let x rhs body) ___]
  7443. [(Prim 'not (list e)) ___]
  7444. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7445. (IfStmt (Prim op es) (create_block thn)
  7446. (create_block els))]
  7447. [(Bool b) (if b thn els)]
  7448. [(If cnd^ thn^ els^) ___]
  7449. [else (error "explicate_pred unhandled case" cnd)]))
  7450. \end{lstlisting}
  7451. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7452. \label{fig:explicate-pred}
  7453. \end{figure}
  7454. \fi}
  7455. \racket{The skeleton for the \code{explicate\_pred} function is given
  7456. in Figure~\ref{fig:explicate-pred}. It takes three parameters:
  7457. 1) \code{cnd}, the condition expression of the \code{if},
  7458. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7459. and 3) \code{els}, the code generated by
  7460. explicate for the ``else'' branch. The \code{explicate\_pred}
  7461. function should match on \code{cnd} with a case for
  7462. every kind of expression that can have type \code{Boolean}.}
  7463. %
  7464. \python{The \code{explicate\_pred} function has four parameters: 1)
  7465. the condition expression, 2) the generated statements for the
  7466. ``then'' branch, 3) the generated statements for the ``else''
  7467. branch, and 4) the dictionary of basic blocks. The
  7468. \code{explicate\_pred} function returns a list of \LangCIf{}
  7469. statements and it may add to the dictionary of basic blocks.}
  7470. Consider the case for comparison operators. We translate the
  7471. comparison to an \code{if} statement whose branches are \code{goto}
  7472. statements created by applying \code{create\_block} to the code
  7473. generated for the \code{thn} and \code{els} branches. Let us
  7474. illustrate this translation with an example. Returning
  7475. to the program with an \code{if} expression in tail position,
  7476. we invoke \code{explicate\_pred} on its condition
  7477. \racket{\code{(eq? x 0)}}
  7478. \python{\code{x == 0}}
  7479. which happens to be a comparison operator.
  7480. {\if\edition\racketEd
  7481. \begin{lstlisting}
  7482. (let ([x (read)])
  7483. (if (eq? x 0) 42 777))
  7484. \end{lstlisting}
  7485. \fi}
  7486. {\if\edition\pythonEd
  7487. \begin{lstlisting}
  7488. x = input_int()
  7489. 42 if x == 0 else 777
  7490. \end{lstlisting}
  7491. \fi}
  7492. The two branches \code{42} and \code{777} were already compiled to \code{return}
  7493. statements, from which we now create the following blocks.
  7494. \begin{center}
  7495. \begin{minipage}{\textwidth}
  7496. \begin{lstlisting}
  7497. block_1:
  7498. return 42;
  7499. block_2:
  7500. return 777;
  7501. \end{lstlisting}
  7502. \end{minipage}
  7503. \end{center}
  7504. %
  7505. So \code{explicate\_pred} compiles the comparison
  7506. \racket{\code{(eq? x 0)}}
  7507. \python{\code{x == 0}}
  7508. to the following \code{if} statement.
  7509. %
  7510. {\if\edition\racketEd
  7511. \begin{center}
  7512. \begin{minipage}{\textwidth}
  7513. \begin{lstlisting}
  7514. if (eq? x 0)
  7515. goto block_1;
  7516. else
  7517. goto block_2;
  7518. \end{lstlisting}
  7519. \end{minipage}
  7520. \end{center}
  7521. \fi}
  7522. {\if\edition\pythonEd
  7523. \begin{center}
  7524. \begin{minipage}{\textwidth}
  7525. \begin{lstlisting}
  7526. if x == 0:
  7527. goto block_1;
  7528. else
  7529. goto block_2;
  7530. \end{lstlisting}
  7531. \end{minipage}
  7532. \end{center}
  7533. \fi}
  7534. Next consider the case for Boolean constants. We perform a kind of
  7535. partial evaluation\index{subject}{partial evaluation} and output
  7536. either the \code{thn} or \code{els} branch depending on whether the
  7537. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7538. following program.
  7539. {\if\edition\racketEd
  7540. \begin{center}
  7541. \begin{minipage}{\textwidth}
  7542. \begin{lstlisting}
  7543. (if #t 42 777)
  7544. \end{lstlisting}
  7545. \end{minipage}
  7546. \end{center}
  7547. \fi}
  7548. {\if\edition\pythonEd
  7549. \begin{center}
  7550. \begin{minipage}{\textwidth}
  7551. \begin{lstlisting}
  7552. 42 if True else 777
  7553. \end{lstlisting}
  7554. \end{minipage}
  7555. \end{center}
  7556. \fi}
  7557. %
  7558. Again, the two branches \code{42} and \code{777} were compiled to
  7559. \code{return} statements, so \code{explicate\_pred} compiles the
  7560. constant
  7561. \racket{\code{\#t}}
  7562. \python{\code{True}}
  7563. to the code for the ``then'' branch.
  7564. \begin{center}
  7565. \begin{minipage}{\textwidth}
  7566. \begin{lstlisting}
  7567. return 42;
  7568. \end{lstlisting}
  7569. \end{minipage}
  7570. \end{center}
  7571. %
  7572. This case demonstrates that we sometimes discard the \code{thn} or
  7573. \code{els} blocks that are input to \code{explicate\_pred}.
  7574. The case for \key{if} expressions in \code{explicate\_pred} is
  7575. particularly illuminating because it deals with the challenges we
  7576. discussed above regarding nested \key{if} expressions
  7577. (Figure~\ref{fig:explicate-control-s1-38}). The
  7578. \racket{\lstinline{thn^}}\python{\code{body}} and
  7579. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  7580. \key{if} inherit their context from the current one, that is,
  7581. predicate context. So you should recursively apply
  7582. \code{explicate\_pred} to the
  7583. \racket{\lstinline{thn^}}\python{\code{body}} and
  7584. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7585. those recursive calls, pass \code{thn} and \code{els} as the extra
  7586. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7587. inside each recursive call. As discussed above, to avoid duplicating
  7588. code, we need to add them to the dictionary of basic blocks so that we
  7589. can instead refer to them by name and execute them with a \key{goto}.
  7590. {\if\edition\pythonEd
  7591. %
  7592. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7593. three parameters: 1) the statement to be compiled, 2) the code for its
  7594. continuation, and 3) the dictionary of basic blocks. The
  7595. \code{explicate\_stmt} returns a list of statements and it may add to
  7596. the dictionary of basic blocks. The cases for assignment and an
  7597. expression-statement are given in full in the skeleton code: they
  7598. simply dispatch to \code{explicate\_assign} and
  7599. \code{explicate\_effect}, respectively. The case for \code{if}
  7600. statements is not given, and is similar to the case for \code{if}
  7601. expressions.
  7602. The \code{explicate\_control} function itself is given in
  7603. Figure~\ref{fig:explicate-control-Lif}. It applies
  7604. \code{explicate\_stmt} to each statement in the program, from back to
  7605. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7606. used as the continuation parameter in the next call to
  7607. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7608. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7609. the dictionary of basic blocks, labeling it as the ``start'' block.
  7610. %
  7611. \fi}
  7612. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7613. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7614. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7615. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7616. %% results from the two recursive calls. We complete the case for
  7617. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7618. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7619. %% the result $B_5$.
  7620. %% \[
  7621. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7622. %% \quad\Rightarrow\quad
  7623. %% B_5
  7624. %% \]
  7625. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7626. %% inherit the current context, so they are in tail position. Thus, the
  7627. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7628. %% \code{explicate\_tail}.
  7629. %% %
  7630. %% We need to pass $B_0$ as the accumulator argument for both of these
  7631. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7632. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7633. %% to the control-flow graph and obtain a promised goto $G_0$.
  7634. %% %
  7635. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7636. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7637. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7638. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7639. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7640. %% \[
  7641. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7642. %% \]
  7643. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7644. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7645. %% should not be confused with the labels for the blocks that appear in
  7646. %% the generated code. We initially construct unlabeled blocks; we only
  7647. %% attach labels to blocks when we add them to the control-flow graph, as
  7648. %% we see in the next case.
  7649. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7650. %% function. The context of the \key{if} is an assignment to some
  7651. %% variable $x$ and then the control continues to some promised block
  7652. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7653. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7654. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7655. %% branches of the \key{if} inherit the current context, so they are in
  7656. %% assignment positions. Let $B_2$ be the result of applying
  7657. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7658. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7659. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7660. %% the result of applying \code{explicate\_pred} to the predicate
  7661. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7662. %% translates to the promise $B_4$.
  7663. %% \[
  7664. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7665. %% \]
  7666. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7667. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7668. \code{remove\_complex\_operands} pass and then the
  7669. \code{explicate\_control} pass on the example program. We walk through
  7670. the output program.
  7671. %
  7672. Following the order of evaluation in the output of
  7673. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7674. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7675. in the predicate of the inner \key{if}. In the output of
  7676. \code{explicate\_control}, in the
  7677. block labeled \code{start}, are two assignment statements followed by a
  7678. \code{if} statement that branches to \code{block\_8} or
  7679. \code{block\_9}. The blocks associated with those labels contain the
  7680. translations of the code
  7681. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7682. and
  7683. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7684. respectively. In particular, we start \code{block\_8} with the
  7685. comparison
  7686. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7687. and then branch to \code{block\_4} or \code{block\_5}.
  7688. Here was see that our algorithm sometimes inserts unnecessary blocks:
  7689. \code{block\_4} is just a \code{goto} to \code{block\_2}
  7690. and \code{block\_5} is just a \code{goto} to \code{block\_3}.
  7691. It would be better to skip blocks \code{block\_4} and \code{block\_5}
  7692. and go directly to \code{block\_2} and \code{block\_3},
  7693. which we investigate in Section~\ref{sec:opt-jumps}.
  7694. Getting back to the example, \code{block\_2} and \code{block\_3},
  7695. corresponds to the two branches of the outer \key{if}, i.e.,
  7696. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7697. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7698. %
  7699. The story for \code{block\_9} is similar to that of \code{block\_8}.
  7700. %
  7701. \python{The \code{block\_1} corresponds to the \code{print} statment
  7702. at the end of the program.}
  7703. \begin{figure}[tbp]
  7704. {\if\edition\racketEd
  7705. \begin{tabular}{lll}
  7706. \begin{minipage}{0.4\textwidth}
  7707. % cond_test_41.rkt
  7708. \begin{lstlisting}
  7709. (let ([x (read)])
  7710. (let ([y (read)])
  7711. (if (if (< x 1)
  7712. (eq? x 0)
  7713. (eq? x 2))
  7714. (+ y 2)
  7715. (+ y 10))))
  7716. \end{lstlisting}
  7717. \end{minipage}
  7718. &
  7719. $\Rightarrow$
  7720. &
  7721. \begin{minipage}{0.55\textwidth}
  7722. \begin{lstlisting}
  7723. start:
  7724. x = (read);
  7725. y = (read);
  7726. if (< x 1)
  7727. goto block_8;
  7728. else
  7729. goto block_9;
  7730. block_8:
  7731. if (eq? x 0)
  7732. goto block_4;
  7733. else
  7734. goto block_5;
  7735. block_9:
  7736. if (eq? x 2)
  7737. goto block_6;
  7738. else
  7739. goto block_7;
  7740. block_4:
  7741. goto block_2;
  7742. block_5:
  7743. goto block_3;
  7744. block_6:
  7745. goto block_2;
  7746. block_7:
  7747. goto block_3;
  7748. block_2:
  7749. return (+ y 2);
  7750. block_3:
  7751. return (+ y 10);
  7752. \end{lstlisting}
  7753. \end{minipage}
  7754. \end{tabular}
  7755. \fi}
  7756. {\if\edition\pythonEd
  7757. \begin{tabular}{lll}
  7758. \begin{minipage}{0.4\textwidth}
  7759. % cond_test_41.rkt
  7760. \begin{lstlisting}
  7761. x = input_int()
  7762. y = input_int()
  7763. print(y + 2 \
  7764. if (x == 0 \
  7765. if x < 1 \
  7766. else x == 2) \
  7767. else y + 10)
  7768. \end{lstlisting}
  7769. \end{minipage}
  7770. &
  7771. $\Rightarrow$
  7772. &
  7773. \begin{minipage}{0.55\textwidth}
  7774. \begin{lstlisting}
  7775. start:
  7776. x = input_int()
  7777. y = input_int()
  7778. if x < 1:
  7779. goto block_8
  7780. else:
  7781. goto block_9
  7782. block_8:
  7783. if x == 0:
  7784. goto block_4
  7785. else:
  7786. goto block_5
  7787. block_9:
  7788. if x == 2:
  7789. goto block_6
  7790. else:
  7791. goto block_7
  7792. block_4:
  7793. goto block_2
  7794. block_5:
  7795. goto block_3
  7796. block_6:
  7797. goto block_2
  7798. block_7:
  7799. goto block_3
  7800. block_2:
  7801. tmp_0 = y + 2
  7802. goto block_1
  7803. block_3:
  7804. tmp_0 = y + 10
  7805. goto block_1
  7806. block_1:
  7807. print(tmp_0)
  7808. return 0
  7809. \end{lstlisting}
  7810. \end{minipage}
  7811. \end{tabular}
  7812. \fi}
  7813. \caption{Translation from \LangIf{} to \LangCIf{}
  7814. via the \code{explicate\_control}.}
  7815. \label{fig:explicate-control-s1-38}
  7816. \end{figure}
  7817. {\if\edition\racketEd
  7818. The way in which the \code{shrink} pass transforms logical operations
  7819. such as \code{and} and \code{or} can impact the quality of code
  7820. generated by \code{explicate\_control}. For example, consider the
  7821. following program.
  7822. % cond_test_21.rkt, and_eq_input.py
  7823. \begin{lstlisting}
  7824. (if (and (eq? (read) 0) (eq? (read) 1))
  7825. 0
  7826. 42)
  7827. \end{lstlisting}
  7828. The \code{and} operation should transform into something that the
  7829. \code{explicate\_pred} function can still analyze and descend through to
  7830. reach the underlying \code{eq?} conditions. Ideally, your
  7831. \code{explicate\_control} pass should generate code similar to the
  7832. following for the above program.
  7833. \begin{center}
  7834. \begin{lstlisting}
  7835. start:
  7836. tmp1 = (read);
  7837. if (eq? tmp1 0) goto block40;
  7838. else goto block39;
  7839. block40:
  7840. tmp2 = (read);
  7841. if (eq? tmp2 1) goto block38;
  7842. else goto block39;
  7843. block38:
  7844. return 0;
  7845. block39:
  7846. return 42;
  7847. \end{lstlisting}
  7848. \end{center}
  7849. \fi}
  7850. \begin{exercise}\normalfont
  7851. \racket{
  7852. Implement the pass \code{explicate\_control} by adding the cases for
  7853. Boolean constants and \key{if} to the \code{explicate\_tail} and
  7854. \code{explicate\_assign} functions. Implement the auxiliary function
  7855. \code{explicate\_pred} for predicate contexts.}
  7856. \python{Implement \code{explicate\_control} pass with its
  7857. four auxiliary functions.}
  7858. %
  7859. Create test cases that exercise all of the new cases in the code for
  7860. this pass.
  7861. %
  7862. {\if\edition\racketEd
  7863. Add the following entry to the list of \code{passes} in
  7864. \code{run-tests.rkt} and then run this script to test your compiler.
  7865. \begin{lstlisting}
  7866. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  7867. \end{lstlisting}
  7868. \fi}
  7869. \end{exercise}
  7870. \clearpage
  7871. \section{Select Instructions}
  7872. \label{sec:select-Lif}
  7873. \index{subject}{instruction selection}
  7874. The \code{select\_instructions} pass translates \LangCIf{} to
  7875. \LangXIfVar{}.
  7876. %
  7877. \racket{Recall that we implement this pass using three auxiliary
  7878. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  7879. $\Tail$.}
  7880. %
  7881. \racket{For $\Atm$, we have new cases for the Booleans.}
  7882. %
  7883. \python{We begin with the Boolean constants.}
  7884. We take the usual approach of encoding them as integers.
  7885. \[
  7886. \TRUE{} \quad\Rightarrow\quad \key{1}
  7887. \qquad\qquad
  7888. \FALSE{} \quad\Rightarrow\quad \key{0}
  7889. \]
  7890. For translating statements, we discuss a selection of cases. The \code{not}
  7891. operation can be implemented in terms of \code{xorq} as we discussed
  7892. at the beginning of this section. Given an assignment, if the
  7893. left-hand side variable is the same as the argument of \code{not},
  7894. then just the \code{xorq} instruction suffices.
  7895. \[
  7896. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  7897. \quad\Rightarrow\quad
  7898. \key{xorq}~\key{\$}1\key{,}~\Var
  7899. \]
  7900. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  7901. semantics of x86. In the following translation, let $\Arg$ be the
  7902. result of translating $\Atm$ to x86.
  7903. \[
  7904. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  7905. \quad\Rightarrow\quad
  7906. \begin{array}{l}
  7907. \key{movq}~\Arg\key{,}~\Var\\
  7908. \key{xorq}~\key{\$}1\key{,}~\Var
  7909. \end{array}
  7910. \]
  7911. Next consider the cases for equality. Translating this operation to
  7912. x86 is slightly involved due to the unusual nature of the \key{cmpq}
  7913. instruction discussed above. We recommend translating an assignment
  7914. with an equality on the right-hand side into a sequence of three
  7915. instructions. \\
  7916. \begin{tabular}{lll}
  7917. \begin{minipage}{0.4\textwidth}
  7918. \begin{lstlisting}
  7919. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  7920. \end{lstlisting}
  7921. \end{minipage}
  7922. &
  7923. $\Rightarrow$
  7924. &
  7925. \begin{minipage}{0.4\textwidth}
  7926. \begin{lstlisting}
  7927. cmpq |$\Arg_2$|, |$\Arg_1$|
  7928. sete %al
  7929. movzbq %al, |$\Var$|
  7930. \end{lstlisting}
  7931. \end{minipage}
  7932. \end{tabular} \\
  7933. The translations for the other comparison operators are similar to the
  7934. above but use different suffixes for the \code{set} instruction.
  7935. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  7936. \key{goto} and \key{if} statements. Both are straightforward to
  7937. translate to x86.}
  7938. %
  7939. A \key{goto} statement becomes a jump instruction.
  7940. \[
  7941. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  7942. \]
  7943. %
  7944. An \key{if} statement becomes a compare instruction followed by a
  7945. conditional jump (for the ``then'' branch) and the fall-through is to
  7946. a regular jump (for the ``else'' branch).\\
  7947. \begin{tabular}{lll}
  7948. \begin{minipage}{0.4\textwidth}
  7949. \begin{lstlisting}
  7950. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  7951. goto |$\ell_1$||$\racket{\key{;}}$|
  7952. else|$\python{\key{:}}$|
  7953. goto |$\ell_2$||$\racket{\key{;}}$|
  7954. \end{lstlisting}
  7955. \end{minipage}
  7956. &
  7957. $\Rightarrow$
  7958. &
  7959. \begin{minipage}{0.4\textwidth}
  7960. \begin{lstlisting}
  7961. cmpq |$\Arg_2$|, |$\Arg_1$|
  7962. je |$\ell_1$|
  7963. jmp |$\ell_2$|
  7964. \end{lstlisting}
  7965. \end{minipage}
  7966. \end{tabular} \\
  7967. Again, the translations for the other comparison operators are similar to the
  7968. above but use different suffixes for the conditional jump instruction.
  7969. \python{Regarding the \key{return} statement, we recommend treating it
  7970. as an assignment to the \key{rax} register followed by a jump to the
  7971. conclusion of the \code{main} function.}
  7972. \begin{exercise}\normalfont
  7973. Expand your \code{select\_instructions} pass to handle the new
  7974. features of the \LangIf{} language.
  7975. %
  7976. {\if\edition\racketEd
  7977. Add the following entry to the list of \code{passes} in
  7978. \code{run-tests.rkt}
  7979. \begin{lstlisting}
  7980. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  7981. \end{lstlisting}
  7982. \fi}
  7983. %
  7984. Run the script to test your compiler on all the test programs.
  7985. \end{exercise}
  7986. \section{Register Allocation}
  7987. \label{sec:register-allocation-Lif}
  7988. \index{subject}{register allocation}
  7989. The changes required for \LangIf{} affect liveness analysis, building the
  7990. interference graph, and assigning homes, but the graph coloring
  7991. algorithm itself does not change.
  7992. \subsection{Liveness Analysis}
  7993. \label{sec:liveness-analysis-Lif}
  7994. \index{subject}{liveness analysis}
  7995. Recall that for \LangVar{} we implemented liveness analysis for a
  7996. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  7997. the addition of \key{if} expressions to \LangIf{},
  7998. \code{explicate\_control} produces many basic blocks.
  7999. %% We recommend that you create a new auxiliary function named
  8000. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8001. %% control-flow graph.
  8002. The first question is: in what order should we process the basic blocks?
  8003. Recall that to perform liveness analysis on a basic block we need to
  8004. know the live-after set for the last instruction in the block. If a
  8005. basic block has no successors (i.e. contains no jumps to other
  8006. blocks), then it has an empty live-after set and we can immediately
  8007. apply liveness analysis to it. If a basic block has some successors,
  8008. then we need to complete liveness analysis on those blocks
  8009. first. These ordering contraints are the reverse of a
  8010. \emph{topological order}\index{subject}{topological order} on a graph
  8011. representation of the program. In particular, the \emph{control flow
  8012. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  8013. of a program has a node for each basic block and an edge for each jump
  8014. from one block to another. It is straightforward to generate a CFG
  8015. from the dictionary of basic blocks. One then transposes the CFG and
  8016. applies the topological sort algorithm.
  8017. %
  8018. %
  8019. \racket{We recommend using the \code{tsort} and \code{transpose}
  8020. functions of the Racket \code{graph} package to accomplish this.}
  8021. %
  8022. \python{We provide implementations of \code{topological\_sort} and
  8023. \code{transpose} in the file \code{graph.py} of the support code.}
  8024. %
  8025. As an aside, a topological ordering is only guaranteed to exist if the
  8026. graph does not contain any cycles. This is the case for the
  8027. control-flow graphs that we generate from \LangIf{} programs.
  8028. However, in Chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  8029. and learn how to handle cycles in the control-flow graph.
  8030. \racket{You'll need to construct a directed graph to represent the
  8031. control-flow graph. Do not use the \code{directed-graph} of the
  8032. \code{graph} package because that only allows at most one edge
  8033. between each pair of vertices, but a control-flow graph may have
  8034. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  8035. file in the support code implements a graph representation that
  8036. allows multiple edges between a pair of vertices.}
  8037. {\if\edition\racketEd
  8038. The next question is how to analyze jump instructions. Recall that in
  8039. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  8040. \code{label->live} that maps each label to the set of live locations
  8041. at the beginning of its block. We use \code{label->live} to determine
  8042. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  8043. that we have many basic blocks, \code{label->live} needs to be updated
  8044. as we process the blocks. In particular, after performing liveness
  8045. analysis on a block, we take the live-before set of its first
  8046. instruction and associate that with the block's label in the
  8047. \code{label->live}.
  8048. \fi}
  8049. %
  8050. {\if\edition\pythonEd
  8051. %
  8052. The next question is how to analyze jump instructions. The locations
  8053. that are live before a \code{jmp} should be the locations in
  8054. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  8055. maintaining a dictionary named \code{live\_before\_block} that maps each
  8056. label to the $L_{\mathtt{before}}$ for the first instruction in its
  8057. block. After performing liveness analysis on each block, we take the
  8058. live-before set of its first instruction and associate that with the
  8059. block's label in the \code{live\_before\_block} dictionary.
  8060. %
  8061. \fi}
  8062. In \LangXIfVar{} we also have the conditional jump
  8063. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8064. this instruction is particularly interesting because, during
  8065. compilation, we do not know which way a conditional jump will go. So
  8066. we do not know whether to use the live-before set for the following
  8067. instruction or the live-before set for the block associated with the
  8068. $\itm{label}$. However, there is no harm to the correctness of the
  8069. generated code if we classify more locations as live than the ones
  8070. that are truly live during one particular execution of the
  8071. instruction. Thus, we can take the union of the live-before sets from
  8072. the following instruction and from the mapping for $\itm{label}$ in
  8073. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8074. The auxiliary functions for computing the variables in an
  8075. instruction's argument and for computing the variables read-from ($R$)
  8076. or written-to ($W$) by an instruction need to be updated to handle the
  8077. new kinds of arguments and instructions in \LangXIfVar{}.
  8078. \begin{exercise}\normalfont
  8079. {\if\edition\racketEd
  8080. %
  8081. Update the \code{uncover\_live} pass to apply liveness analysis to
  8082. every basic block in the program.
  8083. %
  8084. Add the following entry to the list of \code{passes} in the
  8085. \code{run-tests.rkt} script.
  8086. \begin{lstlisting}
  8087. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8088. \end{lstlisting}
  8089. \fi}
  8090. {\if\edition\pythonEd
  8091. %
  8092. Update the \code{uncover\_live} function to perform liveness analysis,
  8093. in reverse topological order, on all of the basic blocks in the
  8094. program.
  8095. %
  8096. \fi}
  8097. % Check that the live-after sets that you generate for
  8098. % example X matches the following... -Jeremy
  8099. \end{exercise}
  8100. \subsection{Build the Interference Graph}
  8101. \label{sec:build-interference-Lif}
  8102. Many of the new instructions in \LangXIfVar{} can be handled in the
  8103. same way as the instructions in \LangXVar{}.
  8104. % Thus, if your code was
  8105. % already quite general, it will not need to be changed to handle the
  8106. % new instructions. If your code is not general enough, we recommend that
  8107. % you change your code to be more general. For example, you can factor
  8108. % out the computing of the the read and write sets for each kind of
  8109. % instruction into auxiliary functions.
  8110. %
  8111. Some instructions, e.g., the \key{movzbq} instruction, require special care,
  8112. similar to the \key{movq} instruction. See rule number 1 in
  8113. Section~\ref{sec:build-interference}.
  8114. \begin{exercise}\normalfont
  8115. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8116. {\if\edition\racketEd
  8117. Add the following entries to the list of \code{passes} in the
  8118. \code{run-tests.rkt} script.
  8119. \begin{lstlisting}
  8120. (list "build_interference" build_interference interp-pseudo-x86-1)
  8121. (list "allocate_registers" allocate_registers interp-x86-1)
  8122. \end{lstlisting}
  8123. \fi}
  8124. % Check that the interference graph that you generate for
  8125. % example X matches the following graph G... -Jeremy
  8126. \end{exercise}
  8127. \section{Patch Instructions}
  8128. The new instructions \key{cmpq} and \key{movzbq} have some special
  8129. restrictions that need to be handled in the \code{patch\_instructions}
  8130. pass.
  8131. %
  8132. The second argument of the \key{cmpq} instruction must not be an
  8133. immediate value (such as an integer). So if you are comparing two
  8134. immediates, we recommend inserting a \key{movq} instruction to put the
  8135. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8136. one memory reference.
  8137. %
  8138. The second argument of the \key{movzbq} must be a register.
  8139. \begin{exercise}\normalfont
  8140. %
  8141. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8142. %
  8143. {\if\edition\racketEd
  8144. Add the following entry to the list of \code{passes} in
  8145. \code{run-tests.rkt} and then run this script to test your compiler.
  8146. \begin{lstlisting}
  8147. (list "patch_instructions" patch_instructions interp-x86-1)
  8148. \end{lstlisting}
  8149. \fi}
  8150. \end{exercise}
  8151. {\if\edition\pythonEd
  8152. \section{Prelude and Conclusion}
  8153. \label{sec:prelude-conclusion-cond}
  8154. The generation of the \code{main} function with its prelude and
  8155. conclusion must change to accomodate how the program now consists of
  8156. one or more basic blocks. After the prelude in \code{main}, jump to
  8157. the \code{start} block. Place the conclusion in a basic block labelled
  8158. with \code{conclusion}.
  8159. \fi}
  8160. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8161. \LangIf{} translated to x86, showing the results of
  8162. \code{explicate\_control}, \code{select\_instructions}, and the final
  8163. x86 assembly.
  8164. \begin{figure}[tbp]
  8165. {\if\edition\racketEd
  8166. \begin{tabular}{lll}
  8167. \begin{minipage}{0.4\textwidth}
  8168. % cond_test_20.rkt, eq_input.py
  8169. \begin{lstlisting}
  8170. (if (eq? (read) 1) 42 0)
  8171. \end{lstlisting}
  8172. $\Downarrow$
  8173. \begin{lstlisting}
  8174. start:
  8175. tmp7951 = (read);
  8176. if (eq? tmp7951 1)
  8177. goto block7952;
  8178. else
  8179. goto block7953;
  8180. block7952:
  8181. return 42;
  8182. block7953:
  8183. return 0;
  8184. \end{lstlisting}
  8185. $\Downarrow$
  8186. \begin{lstlisting}
  8187. start:
  8188. callq read_int
  8189. movq %rax, tmp7951
  8190. cmpq $1, tmp7951
  8191. je block7952
  8192. jmp block7953
  8193. block7953:
  8194. movq $0, %rax
  8195. jmp conclusion
  8196. block7952:
  8197. movq $42, %rax
  8198. jmp conclusion
  8199. \end{lstlisting}
  8200. \end{minipage}
  8201. &
  8202. $\Rightarrow\qquad$
  8203. \begin{minipage}{0.4\textwidth}
  8204. \begin{lstlisting}
  8205. start:
  8206. callq read_int
  8207. movq %rax, %rcx
  8208. cmpq $1, %rcx
  8209. je block7952
  8210. jmp block7953
  8211. block7953:
  8212. movq $0, %rax
  8213. jmp conclusion
  8214. block7952:
  8215. movq $42, %rax
  8216. jmp conclusion
  8217. .globl main
  8218. main:
  8219. pushq %rbp
  8220. movq %rsp, %rbp
  8221. pushq %r13
  8222. pushq %r12
  8223. pushq %rbx
  8224. pushq %r14
  8225. subq $0, %rsp
  8226. jmp start
  8227. conclusion:
  8228. addq $0, %rsp
  8229. popq %r14
  8230. popq %rbx
  8231. popq %r12
  8232. popq %r13
  8233. popq %rbp
  8234. retq
  8235. \end{lstlisting}
  8236. \end{minipage}
  8237. \end{tabular}
  8238. \fi}
  8239. {\if\edition\pythonEd
  8240. \begin{tabular}{lll}
  8241. \begin{minipage}{0.4\textwidth}
  8242. % cond_test_20.rkt, eq_input.py
  8243. \begin{lstlisting}
  8244. print(42 if input_int() == 1 else 0)
  8245. \end{lstlisting}
  8246. $\Downarrow$
  8247. \begin{lstlisting}
  8248. start:
  8249. tmp_0 = input_int()
  8250. if tmp_0 == 1:
  8251. goto block_3
  8252. else:
  8253. goto block_4
  8254. block_3:
  8255. tmp_1 = 42
  8256. goto block_2
  8257. block_4:
  8258. tmp_1 = 0
  8259. goto block_2
  8260. block_2:
  8261. print(tmp_1)
  8262. return 0
  8263. \end{lstlisting}
  8264. $\Downarrow$
  8265. \begin{lstlisting}
  8266. start:
  8267. callq read_int
  8268. movq %rax, tmp_0
  8269. cmpq 1, tmp_0
  8270. je block_3
  8271. jmp block_4
  8272. block_3:
  8273. movq 42, tmp_1
  8274. jmp block_2
  8275. block_4:
  8276. movq 0, tmp_1
  8277. jmp block_2
  8278. block_2:
  8279. movq tmp_1, %rdi
  8280. callq print_int
  8281. movq 0, %rax
  8282. jmp conclusion
  8283. \end{lstlisting}
  8284. \end{minipage}
  8285. &
  8286. $\Rightarrow\qquad$
  8287. \begin{minipage}{0.4\textwidth}
  8288. \begin{lstlisting}
  8289. .globl main
  8290. main:
  8291. pushq %rbp
  8292. movq %rsp, %rbp
  8293. subq $0, %rsp
  8294. jmp start
  8295. start:
  8296. callq read_int
  8297. movq %rax, %rcx
  8298. cmpq $1, %rcx
  8299. je block_3
  8300. jmp block_4
  8301. block_3:
  8302. movq $42, %rcx
  8303. jmp block_2
  8304. block_4:
  8305. movq $0, %rcx
  8306. jmp block_2
  8307. block_2:
  8308. movq %rcx, %rdi
  8309. callq print_int
  8310. movq $0, %rax
  8311. jmp conclusion
  8312. conclusion:
  8313. addq $0, %rsp
  8314. popq %rbp
  8315. retq
  8316. \end{lstlisting}
  8317. \end{minipage}
  8318. \end{tabular}
  8319. \fi}
  8320. \caption{Example compilation of an \key{if} expression to x86, showing
  8321. the results of \code{explicate\_control},
  8322. \code{select\_instructions}, and the final x86 assembly code. }
  8323. \label{fig:if-example-x86}
  8324. \end{figure}
  8325. \begin{figure}[tbp]
  8326. {\if\edition\racketEd
  8327. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8328. \node (Lif) at (0,2) {\large \LangIf{}};
  8329. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8330. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8331. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8332. \node (Lif-5) at (12,2) {\large \LangIfANF{}};
  8333. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8334. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8335. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8336. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8337. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8338. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8339. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8340. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8341. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8342. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8343. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8344. \path[->,bend left=15] (Lif-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8345. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  8346. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8347. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8348. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8349. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8350. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8351. \end{tikzpicture}
  8352. \fi}
  8353. {\if\edition\pythonEd
  8354. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8355. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8356. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8357. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8358. \node (C-1) at (3,0) {\large \LangCIf{}};
  8359. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8360. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8361. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8362. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8363. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8364. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8365. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8366. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8367. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8368. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8369. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8370. \end{tikzpicture}
  8371. \fi}
  8372. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8373. \label{fig:Lif-passes}
  8374. \end{figure}
  8375. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8376. compilation of \LangIf{}.
  8377. \section{Challenge: Optimize Blocks and Remove Jumps}
  8378. \label{sec:opt-jumps}
  8379. We discuss two optional challenges that involve optimizing the
  8380. control-flow of the program.
  8381. \subsection{Optimize Blocks}
  8382. The algorithm for \code{explicate\_control} that we discussed in
  8383. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8384. blocks. It does so in two different ways.
  8385. %
  8386. First, recall how in Figure~\ref{fig:explicate-control-s1-38},
  8387. \code{block\_4} consists of just a jump to \code{block\_2}. We created
  8388. a new basic block from a single \code{goto} statement, whereas we
  8389. could have simply returned the \code{goto} statement. We can solve
  8390. this problem by modifying the \code{create\_block} function to
  8391. recognize this situation.
  8392. Second, \code{explicate\_control} creates a basic block whenever a
  8393. continuation \emph{might} get used more than once (whenever a
  8394. continuation is passed into two or more recursive calls). However,
  8395. some continuation parameters may not be used at all. For example, consider the
  8396. case for the constant \TRUE{} in \code{explicate\_pred}, where we
  8397. discard the \code{els} branch. So the question is how can we decide
  8398. whether to create a basic block?
  8399. The solution to this conundrum is to use \emph{lazy
  8400. evaluation}\index{subject}{lazy evaluation}~\citep{Friedman:1976aa}
  8401. to delay creating a basic block until the point in time where we know
  8402. it will be used.
  8403. %
  8404. {\if\edition\racketEd
  8405. %
  8406. Racket provides support for
  8407. lazy evaluation with the
  8408. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8409. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8410. \index{subject}{delay} creates a
  8411. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8412. expressions is postponed. When \key{(force}
  8413. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8414. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8415. result of $e_n$ is cached in the promise and returned. If \code{force}
  8416. is applied again to the same promise, then the cached result is
  8417. returned. If \code{force} is applied to an argument that is not a
  8418. promise, \code{force} simply returns the argument.
  8419. %
  8420. \fi}
  8421. %
  8422. {\if\edition\pythonEd
  8423. %
  8424. While Python does not provide direct support for lazy evaluation, it
  8425. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8426. by wrapping it inside a function with no parameters. We can
  8427. \emph{force} its evaluation by calling the function. However, in some
  8428. cases of \code{explicate\_pred}, etc., we will return a list of
  8429. statements and in other cases we will return a function that computes
  8430. a list of statements. We use the term \emph{promise} to refer to a
  8431. value that may be delayed. To uniformly deal with
  8432. promises, we define the following \code{force} function that checks
  8433. whether its input is delayed (i.e., whether it is a function) and then
  8434. either 1) calls the function, or 2) returns the input.
  8435. \begin{lstlisting}
  8436. def force(promise):
  8437. if isinstance(promise, types.FunctionType):
  8438. return promise()
  8439. else:
  8440. return promise
  8441. \end{lstlisting}
  8442. %
  8443. \fi}
  8444. We use promises for the input and output of the functions
  8445. \code{explicate\_pred}, \code{explicate\_assign},
  8446. %
  8447. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8448. %
  8449. So instead of taking and returning lists of statments, they take and
  8450. return promises. Furthermore, when we come to a situation in which a
  8451. continuation might be used more than once, as in the case for
  8452. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8453. that creates a basic block for each continuation (if there is not
  8454. already one) and then returns a \code{goto} statement to that basic
  8455. block.
  8456. %
  8457. {\if\edition\racketEd
  8458. %
  8459. The following auxiliary function named \code{create\_block} accomplishes
  8460. this task. It begins with \code{delay} to create a promise. When
  8461. forced, this promise will force the original promise. If that returns
  8462. a \code{goto} (because the block was already added to the control-flow
  8463. graph), then we return the \code{goto}. Otherwise we add the block to
  8464. the control-flow graph with another auxiliary function named
  8465. \code{add-node}. That function returns the label for the new block,
  8466. which we use to create a \code{goto}.
  8467. \begin{lstlisting}
  8468. (define (create_block tail)
  8469. (delay
  8470. (define t (force tail))
  8471. (match t
  8472. [(Goto label) (Goto label)]
  8473. [else (Goto (add-node t))])))
  8474. \end{lstlisting}
  8475. \fi}
  8476. {\if\edition\pythonEd
  8477. %
  8478. Here is the new version of the \code{create\_block} auxiliary function
  8479. that works on promises and that checks whether the block consists of a
  8480. solitary \code{goto} statement.\\
  8481. \begin{minipage}{\textwidth}
  8482. \begin{lstlisting}
  8483. def create_block(promise, basic_blocks):
  8484. stmts = force(promise)
  8485. match stmts:
  8486. case [Goto(l)]:
  8487. return Goto(l)
  8488. case _:
  8489. label = label_name(generate_name('block'))
  8490. basic_blocks[label] = stmts
  8491. return Goto(label)
  8492. \end{lstlisting}
  8493. \end{minipage}
  8494. \fi}
  8495. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8496. \code{explicate\_control} on the example of the nested \code{if}
  8497. expressions with the two improvements discussed above. As you can
  8498. see, the number of basic blocks has been reduced from 10 blocks (see
  8499. Figure~\ref{fig:explicate-control-s1-38}) down to 6 blocks.
  8500. \begin{figure}[tbp]
  8501. {\if\edition\racketEd
  8502. \begin{tabular}{lll}
  8503. \begin{minipage}{0.4\textwidth}
  8504. % cond_test_41.rkt
  8505. \begin{lstlisting}
  8506. (let ([x (read)])
  8507. (let ([y (read)])
  8508. (if (if (< x 1)
  8509. (eq? x 0)
  8510. (eq? x 2))
  8511. (+ y 2)
  8512. (+ y 10))))
  8513. \end{lstlisting}
  8514. \end{minipage}
  8515. &
  8516. $\Rightarrow$
  8517. &
  8518. \begin{minipage}{0.55\textwidth}
  8519. \begin{lstlisting}
  8520. start:
  8521. x = (read);
  8522. y = (read);
  8523. if (< x 1) goto block40;
  8524. else goto block41;
  8525. block40:
  8526. if (eq? x 0) goto block38;
  8527. else goto block39;
  8528. block41:
  8529. if (eq? x 2) goto block38;
  8530. else goto block39;
  8531. block38:
  8532. return (+ y 2);
  8533. block39:
  8534. return (+ y 10);
  8535. \end{lstlisting}
  8536. \end{minipage}
  8537. \end{tabular}
  8538. \fi}
  8539. {\if\edition\pythonEd
  8540. \begin{tabular}{lll}
  8541. \begin{minipage}{0.4\textwidth}
  8542. % cond_test_41.rkt
  8543. \begin{lstlisting}
  8544. x = input_int()
  8545. y = input_int()
  8546. print(y + 2 \
  8547. if (x == 0 \
  8548. if x < 1 \
  8549. else x == 2) \
  8550. else y + 10)
  8551. \end{lstlisting}
  8552. \end{minipage}
  8553. &
  8554. $\Rightarrow$
  8555. &
  8556. \begin{minipage}{0.55\textwidth}
  8557. \begin{lstlisting}
  8558. start:
  8559. x = input_int()
  8560. y = input_int()
  8561. if x < 1:
  8562. goto block_4
  8563. else:
  8564. goto block_5
  8565. block_4:
  8566. if x == 0:
  8567. goto block_2
  8568. else:
  8569. goto block_3
  8570. block_5:
  8571. if x == 2:
  8572. goto block_2
  8573. else:
  8574. goto block_3
  8575. block_2:
  8576. tmp_0 = y + 2
  8577. goto block_1
  8578. block_3:
  8579. tmp_0 = y + 10
  8580. goto block_1
  8581. block_1:
  8582. print(tmp_0)
  8583. return 0
  8584. \end{lstlisting}
  8585. \end{minipage}
  8586. \end{tabular}
  8587. \fi}
  8588. \caption{Translation from \LangIf{} to \LangCIf{}
  8589. via the improved \code{explicate\_control}.}
  8590. \label{fig:explicate-control-challenge}
  8591. \end{figure}
  8592. %% Recall that in the example output of \code{explicate\_control} in
  8593. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8594. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8595. %% block. The first goal of this challenge assignment is to remove those
  8596. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8597. %% \code{explicate\_control} on the left and shows the result of bypassing
  8598. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8599. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8600. %% \code{block55}. The optimized code on the right of
  8601. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8602. %% \code{then} branch jumping directly to \code{block55}. The story is
  8603. %% similar for the \code{else} branch, as well as for the two branches in
  8604. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8605. %% have been optimized in this way, there are no longer any jumps to
  8606. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8607. %% \begin{figure}[tbp]
  8608. %% \begin{tabular}{lll}
  8609. %% \begin{minipage}{0.4\textwidth}
  8610. %% \begin{lstlisting}
  8611. %% block62:
  8612. %% tmp54 = (read);
  8613. %% if (eq? tmp54 2) then
  8614. %% goto block59;
  8615. %% else
  8616. %% goto block60;
  8617. %% block61:
  8618. %% tmp53 = (read);
  8619. %% if (eq? tmp53 0) then
  8620. %% goto block57;
  8621. %% else
  8622. %% goto block58;
  8623. %% block60:
  8624. %% goto block56;
  8625. %% block59:
  8626. %% goto block55;
  8627. %% block58:
  8628. %% goto block56;
  8629. %% block57:
  8630. %% goto block55;
  8631. %% block56:
  8632. %% return (+ 700 77);
  8633. %% block55:
  8634. %% return (+ 10 32);
  8635. %% start:
  8636. %% tmp52 = (read);
  8637. %% if (eq? tmp52 1) then
  8638. %% goto block61;
  8639. %% else
  8640. %% goto block62;
  8641. %% \end{lstlisting}
  8642. %% \end{minipage}
  8643. %% &
  8644. %% $\Rightarrow$
  8645. %% &
  8646. %% \begin{minipage}{0.55\textwidth}
  8647. %% \begin{lstlisting}
  8648. %% block62:
  8649. %% tmp54 = (read);
  8650. %% if (eq? tmp54 2) then
  8651. %% goto block55;
  8652. %% else
  8653. %% goto block56;
  8654. %% block61:
  8655. %% tmp53 = (read);
  8656. %% if (eq? tmp53 0) then
  8657. %% goto block55;
  8658. %% else
  8659. %% goto block56;
  8660. %% block56:
  8661. %% return (+ 700 77);
  8662. %% block55:
  8663. %% return (+ 10 32);
  8664. %% start:
  8665. %% tmp52 = (read);
  8666. %% if (eq? tmp52 1) then
  8667. %% goto block61;
  8668. %% else
  8669. %% goto block62;
  8670. %% \end{lstlisting}
  8671. %% \end{minipage}
  8672. %% \end{tabular}
  8673. %% \caption{Optimize jumps by removing trivial blocks.}
  8674. %% \label{fig:optimize-jumps}
  8675. %% \end{figure}
  8676. %% The name of this pass is \code{optimize-jumps}. We recommend
  8677. %% implementing this pass in two phases. The first phrase builds a hash
  8678. %% table that maps labels to possibly improved labels. The second phase
  8679. %% changes the target of each \code{goto} to use the improved label. If
  8680. %% the label is for a trivial block, then the hash table should map the
  8681. %% label to the first non-trivial block that can be reached from this
  8682. %% label by jumping through trivial blocks. If the label is for a
  8683. %% non-trivial block, then the hash table should map the label to itself;
  8684. %% we do not want to change jumps to non-trivial blocks.
  8685. %% The first phase can be accomplished by constructing an empty hash
  8686. %% table, call it \code{short-cut}, and then iterating over the control
  8687. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8688. %% then update the hash table, mapping the block's source to the target
  8689. %% of the \code{goto}. Also, the hash table may already have mapped some
  8690. %% labels to the block's source, to you must iterate through the hash
  8691. %% table and update all of those so that they instead map to the target
  8692. %% of the \code{goto}.
  8693. %% For the second phase, we recommend iterating through the $\Tail$ of
  8694. %% each block in the program, updating the target of every \code{goto}
  8695. %% according to the mapping in \code{short-cut}.
  8696. \begin{exercise}\normalfont
  8697. Implement the improvements to the \code{explicate\_control} pass.
  8698. Check that it removes trivial blocks in a few example programs. Then
  8699. check that your compiler still passes all of your tests.
  8700. \end{exercise}
  8701. \subsection{Remove Jumps}
  8702. There is an opportunity for removing jumps that is apparent in the
  8703. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8704. ends with a jump to \code{block\_4} and there are no other jumps to
  8705. \code{block\_4} in the rest of the program. In this situation we can
  8706. avoid the runtime overhead of this jump by merging \code{block\_4}
  8707. into the preceding block, in this case the \code{start} block.
  8708. Figure~\ref{fig:remove-jumps} shows the output of
  8709. \code{select\_instructions} on the left and the result of this
  8710. optimization on the right.
  8711. \begin{figure}[tbp]
  8712. {\if\edition\racketEd
  8713. \begin{tabular}{lll}
  8714. \begin{minipage}{0.5\textwidth}
  8715. % cond_test_20.rkt
  8716. \begin{lstlisting}
  8717. start:
  8718. callq read_int
  8719. movq %rax, tmp7951
  8720. cmpq $1, tmp7951
  8721. je block7952
  8722. jmp block7953
  8723. block7953:
  8724. movq $0, %rax
  8725. jmp conclusion
  8726. block7952:
  8727. movq $42, %rax
  8728. jmp conclusion
  8729. \end{lstlisting}
  8730. \end{minipage}
  8731. &
  8732. $\Rightarrow\qquad$
  8733. \begin{minipage}{0.4\textwidth}
  8734. \begin{lstlisting}
  8735. start:
  8736. callq read_int
  8737. movq %rax, tmp7951
  8738. cmpq $1, tmp7951
  8739. je block7952
  8740. movq $0, %rax
  8741. jmp conclusion
  8742. block7952:
  8743. movq $42, %rax
  8744. jmp conclusion
  8745. \end{lstlisting}
  8746. \end{minipage}
  8747. \end{tabular}
  8748. \fi}
  8749. {\if\edition\pythonEd
  8750. \begin{tabular}{lll}
  8751. \begin{minipage}{0.5\textwidth}
  8752. % cond_test_20.rkt
  8753. \begin{lstlisting}
  8754. start:
  8755. callq read_int
  8756. movq %rax, tmp_0
  8757. cmpq 1, tmp_0
  8758. je block_3
  8759. jmp block_4
  8760. block_3:
  8761. movq 42, tmp_1
  8762. jmp block_2
  8763. block_4:
  8764. movq 0, tmp_1
  8765. jmp block_2
  8766. block_2:
  8767. movq tmp_1, %rdi
  8768. callq print_int
  8769. movq 0, %rax
  8770. jmp conclusion
  8771. \end{lstlisting}
  8772. \end{minipage}
  8773. &
  8774. $\Rightarrow\qquad$
  8775. \begin{minipage}{0.4\textwidth}
  8776. \begin{lstlisting}
  8777. start:
  8778. callq read_int
  8779. movq %rax, tmp_0
  8780. cmpq 1, tmp_0
  8781. je block_3
  8782. movq 0, tmp_1
  8783. jmp block_2
  8784. block_3:
  8785. movq 42, tmp_1
  8786. jmp block_2
  8787. block_2:
  8788. movq tmp_1, %rdi
  8789. callq print_int
  8790. movq 0, %rax
  8791. jmp conclusion
  8792. \end{lstlisting}
  8793. \end{minipage}
  8794. \end{tabular}
  8795. \fi}
  8796. \caption{Merging basic blocks by removing unnecessary jumps.}
  8797. \label{fig:remove-jumps}
  8798. \end{figure}
  8799. \begin{exercise}\normalfont
  8800. %
  8801. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8802. into their preceding basic block, when there is only one preceding
  8803. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8804. %
  8805. {\if\edition\racketEd
  8806. In the \code{run-tests.rkt} script, add the following entry to the
  8807. list of \code{passes} between \code{allocate\_registers}
  8808. and \code{patch\_instructions}.
  8809. \begin{lstlisting}
  8810. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8811. \end{lstlisting}
  8812. \fi}
  8813. %
  8814. Run the script to test your compiler.
  8815. %
  8816. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8817. blocks on several test programs.
  8818. \end{exercise}
  8819. \section{Further Reading}
  8820. \label{sec:cond-further-reading}
  8821. The algorithm for the \code{explicate\_control} pass is based on the
  8822. \code{explose-basic-blocks} pass in the course notes of
  8823. \citet{Dybvig:2010aa}.
  8824. %
  8825. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  8826. \citet{Appel:2003fk}, and is related to translations into continuation
  8827. passing
  8828. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  8829. %
  8830. The treatment of conditionals in the \code{explicate\_control} pass is
  8831. similar to short-cut boolean
  8832. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  8833. and the case-of-case transformation of \citet{PeytonJones:1998}.
  8834. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8835. \chapter{Loops and Dataflow Analysis}
  8836. \label{ch:Lwhile}
  8837. % TODO: define R'_8
  8838. % TODO: multi-graph
  8839. {\if\edition\racketEd
  8840. %
  8841. In this chapter we study two features that are the hallmarks of
  8842. imperative programming languages: loops and assignments to local
  8843. variables. The following example demonstrates these new features by
  8844. computing the sum of the first five positive integers.
  8845. % similar to loop_test_1.rkt
  8846. \begin{lstlisting}
  8847. (let ([sum 0])
  8848. (let ([i 5])
  8849. (begin
  8850. (while (> i 0)
  8851. (begin
  8852. (set! sum (+ sum i))
  8853. (set! i (- i 1))))
  8854. sum)))
  8855. \end{lstlisting}
  8856. The \code{while} loop consists of a condition and a
  8857. body\footnote{The \code{while} loop in particular is not a built-in
  8858. feature of the Racket language, but Racket includes many looping
  8859. constructs and it is straightforward to define \code{while} as a
  8860. macro.}. The body is evaluated repeatedly so long as the condition
  8861. remains true.
  8862. %
  8863. The \code{set!} consists of a variable and a right-hand-side
  8864. expression. The \code{set!} updates value of the variable to the
  8865. value of the right-hand-side.
  8866. %
  8867. The primary purpose of both the \code{while} loop and \code{set!} is
  8868. to cause side effects, so they do not have a meaningful result
  8869. value. Instead their result is the \code{\#<void>} value. The
  8870. expression \code{(void)} is an explicit way to create the
  8871. \code{\#<void>} value and it has type \code{Void}. The
  8872. \code{\#<void>} value can be passed around just like other values
  8873. inside an \LangLoop{} program and a \code{\#<void>} value can be
  8874. compared for equality with another \code{\#<void>} value. However,
  8875. there are no other operations specific to the the \code{\#<void>}
  8876. value in \LangLoop{}. In contrast, Racket defines the \code{void?}
  8877. predicate that returns \code{\#t} when applied to \code{\#<void>} and
  8878. \code{\#f} otherwise.
  8879. %
  8880. \footnote{Racket's \code{Void} type corresponds to what is called the
  8881. \code{Unit} type in the programming languages literature. Racket's
  8882. \code{Void} type is inhabited by a single value \code{\#<void>}
  8883. which corresponds to \code{unit} or \code{()} in the
  8884. literature~\citep{Pierce:2002hj}.}.
  8885. %
  8886. With the addition of side-effecting features such as \code{while} loop
  8887. and \code{set!}, it is helpful to also include in a language feature
  8888. for sequencing side effects: the \code{begin} expression. It consists
  8889. of one or more subexpressions that are evaluated left-to-right.
  8890. %
  8891. \fi}
  8892. {\if\edition\pythonEd
  8893. %
  8894. In this chapter we study loops, one of the hallmarks of imperative
  8895. programming languages. The following example demonstrates the
  8896. \code{while} loop by computing the sum of the first five positive
  8897. integers.
  8898. \begin{lstlisting}
  8899. sum = 0
  8900. i = 5
  8901. while i > 0:
  8902. sum = sum + i
  8903. i = i - 1
  8904. print(sum)
  8905. \end{lstlisting}
  8906. The \code{while} loop consists of a condition expression and a body (a
  8907. sequence of statements). The body is evaluated repeatedly so long as
  8908. the condition remains true.
  8909. %
  8910. \fi}
  8911. \section{The \LangLoop{} Language}
  8912. \newcommand{\LwhileGrammarRacket}{
  8913. \begin{array}{lcl}
  8914. \Type &::=& \key{Void}\\
  8915. \Exp &::=& \CSETBANG{\Var}{\Exp}
  8916. \MID \CBEGIN{\Exp\ldots}{\Exp}
  8917. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  8918. \end{array}
  8919. }
  8920. \newcommand{\LwhileASTRacket}{
  8921. \begin{array}{lcl}
  8922. \Type &::=& \key{Void}\\
  8923. \Exp &::=& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}\\
  8924. &\MID& \WHILE{\Exp}{\Exp} \MID \VOID{}
  8925. \end{array}
  8926. }
  8927. \newcommand{\LwhileGrammarPython}{
  8928. \begin{array}{rcl}
  8929. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  8930. \end{array}
  8931. }
  8932. \newcommand{\LwhileASTPython}{
  8933. \begin{array}{lcl}
  8934. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  8935. \end{array}
  8936. }
  8937. \begin{figure}[tp]
  8938. \centering
  8939. \fbox{
  8940. \begin{minipage}{0.96\textwidth}
  8941. \small
  8942. {\if\edition\racketEd
  8943. \[
  8944. \begin{array}{l}
  8945. \gray{\LintGrammarRacket{}} \\ \hline
  8946. \gray{\LvarGrammarRacket{}} \\ \hline
  8947. \gray{\LifGrammarRacket{}} \\ \hline
  8948. \LwhileGrammarRacket \\
  8949. \begin{array}{lcl}
  8950. \LangLoopM{} &::=& \Exp
  8951. \end{array}
  8952. \end{array}
  8953. \]
  8954. \fi}
  8955. {\if\edition\pythonEd
  8956. \[
  8957. \begin{array}{l}
  8958. \gray{\LintGrammarPython} \\ \hline
  8959. \gray{\LvarGrammarPython} \\ \hline
  8960. \gray{\LifGrammarPython} \\ \hline
  8961. \LwhileGrammarPython \\
  8962. \begin{array}{rcl}
  8963. \LangLoopM{} &::=& \Stmt^{*}
  8964. \end{array}
  8965. \end{array}
  8966. \]
  8967. \fi}
  8968. \end{minipage}
  8969. }
  8970. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-concrete-syntax}).}
  8971. \label{fig:Lwhile-concrete-syntax}
  8972. \end{figure}
  8973. \begin{figure}[tp]
  8974. \centering
  8975. \fbox{
  8976. \begin{minipage}{0.96\textwidth}
  8977. \small
  8978. {\if\edition\racketEd
  8979. \[
  8980. \begin{array}{l}
  8981. \gray{\LintOpAST} \\ \hline
  8982. \gray{\LvarASTRacket{}} \\ \hline
  8983. \gray{\LifASTRacket{}} \\ \hline
  8984. \LwhileASTRacket{} \\
  8985. \begin{array}{lcl}
  8986. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  8987. \end{array}
  8988. \end{array}
  8989. \]
  8990. \fi}
  8991. {\if\edition\pythonEd
  8992. \[
  8993. \begin{array}{l}
  8994. \gray{\LintASTPython} \\ \hline
  8995. \gray{\LvarASTPython} \\ \hline
  8996. \gray{\LifASTPython} \\ \hline
  8997. \LwhileASTPython \\
  8998. \begin{array}{lcl}
  8999. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9000. \end{array}
  9001. \end{array}
  9002. \]
  9003. \fi}
  9004. \end{minipage}
  9005. }
  9006. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-syntax}).}
  9007. \label{fig:Lwhile-syntax}
  9008. \end{figure}
  9009. The concrete syntax of \LangLoop{} is defined in
  9010. Figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  9011. in Figure~\ref{fig:Lwhile-syntax}.
  9012. %
  9013. The definitional interpreter for \LangLoop{} is shown in
  9014. Figure~\ref{fig:interp-Rwhile}.
  9015. %
  9016. {\if\edition\racketEd
  9017. %
  9018. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  9019. and \code{Void} and we make changes to the cases for \code{Var} and
  9020. \code{Let} regarding variables. To support assignment to variables and
  9021. to make their lifetimes indefinite (see the second example in
  9022. Section~\ref{sec:assignment-scoping}), we box the value that is bound
  9023. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  9024. value.
  9025. %
  9026. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9027. variable in the environment to obtain a boxed value and then we change
  9028. it using \code{set-box!} to the result of evaluating the right-hand
  9029. side. The result value of a \code{SetBang} is \code{void}.
  9030. %
  9031. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9032. if the result is true, 2) evaluate the body.
  9033. The result value of a \code{while} loop is also \code{void}.
  9034. %
  9035. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9036. subexpressions \itm{es} for their effects and then evaluates
  9037. and returns the result from \itm{body}.
  9038. %
  9039. The $\VOID{}$ expression produces the \code{void} value.
  9040. %
  9041. \fi}
  9042. {\if\edition\pythonEd
  9043. %
  9044. We add a new case for \code{While} in the \code{interp\_stmts}
  9045. function, where we repeatedly interpret the \code{body} so long as the
  9046. \code{test} expression remains true.
  9047. %
  9048. \fi}
  9049. \begin{figure}[tbp]
  9050. {\if\edition\racketEd
  9051. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9052. (define interp-Rwhile_class
  9053. (class interp-Rany_class
  9054. (super-new)
  9055. (define/override ((interp-exp env) e)
  9056. (define recur (interp-exp env))
  9057. (match e
  9058. [(SetBang x rhs)
  9059. (set-box! (lookup x env) (recur rhs))]
  9060. [(WhileLoop cnd body)
  9061. (define (loop)
  9062. (cond [(recur cnd) (recur body) (loop)]
  9063. [else (void)]))
  9064. (loop)]
  9065. [(Begin es body)
  9066. (for ([e es]) (recur e))
  9067. (recur body)]
  9068. [(Void) (void)]
  9069. [else ((super interp-exp env) e)]))
  9070. ))
  9071. (define (interp-Rwhile p)
  9072. (send (new interp-Rwhile_class) interp-program p))
  9073. \end{lstlisting}
  9074. \fi}
  9075. {\if\edition\pythonEd
  9076. \begin{lstlisting}
  9077. class InterpLwhile(InterpLif):
  9078. def interp_stmts(self, ss, env):
  9079. if len(ss) == 0:
  9080. return
  9081. match ss[0]:
  9082. case While(test, body, []):
  9083. while self.interp_exp(test, env):
  9084. self.interp_stmts(body, env)
  9085. return self.interp_stmts(ss[1:], env)
  9086. case _:
  9087. return super().interp_stmts(ss, env)
  9088. \end{lstlisting}
  9089. \fi}
  9090. \caption{Interpreter for \LangLoop{}.}
  9091. \label{fig:interp-Rwhile}
  9092. \end{figure}
  9093. The type checker for \LangLoop{} is defined in
  9094. Figure~\ref{fig:type-check-Rwhile}.
  9095. %
  9096. {\if\edition\racketEd
  9097. %
  9098. For \LangLoop{} we add a type named \code{Void} and the only value of
  9099. this type is the \code{void} value.
  9100. %
  9101. The type checking of the \code{SetBang} expression requires the type of
  9102. the variable and the right-hand-side to agree. The result type is
  9103. \code{Void}. For \code{while}, the condition must be a
  9104. \code{Boolean}. The result type is also \code{Void}. For
  9105. \code{Begin}, the result type is the type of its last subexpression.
  9106. %
  9107. \fi}
  9108. %
  9109. {\if\edition\pythonEd
  9110. %
  9111. A \code{while} loop is well typed if the type of the \code{test}
  9112. expression is \code{bool} and the statements in the \code{body} are
  9113. well typed.
  9114. %
  9115. \fi}
  9116. \begin{figure}[tbp]
  9117. {\if\edition\racketEd
  9118. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9119. (define type-check-Rwhile_class
  9120. (class type-check-Rany_class
  9121. (super-new)
  9122. (inherit check-type-equal?)
  9123. (define/override (type-check-exp env)
  9124. (lambda (e)
  9125. (define recur (type-check-exp env))
  9126. (match e
  9127. [(SetBang x rhs)
  9128. (define-values (rhs^ rhsT) (recur rhs))
  9129. (define varT (dict-ref env x))
  9130. (check-type-equal? rhsT varT e)
  9131. (values (SetBang x rhs^) 'Void)]
  9132. [(WhileLoop cnd body)
  9133. (define-values (cnd^ Tc) (recur cnd))
  9134. (check-type-equal? Tc 'Boolean e)
  9135. (define-values (body^ Tbody) ((type-check-exp env) body))
  9136. (values (WhileLoop cnd^ body^) 'Void)]
  9137. [(Begin es body)
  9138. (define-values (es^ ts)
  9139. (for/lists (l1 l2) ([e es]) (recur e)))
  9140. (define-values (body^ Tbody) (recur body))
  9141. (values (Begin es^ body^) Tbody)]
  9142. [else ((super type-check-exp env) e)])))
  9143. ))
  9144. (define (type-check-Rwhile p)
  9145. (send (new type-check-Rwhile_class) type-check-program p))
  9146. \end{lstlisting}
  9147. \fi}
  9148. {\if\edition\pythonEd
  9149. \begin{lstlisting}
  9150. class TypeCheckLwhile(TypeCheckLif):
  9151. def type_check_stmts(self, ss, env):
  9152. if len(ss) == 0:
  9153. return
  9154. match ss[0]:
  9155. case While(test, body, []):
  9156. test_t = self.type_check_exp(test, env)
  9157. check_type_equal(bool, test_t, test)
  9158. body_t = self.type_check_stmts(body, env)
  9159. return self.type_check_stmts(ss[1:], env)
  9160. case _:
  9161. return super().type_check_stmts(ss, env)
  9162. \end{lstlisting}
  9163. \fi}
  9164. \caption{Type checker for the \LangLoop{} language.}
  9165. \label{fig:type-check-Rwhile}
  9166. \end{figure}
  9167. {\if\edition\racketEd
  9168. %
  9169. At first glance, the translation of these language features to x86
  9170. seems straightforward because the \LangCIf{} intermediate language
  9171. already supports all of the ingredients that we need: assignment,
  9172. \code{goto}, conditional branching, and sequencing. However, there are
  9173. complications that arise which we discuss in the next section. After
  9174. that we introduce the changes necessary to the existing passes.
  9175. %
  9176. \fi}
  9177. {\if\edition\pythonEd
  9178. %
  9179. At first glance, the translation of \code{while} loops to x86 seems
  9180. straightforward because the \LangCIf{} intermediate language already
  9181. supports \code{goto} and conditional branching. However, there are
  9182. complications that arise which we discuss in the next section. After
  9183. that we introduce the changes necessary to the existing passes.
  9184. %
  9185. \fi}
  9186. \section{Cyclic Control Flow and Dataflow Analysis}
  9187. \label{sec:dataflow-analysis}
  9188. Up until this point the control-flow graphs of the programs generated
  9189. in \code{explicate\_control} were guaranteed to be acyclic. However,
  9190. each \code{while} loop introduces a cycle in the control-flow graph.
  9191. But does that matter?
  9192. %
  9193. Indeed it does. Recall that for register allocation, the compiler
  9194. performs liveness analysis to determine which variables can share the
  9195. same register. To accomplish this we analyzed the control-flow graph
  9196. in reverse topological order
  9197. (Section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9198. only well-defined for acyclic graphs.
  9199. Let us return to the example of computing the sum of the first five
  9200. positive integers. Here is the program after instruction selection but
  9201. before register allocation.
  9202. \begin{center}
  9203. {\if\edition\racketEd
  9204. \begin{minipage}{0.45\textwidth}
  9205. \begin{lstlisting}
  9206. (define (main) : Integer
  9207. mainstart:
  9208. movq $0, sum
  9209. movq $5, i
  9210. jmp block5
  9211. block5:
  9212. movq i, tmp3
  9213. cmpq tmp3, $0
  9214. jl block7
  9215. jmp block8
  9216. \end{lstlisting}
  9217. \end{minipage}
  9218. \begin{minipage}{0.45\textwidth}
  9219. \begin{lstlisting}
  9220. block7:
  9221. addq i, sum
  9222. movq $1, tmp4
  9223. negq tmp4
  9224. addq tmp4, i
  9225. jmp block5
  9226. block8:
  9227. movq $27, %rax
  9228. addq sum, %rax
  9229. jmp mainconclusion
  9230. )
  9231. \end{lstlisting}
  9232. \end{minipage}
  9233. \fi}
  9234. {\if\edition\pythonEd
  9235. \begin{minipage}{0.45\textwidth}
  9236. \begin{lstlisting}
  9237. mainstart:
  9238. movq $0, sum
  9239. movq $5, i
  9240. jmp block5
  9241. block5:
  9242. cmpq $0, i
  9243. jg block7
  9244. jmp block8
  9245. \end{lstlisting}
  9246. \end{minipage}
  9247. \begin{minipage}{0.45\textwidth}
  9248. \begin{lstlisting}
  9249. block7:
  9250. addq i, sum
  9251. subq $1, i
  9252. jmp block5
  9253. block8:
  9254. movq sum, %rdi
  9255. callq print_int
  9256. movq $0, %rax
  9257. jmp mainconclusion
  9258. \end{lstlisting}
  9259. \end{minipage}
  9260. \fi}
  9261. \end{center}
  9262. Recall that liveness analysis works backwards, starting at the end
  9263. of each function. For this example we could start with \code{block8}
  9264. because we know what is live at the beginning of the conclusion,
  9265. just \code{rax} and \code{rsp}. So the live-before set
  9266. for \code{block8} is $\{\ttm{rsp},\ttm{sum}\}$.
  9267. %
  9268. Next we might try to analyze \code{block5} or \code{block7}, but
  9269. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9270. we are stuck.
  9271. The way out of this impasse is to realize that we can compute an
  9272. under-approximation of the live-before set by starting with empty
  9273. live-after sets. By \emph{under-approximation}, we mean that the set
  9274. only contains variables that are live for some execution of the
  9275. program, but the set may be missing some variables. Next, the
  9276. under-approximations for each block can be improved by 1) updating the
  9277. live-after set for each block using the approximate live-before sets
  9278. from the other blocks and 2) perform liveness analysis again on each
  9279. block. In fact, by iterating this process, the under-approximations
  9280. eventually become the correct solutions!
  9281. %
  9282. This approach of iteratively analyzing a control-flow graph is
  9283. applicable to many static analysis problems and goes by the name
  9284. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9285. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9286. Washington.
  9287. Let us apply this approach to the above example. We use the empty set
  9288. for the initial live-before set for each block. Let $m_0$ be the
  9289. following mapping from label names to sets of locations (variables and
  9290. registers).
  9291. \begin{center}
  9292. \begin{lstlisting}
  9293. mainstart: {}, block5: {}, block7: {}, block8: {}
  9294. \end{lstlisting}
  9295. \end{center}
  9296. Using the above live-before approximations, we determine the
  9297. live-after for each block and then apply liveness analysis to each
  9298. block. This produces our next approximation $m_1$ of the live-before
  9299. sets.
  9300. \begin{center}
  9301. \begin{lstlisting}
  9302. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9303. \end{lstlisting}
  9304. \end{center}
  9305. For the second round, the live-after for \code{mainstart} is the
  9306. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9307. liveness analysis for \code{mainstart} computes the empty set. The
  9308. live-after for \code{block5} is the union of the live-before sets for
  9309. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9310. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9311. sum\}}. The live-after for \code{block7} is the live-before for
  9312. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9313. So the liveness analysis for \code{block7} remains \code{\{i,
  9314. sum\}}. Together these yield the following approximation $m_2$ of
  9315. the live-before sets.
  9316. \begin{center}
  9317. \begin{lstlisting}
  9318. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9319. \end{lstlisting}
  9320. \end{center}
  9321. In the preceding iteration, only \code{block5} changed, so we can
  9322. limit our attention to \code{mainstart} and \code{block7}, the two
  9323. blocks that jump to \code{block5}. As a result, the live-before sets
  9324. for \code{mainstart} and \code{block7} are updated to include
  9325. \code{rsp}, yielding the following approximation $m_3$.
  9326. \begin{center}
  9327. \begin{lstlisting}
  9328. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9329. \end{lstlisting}
  9330. \end{center}
  9331. Because \code{block7} changed, we analyze \code{block5} once more, but
  9332. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9333. our approximations have converged, so $m_3$ is the solution.
  9334. This iteration process is guaranteed to converge to a solution by the
  9335. Kleene Fixed-Point Theorem, a general theorem about functions on
  9336. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9337. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9338. elements, a least element $\bot$ (pronounced bottom), and a join
  9339. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9340. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9341. working with join semi-lattices.} When two elements are ordered $m_i
  9342. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9343. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9344. approximation than $m_i$. The bottom element $\bot$ represents the
  9345. complete lack of information, i.e., the worst approximation. The join
  9346. operator takes two lattice elements and combines their information,
  9347. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9348. bound}
  9349. A dataflow analysis typically involves two lattices: one lattice to
  9350. represent abstract states and another lattice that aggregates the
  9351. abstract states of all the blocks in the control-flow graph. For
  9352. liveness analysis, an abstract state is a set of locations. We form
  9353. the lattice $L$ by taking its elements to be sets of locations, the
  9354. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9355. set, and the join operator to be set union.
  9356. %
  9357. We form a second lattice $M$ by taking its elements to be mappings
  9358. from the block labels to sets of locations (elements of $L$). We
  9359. order the mappings point-wise, using the ordering of $L$. So given any
  9360. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9361. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9362. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9363. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9364. We can think of one iteration of liveness analysis applied to the
  9365. whole program as being a function $f$ on the lattice $M$. It takes a
  9366. mapping as input and computes a new mapping.
  9367. \[
  9368. f(m_i) = m_{i+1}
  9369. \]
  9370. Next let us think for a moment about what a final solution $m_s$
  9371. should look like. If we perform liveness analysis using the solution
  9372. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9373. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9374. \[
  9375. f(m_s) = m_s
  9376. \]
  9377. Furthermore, the solution should only include locations that are
  9378. forced to be there by performing liveness analysis on the program, so
  9379. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9380. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9381. monotone (better inputs produce better outputs), then the least fixed
  9382. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9383. chain} obtained by starting at $\bot$ and iterating $f$ as
  9384. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9385. \[
  9386. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9387. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9388. \]
  9389. When a lattice contains only finitely-long ascending chains, then
  9390. every Kleene chain tops out at some fixed point after some number of
  9391. iterations of $f$.
  9392. \[
  9393. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9394. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9395. \]
  9396. The liveness analysis is indeed a monotone function and the lattice
  9397. $M$ only has finitely-long ascending chains because there are only a
  9398. finite number of variables and blocks in the program. Thus we are
  9399. guaranteed that iteratively applying liveness analysis to all blocks
  9400. in the program will eventually produce the least fixed point solution.
  9401. Next let us consider dataflow analysis in general and discuss the
  9402. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9403. %
  9404. The algorithm has four parameters: the control-flow graph \code{G}, a
  9405. function \code{transfer} that applies the analysis to one block, the
  9406. \code{bottom} and \code{join} operator for the lattice of abstract
  9407. states. The algorithm begins by creating the bottom mapping,
  9408. represented by a hash table. It then pushes all of the nodes in the
  9409. control-flow graph onto the work list (a queue). The algorithm repeats
  9410. the \code{while} loop as long as there are items in the work list. In
  9411. each iteration, a node is popped from the work list and processed. The
  9412. \code{input} for the node is computed by taking the join of the
  9413. abstract states of all the predecessor nodes. The \code{transfer}
  9414. function is then applied to obtain the \code{output} abstract
  9415. state. If the output differs from the previous state for this block,
  9416. the mapping for this block is updated and its successor nodes are
  9417. pushed onto the work list.
  9418. Note that the \code{analyze\_dataflow} function is formulated as a
  9419. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9420. function come from the predecessor nodes in the control-flow
  9421. graph. However, liveness analysis is a \emph{backward} dataflow
  9422. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9423. function with the transpose of the control-flow graph.
  9424. \begin{figure}[tb]
  9425. {\if\edition\racketEd
  9426. \begin{lstlisting}
  9427. (define (analyze_dataflow G transfer bottom join)
  9428. (define mapping (make-hash))
  9429. (for ([v (in-vertices G)])
  9430. (dict-set! mapping v bottom))
  9431. (define worklist (make-queue))
  9432. (for ([v (in-vertices G)])
  9433. (enqueue! worklist v))
  9434. (define trans-G (transpose G))
  9435. (while (not (queue-empty? worklist))
  9436. (define node (dequeue! worklist))
  9437. (define input (for/fold ([state bottom])
  9438. ([pred (in-neighbors trans-G node)])
  9439. (join state (dict-ref mapping pred))))
  9440. (define output (transfer node input))
  9441. (cond [(not (equal? output (dict-ref mapping node)))
  9442. (dict-set! mapping node output)
  9443. (for ([v (in-neighbors G node)])
  9444. (enqueue! worklist v))]))
  9445. mapping)
  9446. \end{lstlisting}
  9447. \fi}
  9448. {\if\edition\pythonEd
  9449. \begin{lstlisting}
  9450. def analyze_dataflow(G, transfer, bottom, join):
  9451. trans_G = transpose(G)
  9452. mapping = dict((v, bottom) for v in G.vertices())
  9453. worklist = deque(G.vertices)
  9454. while worklist:
  9455. node = worklist.pop()
  9456. input = reduce(join, [mapping[v] for v in trans_G.adjacent(node)], bottom)
  9457. output = transfer(node, input)
  9458. if output != mapping[node]:
  9459. mapping[node] = output
  9460. worklist.extend(G.adjacent(node))
  9461. \end{lstlisting}
  9462. \fi}
  9463. \caption{Generic work list algorithm for dataflow analysis}
  9464. \label{fig:generic-dataflow}
  9465. \end{figure}
  9466. {\if\edition\racketEd
  9467. \section{Mutable Variables \& Remove Complex Operands}
  9468. There is a subtle interaction between the addition of \code{set!}, the
  9469. \code{remove\_complex\_operands} pass, and the left-to-right order of
  9470. evaluation of Racket. Consider the following example.
  9471. \begin{lstlisting}
  9472. (let ([x 2])
  9473. (+ x (begin (set! x 40) x)))
  9474. \end{lstlisting}
  9475. The result of this program is \code{42} because the first read from
  9476. \code{x} produces \code{2} and the second produces \code{40}. However,
  9477. if we naively apply the \code{remove\_complex\_operands} pass to this
  9478. example we obtain the following program whose result is \code{80}!
  9479. \begin{lstlisting}
  9480. (let ([x 2])
  9481. (let ([tmp (begin (set! x 40) x)])
  9482. (+ x tmp)))
  9483. \end{lstlisting}
  9484. The problem is that, with mutable variables, the ordering between
  9485. reads and writes is important, and the
  9486. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9487. before the first read of \code{x}.
  9488. We recommend solving this problem by giving special treatment to reads
  9489. from mutable variables, that is, variables that occur on the left-hand
  9490. side of a \code{set!}. We mark each read from a mutable variable with
  9491. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9492. that the read operation is effectful in that it can produce different
  9493. results at different points in time. Let's apply this idea to the
  9494. following variation that also involves a variable that is not mutated.
  9495. % loop_test_24.rkt
  9496. \begin{lstlisting}
  9497. (let ([x 2])
  9498. (let ([y 0])
  9499. (+ y (+ x (begin (set! x 40) x)))))
  9500. \end{lstlisting}
  9501. We analyze the above program to discover that variable \code{x} is
  9502. mutable but \code{y} is not. We then transform the program as follows,
  9503. replacing each occurence of \code{x} with \code{(get! x)}.
  9504. \begin{lstlisting}
  9505. (let ([x 2])
  9506. (let ([y 0])
  9507. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9508. \end{lstlisting}
  9509. Now that we have a clear distinction between reads from mutable and
  9510. immutable variables, we can apply the \code{remove\_complex\_operands}
  9511. pass, where reads from immutable variables are still classified as
  9512. atomic expressions but reads from mutable variables are classified as
  9513. complex. Thus, \code{remove\_complex\_operands} yields the following
  9514. program.
  9515. \begin{lstlisting}
  9516. (let ([x 2])
  9517. (let ([y 0])
  9518. (+ y (let ([t1 (get! x)])
  9519. (let ([t2 (begin (set! x 40) (get! x))])
  9520. (+ t1 t2))))))
  9521. \end{lstlisting}
  9522. The temporary variable \code{t1} gets the value of \code{x} before the
  9523. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9524. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9525. do not generate a temporary variable for the occurence of \code{y}
  9526. because it's an immutable variable. We want to avoid such unnecessary
  9527. extra temporaries because they would needless increase the number of
  9528. variables, making it more likely for some of them to be spilled. The
  9529. result of this program is \code{42}, the same as the result prior to
  9530. \code{remove\_complex\_operands}.
  9531. The approach that we've sketched above requires only a small
  9532. modification to \code{remove\_complex\_operands} to handle
  9533. \code{get!}. However, it requires a new pass, called
  9534. \code{uncover-get!}, that we discuss in
  9535. Section~\ref{sec:uncover-get-bang}.
  9536. As an aside, this problematic interaction between \code{set!} and the
  9537. pass \code{remove\_complex\_operands} is particular to Racket and not
  9538. its predecessor, the Scheme language. The key difference is that
  9539. Scheme does not specify an order of evaluation for the arguments of an
  9540. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9541. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9542. would be correct results for the example program. Interestingly,
  9543. Racket is implemented on top of the Chez Scheme
  9544. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9545. presented in this section (using extra \code{let} bindings to control
  9546. the order of evaluation) is used in the translation from Racket to
  9547. Scheme~\citep{Flatt:2019tb}.
  9548. \fi} % racket
  9549. Having discussed the complications that arise from adding support for
  9550. assignment and loops, we turn to discussing the individual compilation
  9551. passes.
  9552. {\if\edition\racketEd
  9553. \section{Uncover \texttt{get!}}
  9554. \label{sec:uncover-get-bang}
  9555. The goal of this pass it to mark uses of mutable variables so that
  9556. \code{remove\_complex\_operands} can treat them as complex expressions
  9557. and thereby preserve their ordering relative to the side-effects in
  9558. other operands. So the first step is to collect all the mutable
  9559. variables. We recommend creating an auxilliary function for this,
  9560. named \code{collect-set!}, that recursively traverses expressions,
  9561. returning a set of all variables that occur on the left-hand side of a
  9562. \code{set!}. Here's an exerpt of its implementation.
  9563. \begin{center}
  9564. \begin{minipage}{\textwidth}
  9565. \begin{lstlisting}
  9566. (define (collect-set! e)
  9567. (match e
  9568. [(Var x) (set)]
  9569. [(Int n) (set)]
  9570. [(Let x rhs body)
  9571. (set-union (collect-set! rhs) (collect-set! body))]
  9572. [(SetBang var rhs)
  9573. (set-union (set var) (collect-set! rhs))]
  9574. ...))
  9575. \end{lstlisting}
  9576. \end{minipage}
  9577. \end{center}
  9578. By placing this pass after \code{uniquify}, we need not worry about
  9579. variable shadowing and our logic for \code{let} can remain simple, as
  9580. in the exerpt above.
  9581. The second step is to mark the occurences of the mutable variables
  9582. with the new \code{GetBang} AST node (\code{get!} in concrete
  9583. syntax). The following is an exerpt of the \code{uncover-get!-exp}
  9584. function, which takes two parameters: the set of mutable varaibles
  9585. \code{set!-vars}, and the expression \code{e} to be processed. The
  9586. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9587. mutable variable or leaves it alone if not.
  9588. \begin{center}
  9589. \begin{minipage}{\textwidth}
  9590. \begin{lstlisting}
  9591. (define ((uncover-get!-exp set!-vars) e)
  9592. (match e
  9593. [(Var x)
  9594. (if (set-member? set!-vars x)
  9595. (GetBang x)
  9596. (Var x))]
  9597. ...))
  9598. \end{lstlisting}
  9599. \end{minipage}
  9600. \end{center}
  9601. To wrap things up, define the \code{uncover-get!} function for
  9602. processing a whole program, using \code{collect-set!} to obtain the
  9603. set of mutable variables and then \code{uncover-get!-exp} to replace
  9604. their occurences with \code{GetBang}.
  9605. \fi}
  9606. \section{Remove Complex Operands}
  9607. \label{sec:rco-loop}
  9608. {\if\edition\racketEd
  9609. %
  9610. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9611. \code{while} are all complex expressions. The subexpressions of
  9612. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9613. %
  9614. \fi}
  9615. {\if\edition\pythonEd
  9616. %
  9617. The change needed for this pass is to add a case for the \code{while}
  9618. statement. The condition of a \code{while} loop is allowed to be a
  9619. complex expression, just like the condition of the \code{if}
  9620. statement.
  9621. %
  9622. \fi}
  9623. %
  9624. Figure~\ref{fig:Rwhile-anf-syntax} defines the output language
  9625. \LangLoopANF{} of this pass.
  9626. \begin{figure}[tp]
  9627. \centering
  9628. \fbox{
  9629. \begin{minipage}{0.96\textwidth}
  9630. \small
  9631. {\if\edition\racketEd
  9632. \[
  9633. \begin{array}{rcl}
  9634. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} } \MID \VOID{} \\
  9635. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9636. &\MID& \GETBANG{\Var}
  9637. \MID \SETBANG{\Var}{\Exp} \\
  9638. &\MID& \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9639. \MID \WHILE{\Exp}{\Exp} \\
  9640. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9641. \LangLoopANF &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9642. \end{array}
  9643. \]
  9644. \fi}
  9645. {\if\edition\pythonEd
  9646. \[
  9647. \begin{array}{rcl}
  9648. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9649. \Exp &::=& \Atm \MID \READ{} \\
  9650. &\MID& \BINOP{\itm{binaryop}}{\Atm}{\Atm} \MID \UNIOP{\key{unaryop}}{\Atm} \\
  9651. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9652. % &\MID& \LET{\Var}{\Exp}{\Exp}\\
  9653. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9654. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9655. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9656. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9657. \end{array}
  9658. \]
  9659. \fi}
  9660. \end{minipage}
  9661. }
  9662. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9663. \label{fig:Rwhile-anf-syntax}
  9664. \end{figure}
  9665. {\if\edition\racketEd
  9666. As usual, when a complex expression appears in a grammar position that
  9667. needs to be atomic, such as the argument of a primitive operator, we
  9668. must introduce a temporary variable and bind it to the complex
  9669. expression. This approach applies, unchanged, to handle the new
  9670. language forms. For example, in the following code there are two
  9671. \code{begin} expressions appearing as arguments to \code{+}. The
  9672. output of \code{rco\_exp} is shown below, in which the \code{begin}
  9673. expressions have been bound to temporary variables. Recall that
  9674. \code{let} expressions in \LangLoopANF{} are allowed to have
  9675. arbitrary expressions in their right-hand-side expression, so it is
  9676. fine to place \code{begin} there.
  9677. \begin{center}
  9678. \begin{minipage}{\textwidth}
  9679. \begin{lstlisting}
  9680. (let ([x0 10])
  9681. (let ([y1 0])
  9682. (+ (+ (begin (set! y1 (read)) x0)
  9683. (begin (set! x0 (read)) y1))
  9684. x0)))
  9685. |$\Rightarrow$|
  9686. (let ([x0 10])
  9687. (let ([y1 0])
  9688. (let ([tmp2 (begin (set! y1 (read)) x0)])
  9689. (let ([tmp3 (begin (set! x0 (read)) y1)])
  9690. (let ([tmp4 (+ tmp2 tmp3)])
  9691. (+ tmp4 x0))))))
  9692. \end{lstlisting}
  9693. \end{minipage}
  9694. \end{center}
  9695. \fi}
  9696. \section{Explicate Control \racket{and \LangCLoop{}}}
  9697. \label{sec:explicate-loop}
  9698. {\if\edition\racketEd
  9699. Recall that in the \code{explicate\_control} pass we define one helper
  9700. function for each kind of position in the program. For the \LangVar{}
  9701. language of integers and variables we needed kinds of positions:
  9702. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  9703. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  9704. yet another kind of position: effect position. Except for the last
  9705. subexpression, the subexpressions inside a \code{begin} are evaluated
  9706. only for their effect. Their result values are discarded. We can
  9707. generate better code by taking this fact into account.
  9708. The output language of \code{explicate\_control} is \LangCLoop{}
  9709. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9710. \LangCLam{}. The only syntactic difference is that \code{Call} and
  9711. \code{read} may also appear as statements. The most significant
  9712. difference between \LangCLam{} and \LangCLoop{} is that the
  9713. control-flow graphs of the later may contain cycles.
  9714. \begin{figure}[tp]
  9715. \fbox{
  9716. \begin{minipage}{0.96\textwidth}
  9717. \small
  9718. \[
  9719. \begin{array}{lcl}
  9720. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  9721. \MID \READ{}\\
  9722. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  9723. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9724. \end{array}
  9725. \]
  9726. \end{minipage}
  9727. }
  9728. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  9729. \label{fig:c7-syntax}
  9730. \end{figure}
  9731. The new auxiliary function \code{explicate\_effect} takes an
  9732. expression (in an effect position) and a continuation. The function
  9733. returns a $\Tail$ that includes the generated code for the input
  9734. expression followed by the continuation. If the expression is
  9735. obviously pure, that is, never causes side effects, then the
  9736. expression can be removed, so the result is just the continuation.
  9737. %
  9738. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9739. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9740. the loop. Recursively process the \itm{body} (in effect position)
  9741. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9742. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9743. \itm{body'} as the then-branch and the continuation block as the
  9744. else-branch. The result should be added to the control-flow graph with
  9745. the label \itm{loop}. The result for the whole \code{while} loop is a
  9746. \code{goto} to the \itm{loop} label.
  9747. The auxiliary functions for tail, assignment, and predicate positions
  9748. need to be updated. The three new language forms, \code{while},
  9749. \code{set!}, and \code{begin}, can appear in assignment and tail
  9750. positions. Only \code{begin} may appear in predicate positions; the
  9751. other two have result type \code{Void}.
  9752. \fi}
  9753. %
  9754. {\if\edition\pythonEd
  9755. %
  9756. The output of this pass is the language \LangCIf{}. No new language
  9757. features are needed in the output because a \code{while} loop can be
  9758. expressed in terms of \code{goto} and \code{if} statements, which are
  9759. already in \LangCIf{}.
  9760. %
  9761. Add a case for the \code{while} statement to the
  9762. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  9763. the condition expression.
  9764. %
  9765. \fi}
  9766. {\if\edition\racketEd
  9767. \section{Select Instructions}
  9768. \label{sec:select-instructions-loop}
  9769. Only three small additions are needed in the
  9770. \code{select\_instructions} pass to handle the changes to
  9771. \LangCLoop{}. That is, a \code{Call} to \code{read} may now appear as a
  9772. stand-alone statement instead of only appearing on the right-hand
  9773. side of an assignment statement. The code generation is nearly
  9774. identical; just leave off the instruction for moving the result into
  9775. the left-hand side.
  9776. \fi}
  9777. \section{Register Allocation}
  9778. \label{sec:register-allocation-loop}
  9779. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9780. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9781. which complicates the liveness analysis needed for register
  9782. allocation.
  9783. \subsection{Liveness Analysis}
  9784. \label{sec:liveness-analysis-r8}
  9785. We recommend using the generic \code{analyze\_dataflow} function that
  9786. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9787. perform liveness analysis, replacing the code in
  9788. \code{uncover\_live} that processed the basic blocks in topological
  9789. order (Section~\ref{sec:liveness-analysis-Lif}).
  9790. The \code{analyze\_dataflow} function has four parameters.
  9791. \begin{enumerate}
  9792. \item The first parameter \code{G} should be a directed graph from the
  9793. \racket{
  9794. \code{racket/graph} package (see the sidebar in
  9795. Section~\ref{sec:build-interference})}
  9796. \python{\code{graph.py} file in the support code}
  9797. that represents the
  9798. control-flow graph.
  9799. \item The second parameter \code{transfer} is a function that applies
  9800. liveness analysis to a basic block. It takes two parameters: the
  9801. label for the block to analyze and the live-after set for that
  9802. block. The transfer function should return the live-before set for
  9803. the block.
  9804. %
  9805. \racket{Also, as a side-effect, it should update the block's
  9806. $\itm{info}$ with the liveness information for each instruction.}
  9807. %
  9808. \python{Also, as a side-effect, it should update the live-before and
  9809. live-after sets for each instruction.}
  9810. %
  9811. To implement the \code{transfer} function, you should be able to
  9812. reuse the code you already have for analyzing basic blocks.
  9813. \item The third and fourth parameters of \code{analyze\_dataflow} are
  9814. \code{bottom} and \code{join} for the lattice of abstract states,
  9815. i.e. sets of locations. The bottom of the lattice is the empty set
  9816. and the join operator is set union.
  9817. \end{enumerate}
  9818. \begin{figure}[p]
  9819. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9820. \node (Rfun) at (0,2) {\large \LangLoop{}};
  9821. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  9822. %\node (Rfun-3) at (6,2) {\large \LangLoop{}};
  9823. %\node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  9824. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  9825. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  9826. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  9827. \node (F1-4) at (6,2) {\large \LangLoop{}};
  9828. \node (F1-5) at (9,2) {\large \LangLoopANF{}};
  9829. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  9830. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  9831. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  9832. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  9833. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  9834. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  9835. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  9836. %% \path[->,bend left=15] (Rfun) edge [above] node
  9837. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  9838. \path[->,bend left=15] (Rfun) edge [above] node
  9839. {\ttfamily\footnotesize shrink} (Rfun-2);
  9840. \path[->,bend left=15] (Rfun-2) edge [above] node
  9841. {\ttfamily\footnotesize uniquify} (F1-4);
  9842. %% \path[->,bend left=15] (Rfun-3) edge [above] node
  9843. %% {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  9844. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9845. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  9846. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9847. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  9848. %% \path[->,bend right=15] (F1-2) edge [above] node
  9849. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  9850. %% \path[->,bend right=15] (F1-3) edge [above] node
  9851. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9852. \path[->,bend left=15] (F1-4) edge [above] node
  9853. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  9854. \path[->,bend left=15] (F1-5) edge [right] node
  9855. {\ttfamily\footnotesize explicate\_control} (C3-2);
  9856. \path[->,bend left=15] (C3-2) edge [left] node
  9857. {\ttfamily\footnotesize select\_instr.} (x86-2);
  9858. \path[->,bend right=15] (x86-2) edge [left] node
  9859. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9860. \path[->,bend right=15] (x86-2-1) edge [below] node
  9861. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  9862. \path[->,bend right=15] (x86-2-2) edge [left] node
  9863. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  9864. \path[->,bend left=15] (x86-3) edge [above] node
  9865. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  9866. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  9867. \end{tikzpicture}
  9868. \caption{Diagram of the passes for \LangLoop{}.}
  9869. \label{fig:Rwhile-passes}
  9870. \end{figure}
  9871. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  9872. for the compilation of \LangLoop{}.
  9873. % Further Reading: dataflow analysis
  9874. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9875. \chapter{Tuples and Garbage Collection}
  9876. \label{ch:Lvec}
  9877. \index{subject}{tuple}
  9878. \index{subject}{vector}
  9879. \index{subject}{allocate}
  9880. \index{subject}{heap allocate}
  9881. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  9882. %% all the IR grammars are spelled out! \\ --Jeremy}
  9883. %% \margincomment{\scriptsize Be more explicit about how to deal with
  9884. %% the root stack. \\ --Jeremy}
  9885. In this chapter we study the implementation of
  9886. tuples\racket{, called vectors in Racket}.
  9887. %
  9888. This language feature is the first of ours to use the computer's
  9889. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  9890. indefinite, that is, a tuple lives forever from the programmer's
  9891. viewpoint. Of course, from an implementer's viewpoint, it is important
  9892. to reclaim the space associated with a tuple when it is no longer
  9893. needed, which is why we also study \emph{garbage collection}
  9894. \index{garbage collection} techniques in this chapter.
  9895. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  9896. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  9897. language of Chapter~\ref{ch:Lwhile} with tuples.
  9898. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  9899. copying live objects back and forth between two halves of the
  9900. heap. The garbage collector requires coordination with the compiler so
  9901. that it can see all of the \emph{root} pointers, that is, pointers in
  9902. registers or on the procedure call stack.
  9903. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  9904. discuss all the necessary changes and additions to the compiler
  9905. passes, including a new compiler pass named \code{expose\_allocation}.
  9906. \section{The \LangVec{} Language}
  9907. \label{sec:r3}
  9908. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  9909. \LangVec{} and Figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  9910. %
  9911. \racket{The \LangVec{} language includes the forms: \code{vector} for
  9912. creating a tuple, \code{vector-ref} for reading an element of a
  9913. tuple, \code{vector-set!} for writing to an element of a tuple, and
  9914. \code{vector-length} for obtaining the number of elements of a
  9915. tuple.}
  9916. %
  9917. \python{The \LangVec{} language adds 1) tuple creation via a
  9918. comma-separated list of expressions, 2) accessing an element of a
  9919. tuple with the square bracket notation, i.e., \code{t[n]} returns
  9920. the nth element of the tuple \code{t}, 3) the \code{is} comparison
  9921. operator, and 4) obtaining the number of elements (the length) of a
  9922. tuple.}
  9923. %
  9924. The program below shows an example use of tuples. It creates a 3-tuple
  9925. \code{t} and a 1-tuple that is stored at index $2$ of the 3-tuple,
  9926. demonstrating that tuples are first-class values. The element at
  9927. index $1$ of \code{t} is \racket{\code{\#t}}\python{\code{True}}, so the
  9928. ``then'' branch of the \key{if} is taken. The element at index $0$ of
  9929. \code{t} is \code{40}, to which we add \code{2}, the element at index
  9930. $0$ of the 1-tuple. So the result of the program is \code{42}.
  9931. %
  9932. {\if\edition\racketEd
  9933. \begin{lstlisting}
  9934. (let ([t (vector 40 #t (vector 2))])
  9935. (if (vector-ref t 1)
  9936. (+ (vector-ref t 0)
  9937. (vector-ref (vector-ref t 2) 0))
  9938. 44))
  9939. \end{lstlisting}
  9940. \fi}
  9941. {\if\edition\pythonEd
  9942. \begin{lstlisting}
  9943. t = 40, True, (2,)
  9944. print( t[0] + t[2][0] if t[1] else 44 )
  9945. \end{lstlisting}
  9946. \fi}
  9947. \newcommand{\LtupGrammarRacket}{
  9948. \begin{array}{lcl}
  9949. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  9950. \Exp &::=& \LP\key{vector}\;\Exp\ldots\RP
  9951. \MID \LP\key{vector-length}\;\Exp\RP \\
  9952. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  9953. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  9954. \end{array}
  9955. }
  9956. \newcommand{\LtupASTRacket}{
  9957. \begin{array}{lcl}
  9958. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  9959. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  9960. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  9961. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  9962. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  9963. \end{array}
  9964. }
  9965. \newcommand{\LtupGrammarPython}{
  9966. \begin{array}{rcl}
  9967. \itm{cmp} &::= & \key{is} \\
  9968. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp} \MID \CLEN{\Exp}
  9969. \end{array}
  9970. }
  9971. \newcommand{\LtupASTPython}{
  9972. \begin{array}{lcl}
  9973. \itm{cmp} &::= & \code{Is()} \\
  9974. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  9975. &\MID& \LEN{\Exp}
  9976. \end{array}
  9977. }
  9978. \begin{figure}[tbp]
  9979. \centering
  9980. \fbox{
  9981. \begin{minipage}{0.96\textwidth}
  9982. {\if\edition\racketEd
  9983. \[
  9984. \begin{array}{l}
  9985. \gray{\LintGrammarRacket{}} \\ \hline
  9986. \gray{\LvarGrammarRacket{}} \\ \hline
  9987. \gray{\LifGrammarRacket{}} \\ \hline
  9988. \gray{\LwhileGrammarRacket} \\ \hline
  9989. \LtupGrammarRacket \\
  9990. \begin{array}{lcl}
  9991. \LangVecM{} &::=& \Exp
  9992. \end{array}
  9993. \end{array}
  9994. \]
  9995. \fi}
  9996. {\if\edition\pythonEd
  9997. \[
  9998. \begin{array}{l}
  9999. \gray{\LintGrammarPython{}} \\ \hline
  10000. \gray{\LvarGrammarPython{}} \\ \hline
  10001. \gray{\LifGrammarPython{}} \\ \hline
  10002. \gray{\LwhileGrammarPython} \\ \hline
  10003. \LtupGrammarPython \\
  10004. \begin{array}{rcl}
  10005. \LangVecM{} &::=& \Stmt^{*}
  10006. \end{array}
  10007. \end{array}
  10008. \]
  10009. \fi}
  10010. \end{minipage}
  10011. }
  10012. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  10013. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  10014. \label{fig:Lvec-concrete-syntax}
  10015. \end{figure}
  10016. \begin{figure}[tp]
  10017. \centering
  10018. \fbox{
  10019. \begin{minipage}{0.96\textwidth}
  10020. {\if\edition\racketEd
  10021. \[
  10022. \begin{array}{l}
  10023. \gray{\LintOpAST} \\ \hline
  10024. \gray{\LvarASTRacket{}} \\ \hline
  10025. \gray{\LifASTRacket{}} \\ \hline
  10026. \gray{\LwhileASTRacket{}} \\ \hline
  10027. \LtupASTRacket{} \\
  10028. \begin{array}{lcl}
  10029. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  10030. \end{array}
  10031. \end{array}
  10032. \]
  10033. \fi}
  10034. {\if\edition\pythonEd
  10035. \[
  10036. \begin{array}{l}
  10037. \gray{\LintASTPython} \\ \hline
  10038. \gray{\LvarASTPython} \\ \hline
  10039. \gray{\LifASTPython} \\ \hline
  10040. \gray{\LwhileASTPython} \\ \hline
  10041. \LtupASTPython \\
  10042. \begin{array}{lcl}
  10043. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10044. \end{array}
  10045. \end{array}
  10046. \]
  10047. \fi}
  10048. \end{minipage}
  10049. }
  10050. \caption{The abstract syntax of \LangVec{}.}
  10051. \label{fig:Lvec-syntax}
  10052. \end{figure}
  10053. Tuples raises several interesting new issues. First, variable binding
  10054. performs a shallow-copy when dealing with tuples, which means that
  10055. different variables can refer to the same tuple, that is, two
  10056. variables can be \emph{aliases}\index{subject}{alias} for the same
  10057. entity. Consider the following example in which both \code{t1} and
  10058. \code{t2} refer to the same tuple value but \code{t3} refers to a
  10059. different tuple value but with equal elements. The result of the
  10060. program is \code{42}.
  10061. \begin{center}
  10062. \begin{minipage}{0.96\textwidth}
  10063. {\if\edition\racketEd
  10064. \begin{lstlisting}
  10065. (let ([t1 (vector 3 7)])
  10066. (let ([t2 t1])
  10067. (let ([t3 (vector 3 7)])
  10068. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10069. 42
  10070. 0))))
  10071. \end{lstlisting}
  10072. \fi}
  10073. {\if\edition\pythonEd
  10074. \begin{lstlisting}
  10075. t1 = 3, 7
  10076. t2 = t1
  10077. t3 = 3, 7
  10078. print( 42 if (t1 is t2) and not (t1 is t3) else 0)
  10079. \end{lstlisting}
  10080. \fi}
  10081. \end{minipage}
  10082. \end{center}
  10083. {\if\edition\racketEd
  10084. Whether two variables are aliased or not affects what happens
  10085. when the underlying tuple is mutated\index{subject}{mutation}.
  10086. Consider the following example in which \code{t1} and \code{t2}
  10087. again refer to the same tuple value.
  10088. \begin{center}
  10089. \begin{minipage}{0.96\textwidth}
  10090. \begin{lstlisting}
  10091. (let ([t1 (vector 3 7)])
  10092. (let ([t2 t1])
  10093. (let ([_ (vector-set! t2 0 42)])
  10094. (vector-ref t1 0))))
  10095. \end{lstlisting}
  10096. \end{minipage}
  10097. \end{center}
  10098. The mutation through \code{t2} is visible when referencing the tuple
  10099. from \code{t1}, so the result of this program is \code{42}.
  10100. \fi}
  10101. The next issue concerns the lifetime of tuples. When does their
  10102. lifetime end? Notice that \LangVec{} does not include an operation
  10103. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10104. to any notion of static scoping.
  10105. %
  10106. {\if\edition\racketEd
  10107. %
  10108. For example, the following program returns \code{42} even though the
  10109. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10110. that reads from the vector it was bound to.
  10111. \begin{center}
  10112. \begin{minipage}{0.96\textwidth}
  10113. \begin{lstlisting}
  10114. (let ([v (vector (vector 44))])
  10115. (let ([x (let ([w (vector 42)])
  10116. (let ([_ (vector-set! v 0 w)])
  10117. 0))])
  10118. (+ x (vector-ref (vector-ref v 0) 0))))
  10119. \end{lstlisting}
  10120. \end{minipage}
  10121. \end{center}
  10122. \fi}
  10123. %
  10124. {\if\edition\pythonEd
  10125. %
  10126. For example, the following program returns \code{42} even though the
  10127. variable \code{x} goes out of scope when the function returns, prior
  10128. to reading the tuple element at index zero. (We study the compilation
  10129. of functions in Chapter~\ref{ch:Rfun}.)
  10130. %
  10131. \begin{center}
  10132. \begin{minipage}{0.96\textwidth}
  10133. \begin{lstlisting}
  10134. def f():
  10135. x = 42, 43
  10136. return x
  10137. t = f()
  10138. print( t[0] )
  10139. \end{lstlisting}
  10140. \end{minipage}
  10141. \end{center}
  10142. \fi}
  10143. %
  10144. From the perspective of programmer-observable behavior, tuples live
  10145. forever. Of course, if they really lived forever then many programs
  10146. would run out of memory. The language's runtime system must therefore
  10147. perform automatic garbage collection.
  10148. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10149. \LangVec{} language.
  10150. %
  10151. \racket{We define the \code{vector}, \code{vector-ref},
  10152. \code{vector-set!}, and \code{vector-length} operations for
  10153. \LangVec{} in terms of the corresponding operations in Racket. One
  10154. subtle point is that the \code{vector-set!} operation returns the
  10155. \code{\#<void>} value.}
  10156. %
  10157. \python{We define tuple creation, element access, and the \code{len}
  10158. operator for \LangVec{} in terms of the corresponding operations in
  10159. Python.}
  10160. \begin{figure}[tbp]
  10161. {\if\edition\racketEd
  10162. \begin{lstlisting}
  10163. (define interp-Lvec_class
  10164. (class interp-Lif_class
  10165. (super-new)
  10166. (define/override (interp-op op)
  10167. (match op
  10168. ['eq? (lambda (v1 v2)
  10169. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10170. (and (boolean? v1) (boolean? v2))
  10171. (and (vector? v1) (vector? v2))
  10172. (and (void? v1) (void? v2)))
  10173. (eq? v1 v2)]))]
  10174. ['vector vector]
  10175. ['vector-length vector-length]
  10176. ['vector-ref vector-ref]
  10177. ['vector-set! vector-set!]
  10178. [else (super interp-op op)]
  10179. ))
  10180. (define/override ((interp-exp env) e)
  10181. (define recur (interp-exp env))
  10182. (match e
  10183. [(HasType e t) (recur e)]
  10184. [(Void) (void)]
  10185. [else ((super interp-exp env) e)]
  10186. ))
  10187. ))
  10188. (define (interp-Lvec p)
  10189. (send (new interp-Lvec_class) interp-program p))
  10190. \end{lstlisting}
  10191. \fi}
  10192. %
  10193. {\if\edition\pythonEd
  10194. \begin{lstlisting}
  10195. class InterpLtup(InterpLwhile):
  10196. def interp_cmp(self, cmp):
  10197. match cmp:
  10198. case Is():
  10199. return lambda x, y: x is y
  10200. case _:
  10201. return super().interp_cmp(cmp)
  10202. def interp_exp(self, e, env):
  10203. match e:
  10204. case Tuple(es, Load()):
  10205. return tuple([self.interp_exp(e, env) for e in es])
  10206. case Subscript(tup, index, Load()):
  10207. t = self.interp_exp(tup, env)
  10208. n = self.interp_exp(index, env)
  10209. return t[n]
  10210. case _:
  10211. return super().interp_exp(e, env)
  10212. \end{lstlisting}
  10213. \fi}
  10214. \caption{Interpreter for the \LangVec{} language.}
  10215. \label{fig:interp-Lvec}
  10216. \end{figure}
  10217. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10218. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10219. we need to know which elements of the tuple are pointers (i.e. are
  10220. also tuple) for garbage collection purposes. We can obtain this
  10221. information during type checking. The type checker in
  10222. Figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10223. expression, it also
  10224. %
  10225. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10226. where $T$ is the vector's type.
  10227. To create the s-expression for the \code{Vector} type in
  10228. Figure~\ref{fig:type-check-Lvec}, we use the
  10229. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10230. operator} \code{,@} to insert the list \code{t*} without its usual
  10231. start and end parentheses. \index{subject}{unquote-slicing}}
  10232. %
  10233. \python{records the type of each tuple expression in a new field
  10234. named \code{has\_type}.}
  10235. \begin{figure}[tp]
  10236. {\if\edition\racketEd
  10237. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10238. (define type-check-Lvec_class
  10239. (class type-check-Lif_class
  10240. (super-new)
  10241. (inherit check-type-equal?)
  10242. (define/override (type-check-exp env)
  10243. (lambda (e)
  10244. (define recur (type-check-exp env))
  10245. (match e
  10246. [(Void) (values (Void) 'Void)]
  10247. [(Prim 'vector es)
  10248. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10249. (define t `(Vector ,@t*))
  10250. (values (HasType (Prim 'vector e*) t) t)]
  10251. [(Prim 'vector-ref (list e1 (Int i)))
  10252. (define-values (e1^ t) (recur e1))
  10253. (match t
  10254. [`(Vector ,ts ...)
  10255. (unless (and (0 . <= . i) (i . < . (length ts)))
  10256. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10257. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10258. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10259. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10260. (define-values (e-vec t-vec) (recur e1))
  10261. (define-values (e-arg^ t-arg) (recur arg))
  10262. (match t-vec
  10263. [`(Vector ,ts ...)
  10264. (unless (and (0 . <= . i) (i . < . (length ts)))
  10265. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10266. (check-type-equal? (list-ref ts i) t-arg e)
  10267. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10268. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10269. [(Prim 'vector-length (list e))
  10270. (define-values (e^ t) (recur e))
  10271. (match t
  10272. [`(Vector ,ts ...)
  10273. (values (Prim 'vector-length (list e^)) 'Integer)]
  10274. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10275. [(Prim 'eq? (list arg1 arg2))
  10276. (define-values (e1 t1) (recur arg1))
  10277. (define-values (e2 t2) (recur arg2))
  10278. (match* (t1 t2)
  10279. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10280. [(other wise) (check-type-equal? t1 t2 e)])
  10281. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10282. [(HasType (Prim 'vector es) t)
  10283. ((type-check-exp env) (Prim 'vector es))]
  10284. [(HasType e1 t)
  10285. (define-values (e1^ t^) (recur e1))
  10286. (check-type-equal? t t^ e)
  10287. (values (HasType e1^ t) t)]
  10288. [else ((super type-check-exp env) e)]
  10289. )))
  10290. ))
  10291. (define (type-check-Lvec p)
  10292. (send (new type-check-Lvec_class) type-check-program p))
  10293. \end{lstlisting}
  10294. \fi}
  10295. {\if\edition\pythonEd
  10296. \begin{lstlisting}
  10297. class TypeCheckLtup(TypeCheckLwhile):
  10298. def type_check_exp(self, e, env):
  10299. match e:
  10300. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10301. l = self.type_check_exp(left, env)
  10302. r = self.type_check_exp(right, env)
  10303. check_type_equal(l, r, e)
  10304. return bool
  10305. case Tuple(es, Load()):
  10306. ts = [self.type_check_exp(e, env) for e in es]
  10307. e.has_type = tuple(ts)
  10308. return e.has_type
  10309. case Subscript(tup, Constant(index), Load()):
  10310. tup_ty = self.type_check_exp(tup, env)
  10311. index_ty = self.type_check_exp(Constant(index), env)
  10312. check_type_equal(index_ty, int, index)
  10313. match tup_ty:
  10314. case tuple(ts):
  10315. return ts[index]
  10316. case _:
  10317. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10318. case _:
  10319. return super().type_check_exp(e, env)
  10320. \end{lstlisting}
  10321. \fi}
  10322. \caption{Type checker for the \LangVec{} language.}
  10323. \label{fig:type-check-Lvec}
  10324. \end{figure}
  10325. \section{Garbage Collection}
  10326. \label{sec:GC}
  10327. Here we study a relatively simple algorithm for garbage collection
  10328. that is the basis of state-of-the-art garbage
  10329. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10330. particular, we describe a two-space copying
  10331. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10332. perform the
  10333. copy~\citep{Cheney:1970aa}.
  10334. \index{subject}{copying collector}
  10335. \index{subject}{two-space copying collector}
  10336. Figure~\ref{fig:copying-collector} gives a
  10337. coarse-grained depiction of what happens in a two-space collector,
  10338. showing two time steps, prior to garbage collection (on the top) and
  10339. after garbage collection (on the bottom). In a two-space collector,
  10340. the heap is divided into two parts named the FromSpace and the
  10341. ToSpace. Initially, all allocations go to the FromSpace until there is
  10342. not enough room for the next allocation request. At that point, the
  10343. garbage collector goes to work to make more room.
  10344. \index{subject}{ToSpace}
  10345. \index{subject}{FromSpace}
  10346. The garbage collector must be careful not to reclaim tuples that will
  10347. be used by the program in the future. Of course, it is impossible in
  10348. general to predict what a program will do, but we can over approximate
  10349. the will-be-used tuples by preserving all tuples that could be
  10350. accessed by \emph{any} program given the current computer state. A
  10351. program could access any tuple whose address is in a register or on
  10352. the procedure call stack. These addresses are called the \emph{root
  10353. set}\index{subject}{root set}. In addition, a program could access any tuple that is
  10354. transitively reachable from the root set. Thus, it is safe for the
  10355. garbage collector to reclaim the tuples that are not reachable in this
  10356. way.
  10357. So the goal of the garbage collector is twofold:
  10358. \begin{enumerate}
  10359. \item preserve all tuple that are reachable from the root set via a
  10360. path of pointers, that is, the \emph{live} tuples, and
  10361. \item reclaim the memory of everything else, that is, the
  10362. \emph{garbage}.
  10363. \end{enumerate}
  10364. A copying collector accomplishes this by copying all of the live
  10365. objects from the FromSpace into the ToSpace and then performs a sleight
  10366. of hand, treating the ToSpace as the new FromSpace and the old
  10367. FromSpace as the new ToSpace. In the example of
  10368. Figure~\ref{fig:copying-collector}, there are three pointers in the
  10369. root set, one in a register and two on the stack. All of the live
  10370. objects have been copied to the ToSpace (the right-hand side of
  10371. Figure~\ref{fig:copying-collector}) in a way that preserves the
  10372. pointer relationships. For example, the pointer in the register still
  10373. points to a 2-tuple whose first element is a 3-tuple and whose second
  10374. element is a 2-tuple. There are four tuples that are not reachable
  10375. from the root set and therefore do not get copied into the ToSpace.
  10376. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  10377. created by a well-typed program in \LangVec{} because it contains a
  10378. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  10379. We design the garbage collector to deal with cycles to begin with so
  10380. we will not need to revisit this issue.
  10381. \begin{figure}[tbp]
  10382. \centering
  10383. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  10384. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  10385. \caption{A copying collector in action.}
  10386. \label{fig:copying-collector}
  10387. \end{figure}
  10388. There are many alternatives to copying collectors (and their bigger
  10389. siblings, the generational collectors) when its comes to garbage
  10390. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  10391. reference counting~\citep{Collins:1960aa}. The strengths of copying
  10392. collectors are that allocation is fast (just a comparison and pointer
  10393. increment), there is no fragmentation, cyclic garbage is collected,
  10394. and the time complexity of collection only depends on the amount of
  10395. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  10396. main disadvantages of a two-space copying collector is that it uses a
  10397. lot of space and takes a long time to perform the copy, though these
  10398. problems are ameliorated in generational collectors. Racket and
  10399. Scheme programs tend to allocate many small objects and generate a lot
  10400. of garbage, so copying and generational collectors are a good fit.
  10401. Garbage collection is an active research topic, especially concurrent
  10402. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  10403. developing new techniques and revisiting old
  10404. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  10405. meet every year at the International Symposium on Memory Management to
  10406. present these findings.
  10407. \subsection{Graph Copying via Cheney's Algorithm}
  10408. \label{sec:cheney}
  10409. \index{subject}{Cheney's algorithm}
  10410. Let us take a closer look at the copying of the live objects. The
  10411. allocated objects and pointers can be viewed as a graph and we need to
  10412. copy the part of the graph that is reachable from the root set. To
  10413. make sure we copy all of the reachable vertices in the graph, we need
  10414. an exhaustive graph traversal algorithm, such as depth-first search or
  10415. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10416. such algorithms take into account the possibility of cycles by marking
  10417. which vertices have already been visited, so as to ensure termination
  10418. of the algorithm. These search algorithms also use a data structure
  10419. such as a stack or queue as a to-do list to keep track of the vertices
  10420. that need to be visited. We use breadth-first search and a trick
  10421. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10422. and copying tuples into the ToSpace.
  10423. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10424. copy progresses. The queue is represented by a chunk of contiguous
  10425. memory at the beginning of the ToSpace, using two pointers to track
  10426. the front and the back of the queue. The algorithm starts by copying
  10427. all tuples that are immediately reachable from the root set into the
  10428. ToSpace to form the initial queue. When we copy a tuple, we mark the
  10429. old tuple to indicate that it has been visited. We discuss how this
  10430. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  10431. pointers inside the copied tuples in the queue still point back to the
  10432. FromSpace. Once the initial queue has been created, the algorithm
  10433. enters a loop in which it repeatedly processes the tuple at the front
  10434. of the queue and pops it off the queue. To process a tuple, the
  10435. algorithm copies all the tuple that are directly reachable from it to
  10436. the ToSpace, placing them at the back of the queue. The algorithm then
  10437. updates the pointers in the popped tuple so they point to the newly
  10438. copied tuples.
  10439. \begin{figure}[tbp]
  10440. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  10441. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10442. \label{fig:cheney}
  10443. \end{figure}
  10444. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  10445. tuple whose second element is $42$ to the back of the queue. The other
  10446. pointer goes to a tuple that has already been copied, so we do not
  10447. need to copy it again, but we do need to update the pointer to the new
  10448. location. This can be accomplished by storing a \emph{forwarding
  10449. pointer} to the new location in the old tuple, back when we initially
  10450. copied the tuple into the ToSpace. This completes one step of the
  10451. algorithm. The algorithm continues in this way until the front of the
  10452. queue is empty, that is, until the front catches up with the back.
  10453. \subsection{Data Representation}
  10454. \label{sec:data-rep-gc}
  10455. The garbage collector places some requirements on the data
  10456. representations used by our compiler. First, the garbage collector
  10457. needs to distinguish between pointers and other kinds of data. There
  10458. are several ways to accomplish this.
  10459. \begin{enumerate}
  10460. \item Attached a tag to each object that identifies what type of
  10461. object it is~\citep{McCarthy:1960dz}.
  10462. \item Store different types of objects in different
  10463. regions~\citep{Steele:1977ab}.
  10464. \item Use type information from the program to either generate
  10465. type-specific code for collecting or to generate tables that can
  10466. guide the
  10467. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10468. \end{enumerate}
  10469. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10470. need to tag objects anyways, so option 1 is a natural choice for those
  10471. languages. However, \LangVec{} is a statically typed language, so it
  10472. would be unfortunate to require tags on every object, especially small
  10473. and pervasive objects like integers and Booleans. Option 3 is the
  10474. best-performing choice for statically typed languages, but comes with
  10475. a relatively high implementation complexity. To keep this chapter
  10476. within a 2-week time budget, we recommend a combination of options 1
  10477. and 2, using separate strategies for the stack and the heap.
  10478. Regarding the stack, we recommend using a separate stack for pointers,
  10479. which we call a \emph{root stack}\index{subject}{root stack}
  10480. (a.k.a. ``shadow
  10481. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10482. is, when a local variable needs to be spilled and is of type
  10483. \racket{\code{Vector}}\python{\code{TupleType}}, then we put it on the
  10484. root stack instead of the normal procedure call stack. Furthermore, we
  10485. always spill tuple-typed variables if they are live during a call to
  10486. the collector, thereby ensuring that no pointers are in registers
  10487. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  10488. example from Figure~\ref{fig:copying-collector} and contrasts it with
  10489. the data layout using a root stack. The root stack contains the two
  10490. pointers from the regular stack and also the pointer in the second
  10491. register.
  10492. \begin{figure}[tbp]
  10493. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  10494. \caption{Maintaining a root stack to facilitate garbage collection.}
  10495. \label{fig:shadow-stack}
  10496. \end{figure}
  10497. The problem of distinguishing between pointers and other kinds of data
  10498. also arises inside of each tuple on the heap. We solve this problem by
  10499. attaching a tag, an extra 64-bits, to each
  10500. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10501. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  10502. that we have drawn the bits in a big-endian way, from right-to-left,
  10503. with bit location 0 (the least significant bit) on the far right,
  10504. which corresponds to the direction of the x86 shifting instructions
  10505. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10506. is dedicated to specifying which elements of the tuple are pointers,
  10507. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10508. indicates there is a pointer and a 0 bit indicates some other kind of
  10509. data. The pointer mask starts at bit location 7. We have limited
  10510. tuples to a maximum size of 50 elements, so we just need 50 bits for
  10511. the pointer mask. The tag also contains two other pieces of
  10512. information. The length of the tuple (number of elements) is stored in
  10513. bits location 1 through 6. Finally, the bit at location 0 indicates
  10514. whether the tuple has yet to be copied to the ToSpace. If the bit has
  10515. value 1, then this tuple has not yet been copied. If the bit has
  10516. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  10517. of a pointer are always zero anyways because our tuples are 8-byte
  10518. aligned.)
  10519. \begin{figure}[tbp]
  10520. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10521. \caption{Representation of tuples in the heap.}
  10522. \label{fig:tuple-rep}
  10523. \end{figure}
  10524. \subsection{Implementation of the Garbage Collector}
  10525. \label{sec:organize-gz}
  10526. \index{subject}{prelude}
  10527. An implementation of the copying collector is provided in the
  10528. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10529. interface to the garbage collector that is used by the compiler. The
  10530. \code{initialize} function creates the FromSpace, ToSpace, and root
  10531. stack and should be called in the prelude of the \code{main}
  10532. function. The arguments of \code{initialize} are the root stack size
  10533. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10534. good choice for both. The \code{initialize} function puts the address
  10535. of the beginning of the FromSpace into the global variable
  10536. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10537. the address that is 1-past the last element of the FromSpace. (We use
  10538. half-open intervals to represent chunks of
  10539. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  10540. points to the first element of the root stack.
  10541. As long as there is room left in the FromSpace, your generated code
  10542. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10543. %
  10544. The amount of room left in FromSpace is the difference between the
  10545. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10546. function should be called when there is not enough room left in the
  10547. FromSpace for the next allocation. The \code{collect} function takes
  10548. a pointer to the current top of the root stack (one past the last item
  10549. that was pushed) and the number of bytes that need to be
  10550. allocated. The \code{collect} function performs the copying collection
  10551. and leaves the heap in a state such that the next allocation will
  10552. succeed.
  10553. \begin{figure}[tbp]
  10554. \begin{lstlisting}
  10555. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10556. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10557. int64_t* free_ptr;
  10558. int64_t* fromspace_begin;
  10559. int64_t* fromspace_end;
  10560. int64_t** rootstack_begin;
  10561. \end{lstlisting}
  10562. \caption{The compiler's interface to the garbage collector.}
  10563. \label{fig:gc-header}
  10564. \end{figure}
  10565. %% \begin{exercise}
  10566. %% In the file \code{runtime.c} you will find the implementation of
  10567. %% \code{initialize} and a partial implementation of \code{collect}.
  10568. %% The \code{collect} function calls another function, \code{cheney},
  10569. %% to perform the actual copy, and that function is left to the reader
  10570. %% to implement. The following is the prototype for \code{cheney}.
  10571. %% \begin{lstlisting}
  10572. %% static void cheney(int64_t** rootstack_ptr);
  10573. %% \end{lstlisting}
  10574. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10575. %% rootstack (which is an array of pointers). The \code{cheney} function
  10576. %% also communicates with \code{collect} through the global
  10577. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10578. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  10579. %% the ToSpace:
  10580. %% \begin{lstlisting}
  10581. %% static int64_t* tospace_begin;
  10582. %% static int64_t* tospace_end;
  10583. %% \end{lstlisting}
  10584. %% The job of the \code{cheney} function is to copy all the live
  10585. %% objects (reachable from the root stack) into the ToSpace, update
  10586. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10587. %% update the root stack so that it points to the objects in the
  10588. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10589. %% and ToSpace.
  10590. %% \end{exercise}
  10591. %% \section{Compiler Passes}
  10592. %% \label{sec:code-generation-gc}
  10593. The introduction of garbage collection has a non-trivial impact on our
  10594. compiler passes. We introduce a new compiler pass named
  10595. \code{expose\_allocation}. We make significant changes to
  10596. \code{select\_instructions}, \code{build\_interference},
  10597. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10598. make minor changes in several more passes. The following program will
  10599. serve as our running example. It creates two tuples, one nested
  10600. inside the other. Both tuples have length one. The program accesses
  10601. the element in the inner tuple tuple.
  10602. % tests/vectors_test_17.rkt
  10603. {\if\edition\racketEd
  10604. \begin{lstlisting}
  10605. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10606. \end{lstlisting}
  10607. \fi}
  10608. {\if\edition\pythonEd
  10609. \begin{lstlisting}
  10610. print( ((42,),)[0][0] )
  10611. \end{lstlisting}
  10612. \fi}
  10613. {\if\edition\racketEd
  10614. \section{Shrink}
  10615. \label{sec:shrink-Lvec}
  10616. Recall that the \code{shrink} pass translates the primitives operators
  10617. into a smaller set of primitives.
  10618. %
  10619. This pass comes after type checking and the type checker adds a
  10620. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10621. need to add a case for \code{HasType} to the \code{shrink} pass.
  10622. \fi}
  10623. \section{Expose Allocation}
  10624. \label{sec:expose-allocation}
  10625. The pass \code{expose\_allocation} lowers tuple creation into a
  10626. conditional call to the collector followed by allocating the
  10627. appropriate amount of memory and initializing it. We choose to place
  10628. the \code{expose\_allocation} pass before
  10629. \code{remove\_complex\_operands} because the code generated by
  10630. \code{expose\_allocation} contains complex operands.
  10631. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10632. that extends \LangVec{} with new forms that we use in the translation
  10633. of tuple creation.
  10634. %
  10635. {\if\edition\racketEd
  10636. \[
  10637. \begin{array}{lcl}
  10638. \Exp &::=& \cdots
  10639. \MID (\key{collect} \,\itm{int})
  10640. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10641. \MID (\key{global-value} \,\itm{name})
  10642. \end{array}
  10643. \]
  10644. \fi}
  10645. {\if\edition\pythonEd
  10646. \[
  10647. \begin{array}{lcl}
  10648. \Exp &::=& \cdots\\
  10649. &\MID& \key{collect}(\itm{int})
  10650. \MID \key{allocate}(\itm{int},\itm{type})
  10651. \MID \key{global\_value}(\itm{name}) \\
  10652. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp
  10653. \end{array}
  10654. \]
  10655. \fi}
  10656. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10657. make sure that there are $n$ bytes ready to be allocated. During
  10658. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10659. the \code{collect} function in \code{runtime.c}.
  10660. %
  10661. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10662. space at the front for the 64 bit tag), but the elements are not
  10663. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10664. of the tuple:
  10665. %
  10666. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10667. %
  10668. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10669. \CGLOBAL{\itm{name}} form reads the value of a global variable, such
  10670. as \code{free\_ptr}.
  10671. %
  10672. \python{The \code{begin} form is an expression that executes a
  10673. sequence of statements and then produces the value of the expression
  10674. at the end.}
  10675. The following shows the transformation of tuple creation into 1) a
  10676. sequence of temporary variables bindings for the initializing
  10677. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10678. \code{allocate}, and 4) the initialization of the tuple. The
  10679. \itm{len} placeholder refers to the length of the tuple and
  10680. \itm{bytes} is how many total bytes need to be allocated for the
  10681. tuple, which is 8 for the tag plus \itm{len} times 8.
  10682. %
  10683. \python{The \itm{type} needed for the second argument of the
  10684. \code{allocate} form can be obtained from the \code{has\_type} field
  10685. of the tuple AST node, which is stored there by running the type
  10686. checker for \LangVec{} immediately before this pass.}
  10687. %
  10688. \begin{center}
  10689. \begin{minipage}{\textwidth}
  10690. {\if\edition\racketEd
  10691. \begin{lstlisting}
  10692. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10693. |$\Longrightarrow$|
  10694. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10695. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10696. (global-value fromspace_end))
  10697. (void)
  10698. (collect |\itm{bytes}|))])
  10699. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  10700. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  10701. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  10702. |$v$|) ... )))) ...)
  10703. \end{lstlisting}
  10704. \fi}
  10705. {\if\edition\pythonEd
  10706. \begin{lstlisting}
  10707. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  10708. |$\Longrightarrow$|
  10709. begin:
  10710. |$x_0$| = |$e_0$|
  10711. |$\vdots$|
  10712. |$x_{n-1}$| = |$e_{n-1}$|
  10713. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  10714. 0
  10715. else:
  10716. collect(|\itm{bytes}|)
  10717. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  10718. |$v$|[0] = |$x_0$|
  10719. |$\vdots$|
  10720. |$v$|[|$n-1$|] = |$x_{n-1}$|
  10721. |$v$|
  10722. \end{lstlisting}
  10723. \fi}
  10724. \end{minipage}
  10725. \end{center}
  10726. %
  10727. \noindent The sequencing of the initializing expressions
  10728. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  10729. they may trigger garbage collection and we cannot have an allocated
  10730. but uninitialized tuple on the heap during a collection.
  10731. Figure~\ref{fig:expose-alloc-output} shows the output of the
  10732. \code{expose\_allocation} pass on our running example.
  10733. \begin{figure}[tbp]
  10734. % tests/s2_17.rkt
  10735. {\if\edition\racketEd
  10736. \begin{lstlisting}
  10737. (vector-ref
  10738. (vector-ref
  10739. (let ([vecinit7976
  10740. (let ([vecinit7972 42])
  10741. (let ([collectret7974
  10742. (if (< (+ (global-value free_ptr) 16)
  10743. (global-value fromspace_end))
  10744. (void)
  10745. (collect 16)
  10746. )])
  10747. (let ([alloc7971 (allocate 1 (Vector Integer))])
  10748. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  10749. alloc7971))))])
  10750. (let ([collectret7978
  10751. (if (< (+ (global-value free_ptr) 16)
  10752. (global-value fromspace_end))
  10753. (void)
  10754. (collect 16)
  10755. )])
  10756. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  10757. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  10758. alloc7975))))
  10759. 0)
  10760. 0)
  10761. \end{lstlisting}
  10762. \fi}
  10763. {\if\edition\pythonEd
  10764. \begin{lstlisting}
  10765. print( |$T_1$|[0][0] )
  10766. \end{lstlisting}
  10767. where $T_1$ is
  10768. \begin{lstlisting}
  10769. begin:
  10770. tmp.1 = |$T_2$|
  10771. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10772. 0
  10773. else:
  10774. collect(16)
  10775. tmp.2 = allocate(1, TupleType(TupleType([int])))
  10776. tmp.2[0] = tmp.1
  10777. tmp.2
  10778. \end{lstlisting}
  10779. and $T_2$ is
  10780. \begin{lstlisting}
  10781. begin:
  10782. tmp.3 = 42
  10783. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10784. 0
  10785. else:
  10786. collect(16)
  10787. tmp.4 = allocate(1, TupleType([int]))
  10788. tmp.4[0] = tmp.3
  10789. tmp.4
  10790. \end{lstlisting}
  10791. \fi}
  10792. \caption{Output of the \code{expose\_allocation} pass.}
  10793. \label{fig:expose-alloc-output}
  10794. \end{figure}
  10795. \section{Remove Complex Operands}
  10796. \label{sec:remove-complex-opera-Lvec}
  10797. {\if\edition\racketEd
  10798. %
  10799. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  10800. should be treated as complex operands.
  10801. %
  10802. \fi}
  10803. %
  10804. {\if\edition\pythonEd
  10805. %
  10806. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  10807. and tuple access should be treated as complex operands. The
  10808. sub-expressions of tuple access must be atomic.
  10809. %
  10810. \fi}
  10811. %% A new case for
  10812. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  10813. %% handled carefully to prevent the \code{Prim} node from being separated
  10814. %% from its enclosing \code{HasType}.
  10815. Figure~\ref{fig:Lvec-anf-syntax}
  10816. shows the grammar for the output language \LangAllocANF{} of this
  10817. pass, which is \LangAlloc{} in monadic normal form.
  10818. \begin{figure}[tp]
  10819. \centering
  10820. \fbox{
  10821. \begin{minipage}{0.96\textwidth}
  10822. \small
  10823. {\if\edition\racketEd
  10824. \[
  10825. \begin{array}{rcl}
  10826. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  10827. \MID \VOID{} } \\
  10828. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  10829. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  10830. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10831. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  10832. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  10833. &\MID& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  10834. \MID \GLOBALVALUE{\Var}\\
  10835. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  10836. \LangAllocANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10837. \end{array}
  10838. \]
  10839. \fi}
  10840. {\if\edition\pythonEd
  10841. \[
  10842. \begin{array}{lcl}
  10843. \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  10844. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  10845. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \MID \code{Is()} \\
  10846. \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  10847. \itm{bool} &::=& \code{True} \MID \code{False} \\
  10848. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  10849. \Exp &::=& \Atm \MID \READ{} \MID \\
  10850. &\MID& \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  10851. \MID \UNIOP{\itm{unaryop}}{\Exp}\\
  10852. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp}
  10853. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  10854. &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  10855. &\MID& \GET{\Atm}{\Atm} \\
  10856. &\MID& \LEN{\Exp}\\
  10857. &\MID& \ALLOCATE{\Int}{\Type}
  10858. \MID \GLOBALVALUE{\Var}\RP\\
  10859. &\MID& \BEGIN{\Stmt^{*}}{\Exp} \\
  10860. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  10861. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  10862. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Exp} \\
  10863. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10864. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}
  10865. \MID \COLLECT{\Int} \\
  10866. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10867. \end{array}
  10868. \]
  10869. \fi}
  10870. \end{minipage}
  10871. }
  10872. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  10873. \label{fig:Lvec-anf-syntax}
  10874. \end{figure}
  10875. \section{Explicate Control and the \LangCVec{} language}
  10876. \label{sec:explicate-control-r3}
  10877. \newcommand{\CtupASTPython}{
  10878. \begin{array}{lcl}
  10879. \Exp &::= & \GET{\Atm}{\Atm}\MID \ALLOCATE{\Int}{\Type} \\
  10880. &\MID& \GLOBALVALUE{\Var}\RP \MID \LEN{\Atm} \\
  10881. \Stmt &::=& \COLLECT{\Int} \\
  10882. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  10883. \end{array}
  10884. }
  10885. \begin{figure}[tp]
  10886. \fbox{
  10887. \begin{minipage}{0.96\textwidth}
  10888. \small
  10889. {\if\edition\racketEd
  10890. \[
  10891. \begin{array}{lcl}
  10892. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  10893. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  10894. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  10895. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  10896. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  10897. &\MID& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  10898. &\MID& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  10899. &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  10900. &\MID& \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP\\
  10901. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  10902. \MID \LP\key{Collect} \,\itm{int}\RP \\
  10903. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  10904. \MID \GOTO{\itm{label}} } \\
  10905. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  10906. \LangCVecM{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  10907. \end{array}
  10908. \]
  10909. \fi}
  10910. {\if\edition\pythonEd
  10911. \[
  10912. \begin{array}{l}
  10913. \gray{\CifASTPython} \\ \hline
  10914. \CtupASTPython \\
  10915. \begin{array}{lcl}
  10916. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  10917. \end{array}
  10918. \end{array}
  10919. \]
  10920. \fi}
  10921. \end{minipage}
  10922. }
  10923. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  10924. (Figure~\ref{fig:c1-syntax}).}
  10925. \label{fig:c2-syntax}
  10926. \end{figure}
  10927. The output of \code{explicate\_control} is a program in the
  10928. intermediate language \LangCVec{}, whose abstract syntax is defined in
  10929. Figure~\ref{fig:c2-syntax}.
  10930. %
  10931. \racket{(The concrete syntax is defined in
  10932. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  10933. %
  10934. The new expressions of \LangCVec{} include \key{allocate},
  10935. %
  10936. \racket{\key{vector-ref}, and \key{vector-set!},}
  10937. %
  10938. \python{accessing tuple elements,}
  10939. %
  10940. and \key{global\_value}.
  10941. %
  10942. \python{\LangCVec{} also includes the \code{collect} statement and
  10943. assignment to a tuple element.}
  10944. %
  10945. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  10946. %
  10947. The \code{explicate\_control} pass can treat these new forms much like
  10948. the other forms that we've already encoutered.
  10949. \section{Select Instructions and the \LangXGlobal{} Language}
  10950. \label{sec:select-instructions-gc}
  10951. \index{subject}{instruction selection}
  10952. %% void (rep as zero)
  10953. %% allocate
  10954. %% collect (callq collect)
  10955. %% vector-ref
  10956. %% vector-set!
  10957. %% vector-length
  10958. %% global (postpone)
  10959. In this pass we generate x86 code for most of the new operations that
  10960. were needed to compile tuples, including \code{Allocate},
  10961. \code{Collect}, and accessing tuple elements.
  10962. %
  10963. We compile \code{GlobalValue} to \code{Global} because the later has a
  10964. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  10965. \ref{fig:x86-2}). \index{subject}{x86}
  10966. The tuple read and write forms translate into \code{movq}
  10967. instructions. (The plus one in the offset is to get past the tag at
  10968. the beginning of the tuple representation.)
  10969. %
  10970. \begin{center}
  10971. \begin{minipage}{\textwidth}
  10972. {\if\edition\racketEd
  10973. \begin{lstlisting}
  10974. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  10975. |$\Longrightarrow$|
  10976. movq |$\itm{tup}'$|, %r11
  10977. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  10978. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  10979. |$\Longrightarrow$|
  10980. movq |$\itm{tup}'$|, %r11
  10981. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  10982. movq $0, |$\itm{lhs'}$|
  10983. \end{lstlisting}
  10984. \fi}
  10985. {\if\edition\pythonEd
  10986. \begin{lstlisting}
  10987. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  10988. |$\Longrightarrow$|
  10989. movq |$\itm{tup}'$|, %r11
  10990. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  10991. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  10992. |$\Longrightarrow$|
  10993. movq |$\itm{tup}'$|, %r11
  10994. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  10995. movq $0, |$\itm{lhs'}$|
  10996. \end{lstlisting}
  10997. \fi}
  10998. \end{minipage}
  10999. \end{center}
  11000. The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$ are obtained by
  11001. translating $\itm{tup}$ and $\itm{rhs}$ to x86. The move of $\itm{tup}'$ to
  11002. register \code{r11} ensures that offset expression
  11003. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  11004. removing \code{r11} from consideration by the register allocating.
  11005. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  11006. \code{rax}. Then the generated code for tuple assignment would be
  11007. \begin{lstlisting}
  11008. movq |$\itm{tup}'$|, %rax
  11009. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  11010. movq $0, |$\itm{lhs}'$|
  11011. \end{lstlisting}
  11012. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  11013. \code{patch\_instructions} would insert a move through \code{rax}
  11014. as follows.
  11015. \begin{lstlisting}
  11016. movq |$\itm{tup}'$|, %rax
  11017. movq |$\itm{rhs}'$|, %rax
  11018. movq %rax, |$8(n+1)$|(%rax)
  11019. movq $0, |$\itm{lhs}'$|
  11020. \end{lstlisting}
  11021. But the above sequence of instructions does not work because we're
  11022. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  11023. $\itm{rhs}'$) at the same time!
  11024. The \racket{\code{vector-length}}\python{\code{len}} operation should
  11025. be translated into a sequence of instructions that read the tag of the
  11026. tuple and extract the six bits that represent the tuple length, which
  11027. are the bits starting at index 1 and going up to and including bit 6.
  11028. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  11029. (shift right) can be used to accomplish this.
  11030. We compile the \code{allocate} form to operations on the
  11031. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  11032. is the next free address in the FromSpace, so we copy it into
  11033. \code{r11} and then move it forward by enough space for the tuple
  11034. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  11035. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  11036. initialize the \itm{tag} and finally copy the address in \code{r11} to
  11037. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  11038. tag is organized.
  11039. %
  11040. \racket{We recommend using the Racket operations
  11041. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11042. during compilation.}
  11043. %
  11044. \python{We recommend using the bitwise-or operator \code{|} and the
  11045. shift-left operator \code{<<} to compute the tag during
  11046. compilation.}
  11047. %
  11048. The type annotation in the \code{allocate} form is used to determine
  11049. the pointer mask region of the tag.
  11050. %
  11051. {\if\edition\racketEd
  11052. \begin{lstlisting}
  11053. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11054. |$\Longrightarrow$|
  11055. movq free_ptr(%rip), %r11
  11056. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11057. movq $|$\itm{tag}$|, 0(%r11)
  11058. movq %r11, |$\itm{lhs}'$|
  11059. \end{lstlisting}
  11060. \fi}
  11061. {\if\edition\pythonEd
  11062. \begin{lstlisting}
  11063. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  11064. |$\Longrightarrow$|
  11065. movq free_ptr(%rip), %r11
  11066. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11067. movq $|$\itm{tag}$|, 0(%r11)
  11068. movq %r11, |$\itm{lhs}'$|
  11069. \end{lstlisting}
  11070. \fi}
  11071. The \code{collect} form is compiled to a call to the \code{collect}
  11072. function in the runtime. The arguments to \code{collect} are 1) the
  11073. top of the root stack and 2) the number of bytes that need to be
  11074. allocated. We use another dedicated register, \code{r15}, to
  11075. store the pointer to the top of the root stack. So \code{r15} is not
  11076. available for use by the register allocator.
  11077. {\if\edition\racketEd
  11078. \begin{lstlisting}
  11079. (collect |$\itm{bytes}$|)
  11080. |$\Longrightarrow$|
  11081. movq %r15, %rdi
  11082. movq $|\itm{bytes}|, %rsi
  11083. callq collect
  11084. \end{lstlisting}
  11085. \fi}
  11086. {\if\edition\pythonEd
  11087. \begin{lstlisting}
  11088. collect(|$\itm{bytes}$|)
  11089. |$\Longrightarrow$|
  11090. movq %r15, %rdi
  11091. movq $|\itm{bytes}|, %rsi
  11092. callq collect
  11093. \end{lstlisting}
  11094. \fi}
  11095. \begin{figure}[tp]
  11096. \fbox{
  11097. \begin{minipage}{0.96\textwidth}
  11098. \[
  11099. \begin{array}{lcl}
  11100. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  11101. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  11102. & & \gray{ \key{main:} \; \Instr\ldots }
  11103. \end{array}
  11104. \]
  11105. \end{minipage}
  11106. }
  11107. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  11108. \label{fig:x86-2-concrete}
  11109. \end{figure}
  11110. \begin{figure}[tp]
  11111. \fbox{
  11112. \begin{minipage}{0.96\textwidth}
  11113. \small
  11114. \[
  11115. \begin{array}{lcl}
  11116. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  11117. \MID \BYTEREG{\Reg}} \\
  11118. &\MID& \GLOBAL{\Var} \\
  11119. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  11120. \end{array}
  11121. \]
  11122. \end{minipage}
  11123. }
  11124. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  11125. \label{fig:x86-2}
  11126. \end{figure}
  11127. The concrete and abstract syntax of the \LangXGlobal{} language is
  11128. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  11129. differs from \LangXIf{} just in the addition of global variables.
  11130. %
  11131. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11132. \code{select\_instructions} pass on the running example.
  11133. \begin{figure}[tbp]
  11134. \centering
  11135. % tests/s2_17.rkt
  11136. \begin{minipage}[t]{0.5\textwidth}
  11137. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11138. block35:
  11139. movq free_ptr(%rip), alloc9024
  11140. addq $16, free_ptr(%rip)
  11141. movq alloc9024, %r11
  11142. movq $131, 0(%r11)
  11143. movq alloc9024, %r11
  11144. movq vecinit9025, 8(%r11)
  11145. movq $0, initret9026
  11146. movq alloc9024, %r11
  11147. movq 8(%r11), tmp9034
  11148. movq tmp9034, %r11
  11149. movq 8(%r11), %rax
  11150. jmp conclusion
  11151. block36:
  11152. movq $0, collectret9027
  11153. jmp block35
  11154. block38:
  11155. movq free_ptr(%rip), alloc9020
  11156. addq $16, free_ptr(%rip)
  11157. movq alloc9020, %r11
  11158. movq $3, 0(%r11)
  11159. movq alloc9020, %r11
  11160. movq vecinit9021, 8(%r11)
  11161. movq $0, initret9022
  11162. movq alloc9020, vecinit9025
  11163. movq free_ptr(%rip), tmp9031
  11164. movq tmp9031, tmp9032
  11165. addq $16, tmp9032
  11166. movq fromspace_end(%rip), tmp9033
  11167. cmpq tmp9033, tmp9032
  11168. jl block36
  11169. jmp block37
  11170. block37:
  11171. movq %r15, %rdi
  11172. movq $16, %rsi
  11173. callq 'collect
  11174. jmp block35
  11175. block39:
  11176. movq $0, collectret9023
  11177. jmp block38
  11178. \end{lstlisting}
  11179. \end{minipage}
  11180. \begin{minipage}[t]{0.45\textwidth}
  11181. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11182. start:
  11183. movq $42, vecinit9021
  11184. movq free_ptr(%rip), tmp9028
  11185. movq tmp9028, tmp9029
  11186. addq $16, tmp9029
  11187. movq fromspace_end(%rip), tmp9030
  11188. cmpq tmp9030, tmp9029
  11189. jl block39
  11190. jmp block40
  11191. block40:
  11192. movq %r15, %rdi
  11193. movq $16, %rsi
  11194. callq 'collect
  11195. jmp block38
  11196. \end{lstlisting}
  11197. \end{minipage}
  11198. \caption{Output of the \code{select\_instructions} pass.}
  11199. \label{fig:select-instr-output-gc}
  11200. \end{figure}
  11201. \clearpage
  11202. \section{Register Allocation}
  11203. \label{sec:reg-alloc-gc}
  11204. \index{subject}{register allocation}
  11205. As discussed earlier in this chapter, the garbage collector needs to
  11206. access all the pointers in the root set, that is, all variables that
  11207. are tuples. It will be the responsibility of the register allocator
  11208. to make sure that:
  11209. \begin{enumerate}
  11210. \item the root stack is used for spilling tuple-typed variables, and
  11211. \item if a tuple-typed variable is live during a call to the
  11212. collector, it must be spilled to ensure it is visible to the
  11213. collector.
  11214. \end{enumerate}
  11215. The later responsibility can be handled during construction of the
  11216. interference graph, by adding interference edges between the call-live
  11217. tuple-typed variables and all the callee-saved registers. (They
  11218. already interfere with the caller-saved registers.)
  11219. %
  11220. \racket{The type information for variables is in the \code{Program}
  11221. form, so we recommend adding another parameter to the
  11222. \code{build\_interference} function to communicate this alist.}
  11223. %
  11224. \python{The type information for variables is generated by the type
  11225. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11226. the \code{CProgram} AST mode. You'll need to propagate that
  11227. information so that it is available in this pass.}
  11228. The spilling of tuple-typed variables to the root stack can be handled
  11229. after graph coloring, when choosing how to assign the colors
  11230. (integers) to registers and stack locations. The
  11231. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11232. changes to also record the number of spills to the root stack.
  11233. % build-interference
  11234. %
  11235. % callq
  11236. % extra parameter for var->type assoc. list
  11237. % update 'program' and 'if'
  11238. % allocate-registers
  11239. % allocate spilled vectors to the rootstack
  11240. % don't change color-graph
  11241. % TODO:
  11242. %\section{Patch Instructions}
  11243. %[mention that global variables are memory references]
  11244. \section{Prelude and Conclusion}
  11245. \label{sec:print-x86-gc}
  11246. \label{sec:prelude-conclusion-x86-gc}
  11247. \index{subject}{prelude}\index{subject}{conclusion}
  11248. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11249. \code{prelude\_and\_conclusion} pass on the running example. In the
  11250. prelude and conclusion of the \code{main} function, we treat the root
  11251. stack very much like the regular stack in that we move the root stack
  11252. pointer (\code{r15}) to make room for the spills to the root stack,
  11253. except that the root stack grows up instead of down. For the running
  11254. example, there was just one spill so we increment \code{r15} by 8
  11255. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  11256. One issue that deserves special care is that there may be a call to
  11257. \code{collect} prior to the initializing assignments for all the
  11258. variables in the root stack. We do not want the garbage collector to
  11259. accidentally think that some uninitialized variable is a pointer that
  11260. needs to be followed. Thus, we zero-out all locations on the root
  11261. stack in the prelude of \code{main}. In
  11262. Figure~\ref{fig:print-x86-output-gc}, the instruction
  11263. %
  11264. \lstinline{movq $0, (%r15)}
  11265. %
  11266. accomplishes this task. The garbage collector tests each root to see
  11267. if it is null prior to dereferencing it.
  11268. \begin{figure}[htbp]
  11269. % TODO: Python Version -Jeremy
  11270. \begin{minipage}[t]{0.5\textwidth}
  11271. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11272. block35:
  11273. movq free_ptr(%rip), %rcx
  11274. addq $16, free_ptr(%rip)
  11275. movq %rcx, %r11
  11276. movq $131, 0(%r11)
  11277. movq %rcx, %r11
  11278. movq -8(%r15), %rax
  11279. movq %rax, 8(%r11)
  11280. movq $0, %rdx
  11281. movq %rcx, %r11
  11282. movq 8(%r11), %rcx
  11283. movq %rcx, %r11
  11284. movq 8(%r11), %rax
  11285. jmp conclusion
  11286. block36:
  11287. movq $0, %rcx
  11288. jmp block35
  11289. block38:
  11290. movq free_ptr(%rip), %rcx
  11291. addq $16, free_ptr(%rip)
  11292. movq %rcx, %r11
  11293. movq $3, 0(%r11)
  11294. movq %rcx, %r11
  11295. movq %rbx, 8(%r11)
  11296. movq $0, %rdx
  11297. movq %rcx, -8(%r15)
  11298. movq free_ptr(%rip), %rcx
  11299. addq $16, %rcx
  11300. movq fromspace_end(%rip), %rdx
  11301. cmpq %rdx, %rcx
  11302. jl block36
  11303. movq %r15, %rdi
  11304. movq $16, %rsi
  11305. callq collect
  11306. jmp block35
  11307. block39:
  11308. movq $0, %rcx
  11309. jmp block38
  11310. \end{lstlisting}
  11311. \end{minipage}
  11312. \begin{minipage}[t]{0.45\textwidth}
  11313. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11314. start:
  11315. movq $42, %rbx
  11316. movq free_ptr(%rip), %rdx
  11317. addq $16, %rdx
  11318. movq fromspace_end(%rip), %rcx
  11319. cmpq %rcx, %rdx
  11320. jl block39
  11321. movq %r15, %rdi
  11322. movq $16, %rsi
  11323. callq collect
  11324. jmp block38
  11325. .globl main
  11326. main:
  11327. pushq %rbp
  11328. movq %rsp, %rbp
  11329. pushq %r13
  11330. pushq %r12
  11331. pushq %rbx
  11332. pushq %r14
  11333. subq $0, %rsp
  11334. movq $16384, %rdi
  11335. movq $16384, %rsi
  11336. callq initialize
  11337. movq rootstack_begin(%rip), %r15
  11338. movq $0, (%r15)
  11339. addq $8, %r15
  11340. jmp start
  11341. conclusion:
  11342. subq $8, %r15
  11343. addq $0, %rsp
  11344. popq %r14
  11345. popq %rbx
  11346. popq %r12
  11347. popq %r13
  11348. popq %rbp
  11349. retq
  11350. \end{lstlisting}
  11351. \end{minipage}
  11352. \caption{Output of the \code{prelude\_and\_conclusion} pass.}
  11353. \label{fig:print-x86-output-gc}
  11354. \end{figure}
  11355. \begin{figure}[tbp]
  11356. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11357. \node (Lvec) at (0,2) {\large \LangVec{}};
  11358. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11359. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11360. \node (Lvec-4) at (9,2) {\large \LangVec{}};
  11361. \node (Lvec-5) at (9,0) {\large \LangAllocANF{}};
  11362. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11363. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11364. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11365. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11366. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11367. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11368. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11369. %\path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize type-check} (Lvec-2);
  11370. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11371. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11372. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11373. \path[->,bend left=15] (Lvec-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvec-5);
  11374. \path[->,bend left=10] (Lvec-5) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11375. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11376. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11377. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11378. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11379. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11380. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  11381. \end{tikzpicture}
  11382. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11383. \label{fig:Lvec-passes}
  11384. \end{figure}
  11385. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11386. for the compilation of \LangVec{}.
  11387. \clearpage
  11388. {\if\edition\racketEd
  11389. \section{Challenge: Simple Structures}
  11390. \label{sec:simple-structures}
  11391. \index{subject}{struct}
  11392. \index{subject}{structure}
  11393. The language \LangStruct{} extends \LangVec{} with support for simple
  11394. structures. Its concrete syntax is defined in
  11395. Figure~\ref{fig:Lstruct-concrete-syntax} and the abstract syntax is in
  11396. Figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct} in Typed
  11397. Racket is a user-defined data type that contains named fields and that
  11398. is heap allocated, similar to a vector. The following is an example of
  11399. a structure definition, in this case the definition of a \code{point}
  11400. type.
  11401. \begin{lstlisting}
  11402. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11403. \end{lstlisting}
  11404. \newcommand{\LstructGrammarRacket}{
  11405. \begin{array}{lcl}
  11406. \Type &::=& \Var \\
  11407. \Exp &::=& (\Var\;\Exp \ldots)\\
  11408. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11409. \end{array}
  11410. }
  11411. \newcommand{\LstructASTRacket}{
  11412. \begin{array}{lcl}
  11413. \Type &::=& \VAR{\Var} \\
  11414. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11415. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11416. \end{array}
  11417. }
  11418. \begin{figure}[tbp]
  11419. \centering
  11420. \fbox{
  11421. \begin{minipage}{0.96\textwidth}
  11422. \[
  11423. \begin{array}{l}
  11424. \gray{\LintGrammarRacket{}} \\ \hline
  11425. \gray{\LvarGrammarRacket{}} \\ \hline
  11426. \gray{\LifGrammarRacket{}} \\ \hline
  11427. \gray{\LwhileGrammarRacket} \\ \hline
  11428. \gray{\LtupGrammarRacket} \\ \hline
  11429. \LstructGrammarRacket \\
  11430. \begin{array}{lcl}
  11431. \LangStruct{} &::=& \Def \ldots \; \Exp
  11432. \end{array}
  11433. \end{array}
  11434. \]
  11435. \end{minipage}
  11436. }
  11437. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11438. (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11439. \label{fig:Lstruct-concrete-syntax}
  11440. \end{figure}
  11441. \begin{figure}[tbp]
  11442. \centering
  11443. \fbox{
  11444. \begin{minipage}{0.96\textwidth}
  11445. \[
  11446. \begin{array}{l}
  11447. \gray{\LintASTRacket{}} \\ \hline
  11448. \gray{\LvarASTRacket{}} \\ \hline
  11449. \gray{\LifASTRacket{}} \\ \hline
  11450. \gray{\LwhileASTRacket} \\ \hline
  11451. \gray{\LtupASTRacket} \\ \hline
  11452. \LstructASTRacket \\
  11453. \begin{array}{lcl}
  11454. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11455. \end{array}
  11456. \end{array}
  11457. \]
  11458. \end{minipage}
  11459. }
  11460. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11461. (Figure~\ref{fig:Lvec-syntax}).}
  11462. \label{fig:Lstruct-syntax}
  11463. \end{figure}
  11464. An instance of a structure is created using function call syntax, with
  11465. the name of the structure in the function position:
  11466. \begin{lstlisting}
  11467. (point 7 12)
  11468. \end{lstlisting}
  11469. Function-call syntax is also used to read the value in a field of a
  11470. structure. The function name is formed by the structure name, a dash,
  11471. and the field name. The following example uses \code{point-x} and
  11472. \code{point-y} to access the \code{x} and \code{y} fields of two point
  11473. instances.
  11474. \begin{center}
  11475. \begin{lstlisting}
  11476. (let ([pt1 (point 7 12)])
  11477. (let ([pt2 (point 4 3)])
  11478. (+ (- (point-x pt1) (point-x pt2))
  11479. (- (point-y pt1) (point-y pt2)))))
  11480. \end{lstlisting}
  11481. \end{center}
  11482. Similarly, to write to a field of a structure, use its set function,
  11483. whose name starts with \code{set-}, followed by the structure name,
  11484. then a dash, then the field name, and concluded with an exclamation
  11485. mark. The following example uses \code{set-point-x!} to change the
  11486. \code{x} field from \code{7} to \code{42}.
  11487. \begin{center}
  11488. \begin{lstlisting}
  11489. (let ([pt (point 7 12)])
  11490. (let ([_ (set-point-x! pt 42)])
  11491. (point-x pt)))
  11492. \end{lstlisting}
  11493. \end{center}
  11494. \begin{exercise}\normalfont
  11495. Create a type checker for \LangStruct{} by extending the type
  11496. checker for \LangVec{}. Extend your compiler with support for simple
  11497. structures, compiling \LangStruct{} to x86 assembly code. Create
  11498. five new test cases that use structures and test your compiler.
  11499. \end{exercise}
  11500. % TODO: create an interpreter for L_struct
  11501. \clearpage
  11502. \section{Challenge: Arrays}
  11503. \label{sec:arrays}
  11504. In Chapter~\ref{ch:Lvec} we studied tuples, that is, sequences of
  11505. elements whose length is determined at compile-time and where each
  11506. element of a tuple may have a different type (they are
  11507. heterogeous). This challenge is also about sequences, but this time
  11508. the length is determined at run-time and all the elements have the same
  11509. type (they are homogeneous). We use the term ``array'' for this later
  11510. kind of sequence.
  11511. The Racket language does not distinguish between tuples and arrays,
  11512. they are both represented by vectors. However, Typed Racket
  11513. distinguishes between tuples and arrays: the \code{Vector} type is for
  11514. tuples and the \code{Vectorof} type is for arrays.
  11515. %
  11516. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11517. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  11518. and the \code{make-vector} primitive operator for creating an array,
  11519. whose arguments are the length of the array and an initial value for
  11520. all the elements in the array. The \code{vector-length},
  11521. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11522. for tuples become overloaded for use with arrays.
  11523. %
  11524. We also include integer multiplication in \LangArray{}, as it is
  11525. useful in many examples involving arrays such as computing the
  11526. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  11527. \begin{figure}[tp]
  11528. \centering
  11529. \fbox{
  11530. \begin{minipage}{0.96\textwidth}
  11531. \small
  11532. \[
  11533. \begin{array}{lcl}
  11534. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  11535. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11536. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  11537. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11538. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11539. \MID \LP\key{and}\;\Exp\;\Exp\RP
  11540. \MID \LP\key{or}\;\Exp\;\Exp\RP
  11541. \MID \LP\key{not}\;\Exp\RP } \\
  11542. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11543. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  11544. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  11545. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  11546. \MID \LP\Exp \; \Exp\ldots\RP } \\
  11547. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11548. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11549. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  11550. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11551. \MID \CWHILE{\Exp}{\Exp} } \\
  11552. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  11553. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11554. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  11555. \end{array}
  11556. \]
  11557. \end{minipage}
  11558. }
  11559. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  11560. \label{fig:Lvecof-concrete-syntax}
  11561. \end{figure}
  11562. \begin{figure}[tp]
  11563. \begin{lstlisting}
  11564. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11565. [n : Integer]) : Integer
  11566. (let ([i 0])
  11567. (let ([prod 0])
  11568. (begin
  11569. (while (< i n)
  11570. (begin
  11571. (set! prod (+ prod (* (vector-ref A i)
  11572. (vector-ref B i))))
  11573. (set! i (+ i 1))
  11574. ))
  11575. prod))))
  11576. (let ([A (make-vector 2 2)])
  11577. (let ([B (make-vector 2 3)])
  11578. (+ (inner-product A B 2)
  11579. 30)))
  11580. \end{lstlisting}
  11581. \caption{Example program that computes the inner-product.}
  11582. \label{fig:inner-product}
  11583. \end{figure}
  11584. The type checker for \LangArray{} is define in
  11585. Figure~\ref{fig:type-check-Lvecof}. The result type of
  11586. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11587. of the intializing expression. The length expression is required to
  11588. have type \code{Integer}. The type checking of the operators
  11589. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11590. updated to handle the situation where the vector has type
  11591. \code{Vectorof}. In these cases we translate the operators to their
  11592. \code{vectorof} form so that later passes can easily distinguish
  11593. between operations on tuples versus arrays. We override the
  11594. \code{operator-types} method to provide the type signature for
  11595. multiplication: it takes two integers and returns an integer. To
  11596. support injection and projection of arrays to the \code{Any} type
  11597. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  11598. predicate.
  11599. \begin{figure}[tbp]
  11600. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11601. (define type-check-Lvecof_class
  11602. (class type-check-Rwhile_class
  11603. (super-new)
  11604. (inherit check-type-equal?)
  11605. (define/override (flat-ty? ty)
  11606. (match ty
  11607. ['(Vectorof Any) #t]
  11608. [else (super flat-ty? ty)]))
  11609. (define/override (operator-types)
  11610. (append '((* . ((Integer Integer) . Integer)))
  11611. (super operator-types)))
  11612. (define/override (type-check-exp env)
  11613. (lambda (e)
  11614. (define recur (type-check-exp env))
  11615. (match e
  11616. [(Prim 'make-vector (list e1 e2))
  11617. (define-values (e1^ t1) (recur e1))
  11618. (define-values (e2^ elt-type) (recur e2))
  11619. (define vec-type `(Vectorof ,elt-type))
  11620. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  11621. vec-type)]
  11622. [(Prim 'vector-ref (list e1 e2))
  11623. (define-values (e1^ t1) (recur e1))
  11624. (define-values (e2^ t2) (recur e2))
  11625. (match* (t1 t2)
  11626. [(`(Vectorof ,elt-type) 'Integer)
  11627. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  11628. [(other wise) ((super type-check-exp env) e)])]
  11629. [(Prim 'vector-set! (list e1 e2 e3) )
  11630. (define-values (e-vec t-vec) (recur e1))
  11631. (define-values (e2^ t2) (recur e2))
  11632. (define-values (e-arg^ t-arg) (recur e3))
  11633. (match t-vec
  11634. [`(Vectorof ,elt-type)
  11635. (check-type-equal? elt-type t-arg e)
  11636. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  11637. [else ((super type-check-exp env) e)])]
  11638. [(Prim 'vector-length (list e1))
  11639. (define-values (e1^ t1) (recur e1))
  11640. (match t1
  11641. [`(Vectorof ,t)
  11642. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  11643. [else ((super type-check-exp env) e)])]
  11644. [else ((super type-check-exp env) e)])))
  11645. ))
  11646. (define (type-check-Lvecof p)
  11647. (send (new type-check-Lvecof_class) type-check-program p))
  11648. \end{lstlisting}
  11649. \caption{Type checker for the \LangArray{} language.}
  11650. \label{fig:type-check-Lvecof}
  11651. \end{figure}
  11652. The interpreter for \LangArray{} is defined in
  11653. Figure~\ref{fig:interp-Lvecof}. The \code{make-vector} operator is
  11654. implemented with Racket's \code{make-vector} function and
  11655. multiplication is \code{fx*}, multiplication for \code{fixnum}
  11656. integers.
  11657. \begin{figure}[tbp]
  11658. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11659. (define interp-Lvecof_class
  11660. (class interp-Rwhile_class
  11661. (super-new)
  11662. (define/override (interp-op op)
  11663. (verbose "Lvecof/interp-op" op)
  11664. (match op
  11665. ['make-vector make-vector]
  11666. ['* fx*]
  11667. [else (super interp-op op)]))
  11668. ))
  11669. (define (interp-Lvecof p)
  11670. (send (new interp-Lvecof_class) interp-program p))
  11671. \end{lstlisting}
  11672. \caption{Interpreter for \LangArray{}.}
  11673. \label{fig:interp-Lvecof}
  11674. \end{figure}
  11675. \subsection{Data Representation}
  11676. \label{sec:array-rep}
  11677. Just like tuples, we store arrays on the heap which means that the
  11678. garbage collector will need to inspect arrays. An immediate thought is
  11679. to use the same representation for arrays that we use for tuples.
  11680. However, we limit tuples to a length of $50$ so that their length and
  11681. pointer mask can fit into the 64-bit tag at the beginning of each
  11682. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  11683. millions of elements, so we need more bits to store the length.
  11684. However, because arrays are homogeneous, we only need $1$ bit for the
  11685. pointer mask instead of one bit per array elements. Finally, the
  11686. garbage collector will need to be able to distinguish between tuples
  11687. and arrays, so we need to reserve $1$ bit for that purpose. So we
  11688. arrive at the following layout for the 64-bit tag at the beginning of
  11689. an array:
  11690. \begin{itemize}
  11691. \item The right-most bit is the forwarding bit, just like in a tuple.
  11692. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  11693. it is not.
  11694. \item The next bit to the left is the pointer mask. A $0$ indicates
  11695. that none of the elements are pointers to the heap and a $1$
  11696. indicates that all of the elements are pointers.
  11697. \item The next $61$ bits store the length of the array.
  11698. \item The left-most bit distinguishes between a tuple ($0$) versus an
  11699. array ($1$).
  11700. \end{itemize}
  11701. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  11702. differentiate the kinds of values that have been injected into the
  11703. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  11704. to indicate that the value is an array.
  11705. In the following subsections we provide hints regarding how to update
  11706. the passes to handle arrays.
  11707. \subsection{Reveal Casts}
  11708. The array-access operators \code{vectorof-ref} and
  11709. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  11710. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  11711. that the type checker cannot tell whether the index will be in bounds,
  11712. so the bounds check must be performed at run time. Recall that the
  11713. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  11714. an \code{If} arround a vector reference for update to check whether
  11715. the index is less than the length. You should do the same for
  11716. \code{vectorof-ref} and \code{vectorof-set!} .
  11717. In addition, the handling of the \code{any-vector} operators in
  11718. \code{reveal-casts} needs to be updated to account for arrays that are
  11719. injected to \code{Any}. For the \code{any-vector-length} operator, the
  11720. generated code should test whether the tag is for tuples (\code{010})
  11721. or arrays (\code{110}) and then dispatch to either
  11722. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  11723. we add a case in \code{select\_instructions} to generate the
  11724. appropriate instructions for accessing the array length from the
  11725. header of an array.
  11726. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  11727. the generated code needs to check that the index is less than the
  11728. vector length, so like the code for \code{any-vector-length}, check
  11729. the tag to determine whether to use \code{any-vector-length} or
  11730. \code{any-vectorof-length} for this purpose. Once the bounds checking
  11731. is complete, the generated code can use \code{any-vector-ref} and
  11732. \code{any-vector-set!} for both tuples and arrays because the
  11733. instructions used for those operators do not look at the tag at the
  11734. front of the tuple or array.
  11735. \subsection{Expose Allocation}
  11736. This pass should translate the \code{make-vector} operator into
  11737. lower-level operations. In particular, the new AST node
  11738. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  11739. length specified by the $\Exp$, but does not initialize the elements
  11740. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  11741. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  11742. element type for the array. Regarding the initialization of the array,
  11743. we recommend generated a \code{while} loop that uses
  11744. \code{vector-set!} to put the initializing value into every element of
  11745. the array.
  11746. \subsection{Remove Complex Operands}
  11747. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  11748. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  11749. complex and its subexpression must be atomic.
  11750. \subsection{Explicate Control}
  11751. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  11752. \code{explicate\_assign}.
  11753. \subsection{Select Instructions}
  11754. Generate instructions for \code{AllocateArray} similar to those for
  11755. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  11756. that the tag at the front of the array should instead use the
  11757. representation discussed in Section~\ref{sec:array-rep}.
  11758. Regarding \code{vectorof-length}, extract the length from the tag
  11759. according to the representation discussed in
  11760. Section~\ref{sec:array-rep}.
  11761. The instructions generated for \code{vectorof-ref} differ from those
  11762. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  11763. that the index is not a constant so the offset must be computed at
  11764. runtime, similar to the instructions generated for
  11765. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  11766. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  11767. appear in an assignment and as a stand-alone statement, so make sure
  11768. to handle both situations in this pass.
  11769. Finally, the instructions for \code{any-vectorof-length} should be
  11770. similar to those for \code{vectorof-length}, except that one must
  11771. first project the array by writing zeroes into the $3$-bit tag
  11772. \begin{exercise}\normalfont
  11773. Implement a compiler for the \LangArray{} language by extending your
  11774. compiler for \LangLoop{}. Test your compiler on a half dozen new
  11775. programs, including the one in Figure~\ref{fig:inner-product} and also
  11776. a program that multiplies two matrices. Note that matrices are
  11777. 2-dimensional arrays, but those can be encoded into 1-dimensional
  11778. arrays by laying out each row in the array, one after the next.
  11779. \end{exercise}
  11780. \section{Challenge: Generational Collection}
  11781. The copying collector described in Section~\ref{sec:GC} can incur
  11782. significant runtime overhead because the call to \code{collect} takes
  11783. time proportional to all of the live data. One way to reduce this
  11784. overhead is to reduce how much data is inspected in each call to
  11785. \code{collect}. In particular, researchers have observed that recently
  11786. allocated data is more likely to become garbage then data that has
  11787. survived one or more previous calls to \code{collect}. This insight
  11788. motivated the creation of \emph{generational garbage collectors}
  11789. \index{subject}{generational garbage collector} that
  11790. 1) segregates data according to its age into two or more generations,
  11791. 2) allocates less space for younger generations, so collecting them is
  11792. faster, and more space for the older generations, and 3) performs
  11793. collection on the younger generations more frequently then for older
  11794. generations~\citep{Wilson:1992fk}.
  11795. For this challenge assignment, the goal is to adapt the copying
  11796. collector implemented in \code{runtime.c} to use two generations, one
  11797. for young data and one for old data. Each generation consists of a
  11798. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  11799. \code{collect} function to use the two generations.
  11800. \begin{enumerate}
  11801. \item Copy the young generation's FromSpace to its ToSpace then switch
  11802. the role of the ToSpace and FromSpace
  11803. \item If there is enough space for the requested number of bytes in
  11804. the young FromSpace, then return from \code{collect}.
  11805. \item If there is not enough space in the young FromSpace for the
  11806. requested bytes, then move the data from the young generation to the
  11807. old one with the following steps:
  11808. \begin{enumerate}
  11809. \item If there is enough room in the old FromSpace, copy the young
  11810. FromSpace to the old FromSpace and then return.
  11811. \item If there is not enough room in the old FromSpace, then collect
  11812. the old generation by copying the old FromSpace to the old ToSpace
  11813. and swap the roles of the old FromSpace and ToSpace.
  11814. \item If there is enough room now, copy the young FromSpace to the
  11815. old FromSpace and return. Otherwise, allocate a larger FromSpace
  11816. and ToSpace for the old generation. Copy the young FromSpace and
  11817. the old FromSpace into the larger FromSpace for the old
  11818. generation and then return.
  11819. \end{enumerate}
  11820. \end{enumerate}
  11821. We recommend that you generalize the \code{cheney} function so that it
  11822. can be used for all the copies mentioned above: between the young
  11823. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  11824. between the young FromSpace and old FromSpace. This can be
  11825. accomplished by adding parameters to \code{cheney} that replace its
  11826. use of the global variables \code{fromspace\_begin},
  11827. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  11828. Note that the collection of the young generation does not traverse the
  11829. old generation. This introduces a potential problem: there may be
  11830. young data that is only reachable through pointers in the old
  11831. generation. If these pointers are not taken into account, the
  11832. collector could throw away young data that is live! One solution,
  11833. called \emph{pointer recording}, is to maintain a set of all the
  11834. pointers from the old generation into the new generation and consider
  11835. this set as part of the root set. To maintain this set, the compiler
  11836. must insert extra instructions around every \code{vector-set!}. If the
  11837. vector being modified is in the old generation, and if the value being
  11838. written is a pointer into the new generation, than that pointer must
  11839. be added to the set. Also, if the value being overwritten was a
  11840. pointer into the new generation, then that pointer should be removed
  11841. from the set.
  11842. \begin{exercise}\normalfont
  11843. Adapt the \code{collect} function in \code{runtime.c} to implement
  11844. generational garbage collection, as outlined in this section.
  11845. Update the code generation for \code{vector-set!} to implement
  11846. pointer recording. Make sure that your new compiler and runtime
  11847. passes your test suite.
  11848. \end{exercise}
  11849. \fi}
  11850. % Further Reading
  11851. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11852. \chapter{Functions}
  11853. \label{ch:Rfun}
  11854. \index{subject}{function}
  11855. This chapter studies the compilation of functions similar to those
  11856. found in the C language. This corresponds to a subset of \racket{Typed
  11857. Racket} \python{Python} in which only top-level function definitions
  11858. are allowed. This kind of function is an important stepping stone to
  11859. implementing lexically-scoped functions in the form of \key{lambda}
  11860. abstractions, which is the topic of Chapter~\ref{ch:Rlam}.
  11861. \section{The \LangFun{} Language}
  11862. The concrete and abstract syntax for function definitions and function
  11863. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  11864. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  11865. \LangFun{} begin with zero or more function definitions. The function
  11866. names from these definitions are in-scope for the entire program,
  11867. including all other function definitions (so the ordering of function
  11868. definitions does not matter).
  11869. %
  11870. \python{The abstract syntax for function parameters in
  11871. Figure~\ref{fig:Rfun-syntax} is a list of pairs, where each pair
  11872. consists of a parameter name and its type. This differs from
  11873. Python's \code{ast} module, which has a more complex syntax for
  11874. function parameters, for example, to handle keyword parameters and
  11875. defaults. The type checker in \code{type\_check\_Lfun} converts the
  11876. more commplex syntax into the simpler syntax of
  11877. Figure~\ref{fig:Rfun-syntax}.}
  11878. %
  11879. The concrete syntax for function application\index{subject}{function
  11880. application} is $\CAPPLY{\Exp}{\Exp \ldots}$ where the first expression
  11881. must evaluate to a function and the rest are the arguments. The
  11882. abstract syntax for function application is
  11883. $\APPLY{\Exp}{\Exp\ldots}$.
  11884. %% The syntax for function application does not include an explicit
  11885. %% keyword, which is error prone when using \code{match}. To alleviate
  11886. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  11887. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  11888. Functions are first-class in the sense that a function pointer
  11889. \index{subject}{function pointer} is data and can be stored in memory or passed
  11890. as a parameter to another function. Thus, there is a function
  11891. type, written
  11892. {\if\edition\racketEd
  11893. \begin{lstlisting}
  11894. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  11895. \end{lstlisting}
  11896. \fi}
  11897. {\if\edition\pythonEd
  11898. \begin{lstlisting}
  11899. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_r$|]
  11900. \end{lstlisting}
  11901. \fi}
  11902. %
  11903. \noindent for a function whose $n$ parameters have the types $\Type_1$
  11904. through $\Type_n$ and whose return type is $\Type_r$. The main
  11905. limitation of these functions (with respect to
  11906. \racket{Racket}\python{Python} functions) is that they are not
  11907. lexically scoped. That is, the only external entities that can be
  11908. referenced from inside a function body are other globally-defined
  11909. functions. The syntax of \LangFun{} prevents functions from being
  11910. nested inside each other.
  11911. \newcommand{\LfunGrammarRacket}{
  11912. \begin{array}{lcl}
  11913. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  11914. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  11915. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  11916. \end{array}
  11917. }
  11918. \newcommand{\LfunASTRacket}{
  11919. \begin{array}{lcl}
  11920. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  11921. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  11922. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  11923. \end{array}
  11924. }
  11925. \newcommand{\LfunGrammarPython}{
  11926. \begin{array}{lcl}
  11927. \Type &::=& \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  11928. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  11929. \Stmt &::=& \CRETURN{\Exp} \\
  11930. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  11931. \end{array}
  11932. }
  11933. \newcommand{\LfunASTPython}{
  11934. \begin{array}{lcl}
  11935. \Type &::=& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  11936. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  11937. \Stmt &::=& \RETURN{\Exp} \\
  11938. \Def &::=& \FUNDEF{\Var}{\LS \LP \Var \key{, } \Type \RP \key{, } \ldots \RS}{\Type}{}{\Stmt^{+}}
  11939. \end{array}
  11940. }
  11941. \begin{figure}[tp]
  11942. \centering
  11943. \fbox{
  11944. \begin{minipage}{0.96\textwidth}
  11945. \small
  11946. {\if\edition\racketEd
  11947. \[
  11948. \begin{array}{l}
  11949. \gray{\LintGrammarRacket{}} \\ \hline
  11950. \gray{\LvarGrammarRacket{}} \\ \hline
  11951. \gray{\LifGrammarRacket{}} \\ \hline
  11952. \gray{\LwhileGrammarRacket} \\ \hline
  11953. \gray{\LtupGrammarRacket} \\ \hline
  11954. \LfunGrammarRacket \\
  11955. \begin{array}{lcl}
  11956. \LangFunM{} &::=& \Def \ldots \; \Exp
  11957. \end{array}
  11958. \end{array}
  11959. \]
  11960. \fi}
  11961. {\if\edition\pythonEd
  11962. \[
  11963. \begin{array}{l}
  11964. \gray{\LintGrammarPython{}} \\ \hline
  11965. \gray{\LvarGrammarPython{}} \\ \hline
  11966. \gray{\LifGrammarPython{}} \\ \hline
  11967. \gray{\LwhileGrammarPython} \\ \hline
  11968. \gray{\LtupGrammarPython} \\ \hline
  11969. \LfunGrammarPython \\
  11970. \begin{array}{rcl}
  11971. \LangFunM{} &::=& \Def^{*} \Stmt^{*}
  11972. \end{array}
  11973. \end{array}
  11974. \]
  11975. \fi}
  11976. \end{minipage}
  11977. }
  11978. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11979. \label{fig:Rfun-concrete-syntax}
  11980. \end{figure}
  11981. \begin{figure}[tp]
  11982. \centering
  11983. \fbox{
  11984. \begin{minipage}{0.96\textwidth}
  11985. \small
  11986. {\if\edition\racketEd
  11987. \[
  11988. \begin{array}{l}
  11989. \gray{\LintOpAST} \\ \hline
  11990. \gray{\LvarASTRacket{}} \\ \hline
  11991. \gray{\LifASTRacket{}} \\ \hline
  11992. \gray{\LwhileASTRacket{}} \\ \hline
  11993. \gray{\LtupASTRacket{}} \\ \hline
  11994. \LfunASTRacket \\
  11995. \begin{array}{lcl}
  11996. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11997. \end{array}
  11998. \end{array}
  11999. \]
  12000. \fi}
  12001. {\if\edition\pythonEd
  12002. \[
  12003. \begin{array}{l}
  12004. \gray{\LintASTPython{}} \\ \hline
  12005. \gray{\LvarASTPython{}} \\ \hline
  12006. \gray{\LifASTPython{}} \\ \hline
  12007. \gray{\LwhileASTPython} \\ \hline
  12008. \gray{\LtupASTPython} \\ \hline
  12009. \LfunASTPython \\
  12010. \begin{array}{rcl}
  12011. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  12012. \end{array}
  12013. \end{array}
  12014. \]
  12015. \fi}
  12016. \end{minipage}
  12017. }
  12018. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  12019. \label{fig:Rfun-syntax}
  12020. \end{figure}
  12021. The program in Figure~\ref{fig:Rfun-function-example} is a
  12022. representative example of defining and using functions in \LangFun{}.
  12023. We define a function \code{map} that applies some other function
  12024. \code{f} to both elements of a vector and returns a new vector
  12025. containing the results. We also define a function \code{inc}. The
  12026. program applies \code{map} to \code{inc} and
  12027. %
  12028. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  12029. %
  12030. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  12031. %
  12032. from which we return the \code{42}.
  12033. \begin{figure}[tbp]
  12034. {\if\edition\racketEd
  12035. \begin{lstlisting}
  12036. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12037. : (Vector Integer Integer)
  12038. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12039. (define (inc [x : Integer]) : Integer
  12040. (+ x 1))
  12041. (vector-ref (map inc (vector 0 41)) 1)
  12042. \end{lstlisting}
  12043. \fi}
  12044. {\if\edition\pythonEd
  12045. \begin{lstlisting}
  12046. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12047. return f(v[0]), f(v[1])
  12048. def inc(x : int) -> int:
  12049. return x + 1
  12050. print( map(inc, (0, 41))[1] )
  12051. \end{lstlisting}
  12052. \fi}
  12053. \caption{Example of using functions in \LangFun{}.}
  12054. \label{fig:Rfun-function-example}
  12055. \end{figure}
  12056. The definitional interpreter for \LangFun{} is in
  12057. Figure~\ref{fig:interp-Rfun}. The case for the
  12058. %
  12059. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12060. %
  12061. AST is responsible for setting up the mutual recursion between the
  12062. top-level function definitions.
  12063. %
  12064. \racket{We use the classic back-patching
  12065. \index{subject}{back-patching} approach that uses mutable variables
  12066. and makes two passes over the function
  12067. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12068. top-level environment using a mutable cons cell for each function
  12069. definition. Note that the \code{lambda} value for each function is
  12070. incomplete; it does not yet include the environment. Once the
  12071. top-level environment is constructed, we then iterate over it and
  12072. update the \code{lambda} values to use the top-level environment.}
  12073. %
  12074. \python{We create a dictionary named \code{env} and fill it in
  12075. by mapping each function name to a new \code{Function} value,
  12076. each of which stores a reference to the \code{env}.
  12077. (We define the class \code{Function} for this purpose.)}
  12078. %
  12079. To interpret a function \racket{application}\python{call}, we match
  12080. the result of the function expression to obtain a function value. We
  12081. then extend the function's environment with mapping of parameters to
  12082. argument values. Finally, we interpret the body of the function in
  12083. this extended environment.
  12084. \begin{figure}[tp]
  12085. {\if\edition\racketEd
  12086. \begin{lstlisting}
  12087. (define interp-Rfun_class
  12088. (class interp-Lvec_class
  12089. (super-new)
  12090. (define/override ((interp-exp env) e)
  12091. (define recur (interp-exp env))
  12092. (match e
  12093. [(Var x) (unbox (dict-ref env x))]
  12094. [(Let x e body)
  12095. (define new-env (dict-set env x (box (recur e))))
  12096. ((interp-exp new-env) body)]
  12097. [(Apply fun args)
  12098. (define fun-val (recur fun))
  12099. (define arg-vals (for/list ([e args]) (recur e)))
  12100. (match fun-val
  12101. [`(function (,xs ...) ,body ,fun-env)
  12102. (define params-args (for/list ([x xs] [arg arg-vals])
  12103. (cons x (box arg))))
  12104. (define new-env (append params-args fun-env))
  12105. ((interp-exp new-env) body)]
  12106. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12107. [else ((super interp-exp env) e)]
  12108. ))
  12109. (define/public (interp-def d)
  12110. (match d
  12111. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12112. (cons f (box `(function ,xs ,body ())))]))
  12113. (define/override (interp-program p)
  12114. (match p
  12115. [(ProgramDefsExp info ds body)
  12116. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12117. (for/list ([f (in-dict-values top-level)])
  12118. (set-box! f (match (unbox f)
  12119. [`(function ,xs ,body ())
  12120. `(function ,xs ,body ,top-level)])))
  12121. ((interp-exp top-level) body))]))
  12122. ))
  12123. (define (interp-Rfun p)
  12124. (send (new interp-Rfun_class) interp-program p))
  12125. \end{lstlisting}
  12126. \fi}
  12127. {\if\edition\pythonEd
  12128. \begin{lstlisting}
  12129. class InterpLfun(InterpLtup):
  12130. def apply_fun(self, fun, args, e):
  12131. match fun:
  12132. case Function(name, xs, body, env):
  12133. new_env = {x: v for (x,v) in env.items()}
  12134. for (x,arg) in zip(xs, args):
  12135. new_env[x] = arg
  12136. return self.interp_stmts(body, new_env)
  12137. case _:
  12138. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12139. def interp_exp(self, e, env):
  12140. match e:
  12141. case Call(Name('input_int'), []):
  12142. return super().interp_exp(e, env)
  12143. case Call(func, args):
  12144. f = self.interp_exp(func, env)
  12145. vs = [self.interp_exp(arg, env) for arg in args]
  12146. return self.apply_fun(f, vs, e)
  12147. case _:
  12148. return super().interp_exp(e, env)
  12149. def interp_stmts(self, ss, env):
  12150. if len(ss) == 0:
  12151. return
  12152. match ss[0]:
  12153. case Return(value):
  12154. return self.interp_exp(value, env)
  12155. case _:
  12156. return super().interp_stmts(ss, env)
  12157. def interp(self, p):
  12158. match p:
  12159. case Module(defs):
  12160. env = {}
  12161. for d in defs:
  12162. match d:
  12163. case FunctionDef(name, params, bod, dl, returns, comment):
  12164. env[name] = Function(name, [x for (x,t) in params], bod, env)
  12165. self.apply_fun(env['main'], [], None)
  12166. case _:
  12167. raise Exception('interp: unexpected ' + repr(p))
  12168. \end{lstlisting}
  12169. \fi}
  12170. \caption{Interpreter for the \LangFun{} language.}
  12171. \label{fig:interp-Rfun}
  12172. \end{figure}
  12173. %\margincomment{TODO: explain type checker}
  12174. The type checker for \LangFun{} is in
  12175. Figure~\ref{fig:type-check-Rfun}. (We omit the code that parses
  12176. function parameters into the simpler abstract syntax.) Similar to the
  12177. interpreter, the case for the
  12178. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12179. %
  12180. AST is responsible for setting up the mutual recursion between the
  12181. top-level function definitions. We begin by create a mapping
  12182. \code{env} from every function name to its type. We then type check
  12183. the program using this \code{env}.
  12184. %
  12185. In the case for function \racket{application}\python{call}, we match
  12186. the type of the function expression to a function type and check that
  12187. the types of the argument expressions are equal to the function's
  12188. parameter types. The type of the \racket{application}\python{call} as
  12189. a whole is the return type from the function type.
  12190. \begin{figure}[tp]
  12191. {\if\edition\racketEd
  12192. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12193. (define type-check-Rfun_class
  12194. (class type-check-Lvec_class
  12195. (super-new)
  12196. (inherit check-type-equal?)
  12197. (define/public (type-check-apply env e es)
  12198. (define-values (e^ ty) ((type-check-exp env) e))
  12199. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  12200. ((type-check-exp env) e)))
  12201. (match ty
  12202. [`(,ty^* ... -> ,rt)
  12203. (for ([arg-ty ty*] [param-ty ty^*])
  12204. (check-type-equal? arg-ty param-ty (Apply e es)))
  12205. (values e^ e* rt)]))
  12206. (define/override (type-check-exp env)
  12207. (lambda (e)
  12208. (match e
  12209. [(FunRef f)
  12210. (values (FunRef f) (dict-ref env f))]
  12211. [(Apply e es)
  12212. (define-values (e^ es^ rt) (type-check-apply env e es))
  12213. (values (Apply e^ es^) rt)]
  12214. [(Call e es)
  12215. (define-values (e^ es^ rt) (type-check-apply env e es))
  12216. (values (Call e^ es^) rt)]
  12217. [else ((super type-check-exp env) e)])))
  12218. (define/public (type-check-def env)
  12219. (lambda (e)
  12220. (match e
  12221. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  12222. (define new-env (append (map cons xs ps) env))
  12223. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12224. (check-type-equal? ty^ rt body)
  12225. (Def f p:t* rt info body^)])))
  12226. (define/public (fun-def-type d)
  12227. (match d
  12228. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  12229. (define/override (type-check-program e)
  12230. (match e
  12231. [(ProgramDefsExp info ds body)
  12232. (define env (for/list ([d ds])
  12233. (cons (Def-name d) (fun-def-type d))))
  12234. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  12235. (define-values (body^ ty) ((type-check-exp env) body))
  12236. (check-type-equal? ty 'Integer body)
  12237. (ProgramDefsExp info ds^ body^)]))))
  12238. (define (type-check-Rfun p)
  12239. (send (new type-check-Rfun_class) type-check-program p))
  12240. \end{lstlisting}
  12241. \fi}
  12242. {\if\edition\pythonEd
  12243. \begin{lstlisting}
  12244. class TypeCheckLfun(TypeCheckLtup):
  12245. def type_check_exp(self, e, env):
  12246. match e:
  12247. case Call(Name('input_int'), []):
  12248. return super().type_check_exp(e, env)
  12249. case Call(func, args):
  12250. func_t = self.type_check_exp(func, env)
  12251. args_t = [self.type_check_exp(arg, env) for arg in args]
  12252. match func_t:
  12253. case FunctionType(params_t, return_t):
  12254. for (arg_t, param_t) in zip(args_t, params_t):
  12255. check_type_equal(param_t, arg_t, e)
  12256. return return_t
  12257. case _:
  12258. raise Exception('type_check_exp: in call, unexpected ' + \
  12259. repr(func_t))
  12260. case _:
  12261. return super().type_check_exp(e, env)
  12262. def type_check_stmts(self, ss, env):
  12263. if len(ss) == 0:
  12264. return
  12265. match ss[0]:
  12266. case FunctionDef(name, params, body, dl, returns, comment):
  12267. new_env = {x: t for (x,t) in env.items()}
  12268. for (x,t) in params:
  12269. new_env[x] = t
  12270. rt = self.type_check_stmts(body, new_env)
  12271. check_type_equal(returns, rt, ss[0])
  12272. return self.type_check_stmts(ss[1:], env)
  12273. case Return(value):
  12274. return self.type_check_exp(value, env)
  12275. case _:
  12276. return super().type_check_stmts(ss, env)
  12277. def type_check(self, p):
  12278. match p:
  12279. case Module(body):
  12280. env = {}
  12281. for s in body:
  12282. match s:
  12283. case FunctionDef(name, params, bod, dl, returns, comment):
  12284. params_t = [t for (x,t) in params]
  12285. env[name] = FunctionType(params_t, returns)
  12286. self.type_check_stmts(body, env)
  12287. case _:
  12288. raise Exception('type_check: unexpected ' + repr(p))
  12289. \end{lstlisting}
  12290. \fi}
  12291. \caption{Type checker for the \LangFun{} language.}
  12292. \label{fig:type-check-Rfun}
  12293. \end{figure}
  12294. \section{Functions in x86}
  12295. \label{sec:fun-x86}
  12296. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  12297. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  12298. %% \margincomment{\tiny Talk about the return address on the
  12299. %% stack and what callq and retq does.\\ --Jeremy }
  12300. The x86 architecture provides a few features to support the
  12301. implementation of functions. We have already seen that x86 provides
  12302. labels so that one can refer to the location of an instruction, as is
  12303. needed for jump instructions. Labels can also be used to mark the
  12304. beginning of the instructions for a function. Going further, we can
  12305. obtain the address of a label by using the \key{leaq} instruction and
  12306. PC-relative addressing. For example, the following puts the
  12307. address of the \code{inc} label into the \code{rbx} register.
  12308. \begin{lstlisting}
  12309. leaq inc(%rip), %rbx
  12310. \end{lstlisting}
  12311. The instruction pointer register \key{rip} (aka. the program counter
  12312. \index{subject}{program counter}) always points to the next
  12313. instruction to be executed. When combined with an label, as in
  12314. \code{inc(\%rip)}, the assembler computes the distance $d$ between the
  12315. address of \code{inc} and where the \code{rip} would be at that moment
  12316. and then changes the \code{inc(\%rip)} argument to \code{$d$(\%rip)},
  12317. which at runtime will compute the address of \code{inc}.
  12318. In Section~\ref{sec:x86} we used the \code{callq} instruction to jump
  12319. to functions whose locations were given by a label, such as
  12320. \code{read\_int}. To support function calls in this chapter we instead
  12321. will be jumping to functions whose location are given by an address in
  12322. a register, that is, we need to make an \emph{indirect function
  12323. call}. The x86 syntax for this is a \code{callq} instruction but with
  12324. an asterisk before the register name.\index{subject}{indirect function
  12325. call}
  12326. \begin{lstlisting}
  12327. callq *%rbx
  12328. \end{lstlisting}
  12329. \subsection{Calling Conventions}
  12330. \index{subject}{calling conventions}
  12331. The \code{callq} instruction provides partial support for implementing
  12332. functions: it pushes the return address on the stack and it jumps to
  12333. the target. However, \code{callq} does not handle
  12334. \begin{enumerate}
  12335. \item parameter passing,
  12336. \item pushing frames on the procedure call stack and popping them off,
  12337. or
  12338. \item determining how registers are shared by different functions.
  12339. \end{enumerate}
  12340. Regarding (1) parameter passing, recall that the following six
  12341. registers are used to pass arguments to a function, in this order.
  12342. \begin{lstlisting}
  12343. rdi rsi rdx rcx r8 r9
  12344. \end{lstlisting}
  12345. If there are
  12346. more than six arguments, then the convention is to use space on the
  12347. frame of the caller for the rest of the arguments. However, to ease
  12348. the implementation of efficient tail calls
  12349. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  12350. arguments.
  12351. %
  12352. Also recall that the register \code{rax} is for the return value of
  12353. the function.
  12354. \index{subject}{prelude}\index{subject}{conclusion}
  12355. Regarding (2) frames \index{subject}{frame} and the procedure call
  12356. stack, \index{subject}{procedure call stack} recall from
  12357. Section~\ref{sec:x86} that the stack grows down and each function call
  12358. uses a chunk of space on the stack called a frame. The caller sets the
  12359. stack pointer, register \code{rsp}, to the last data item in its
  12360. frame. The callee must not change anything in the caller's frame, that
  12361. is, anything that is at or above the stack pointer. The callee is free
  12362. to use locations that are below the stack pointer.
  12363. Recall that we are storing variables of tuple type on the root stack.
  12364. So the prelude needs to move the root stack pointer \code{r15} up and
  12365. the conclusion needs to move the root stack pointer back down. Also,
  12366. the prelude must initialize to \code{0} this frame's slots in the root
  12367. stack to signal to the garbage collector that those slots do not yet
  12368. contain a pointer to a vector. Otherwise the garbage collector will
  12369. interpret the garbage bits in those slots as memory addresses and try
  12370. to traverse them, causing serious mayhem!
  12371. Regarding (3) the sharing of registers between different functions,
  12372. recall from Section~\ref{sec:calling-conventions} that the registers
  12373. are divided into two groups, the caller-saved registers and the
  12374. callee-saved registers. The caller should assume that all the
  12375. caller-saved registers get overwritten with arbitrary values by the
  12376. callee. That is why we recommend in
  12377. Section~\ref{sec:calling-conventions} that variables that are live
  12378. during a function call should not be assigned to caller-saved
  12379. registers.
  12380. On the flip side, if the callee wants to use a callee-saved register,
  12381. the callee must save the contents of those registers on their stack
  12382. frame and then put them back prior to returning to the caller. That
  12383. is why we recommended in Section~\ref{sec:calling-conventions} that if
  12384. the register allocator assigns a variable to a callee-saved register,
  12385. then the prelude of the \code{main} function must save that register
  12386. to the stack and the conclusion of \code{main} must restore it. This
  12387. recommendation now generalizes to all functions.
  12388. Recall that the base pointer, register \code{rbp}, is used as a
  12389. point-of-reference within a frame, so that each local variable can be
  12390. accessed at a fixed offset from the base pointer
  12391. (Section~\ref{sec:x86}).
  12392. %
  12393. Figure~\ref{fig:call-frames} shows the general layout of the caller
  12394. and callee frames.
  12395. \begin{figure}[tbp]
  12396. \centering
  12397. \begin{tabular}{r|r|l|l} \hline
  12398. Caller View & Callee View & Contents & Frame \\ \hline
  12399. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  12400. 0(\key{\%rbp}) & & old \key{rbp} \\
  12401. -8(\key{\%rbp}) & & callee-saved $1$ \\
  12402. \ldots & & \ldots \\
  12403. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  12404. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  12405. \ldots & & \ldots \\
  12406. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  12407. %% & & \\
  12408. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  12409. %% & \ldots & \ldots \\
  12410. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  12411. \hline
  12412. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  12413. & 0(\key{\%rbp}) & old \key{rbp} \\
  12414. & -8(\key{\%rbp}) & callee-saved $1$ \\
  12415. & \ldots & \ldots \\
  12416. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  12417. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  12418. & \ldots & \ldots \\
  12419. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  12420. \end{tabular}
  12421. \caption{Memory layout of caller and callee frames.}
  12422. \label{fig:call-frames}
  12423. \end{figure}
  12424. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  12425. %% local variables and for storing the values of callee-saved registers
  12426. %% (we shall refer to all of these collectively as ``locals''), and that
  12427. %% at the beginning of a function we move the stack pointer \code{rsp}
  12428. %% down to make room for them.
  12429. %% We recommend storing the local variables
  12430. %% first and then the callee-saved registers, so that the local variables
  12431. %% can be accessed using \code{rbp} the same as before the addition of
  12432. %% functions.
  12433. %% To make additional room for passing arguments, we shall
  12434. %% move the stack pointer even further down. We count how many stack
  12435. %% arguments are needed for each function call that occurs inside the
  12436. %% body of the function and find their maximum. Adding this number to the
  12437. %% number of locals gives us how much the \code{rsp} should be moved at
  12438. %% the beginning of the function. In preparation for a function call, we
  12439. %% offset from \code{rsp} to set up the stack arguments. We put the first
  12440. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  12441. %% so on.
  12442. %% Upon calling the function, the stack arguments are retrieved by the
  12443. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  12444. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  12445. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  12446. %% the layout of the caller and callee frames. Notice how important it is
  12447. %% that we correctly compute the maximum number of arguments needed for
  12448. %% function calls; if that number is too small then the arguments and
  12449. %% local variables will smash into each other!
  12450. \subsection{Efficient Tail Calls}
  12451. \label{sec:tail-call}
  12452. In general, the amount of stack space used by a program is determined
  12453. by the longest chain of nested function calls. That is, if function
  12454. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, $f_n$, then the amount
  12455. of stack space is linear in $n$. The depth $n$ can grow quite large
  12456. in the case of recursive or mutually recursive functions. However, in
  12457. some cases we can arrange to use only a constant amount of space for a
  12458. long chain of nested function calls.
  12459. If a function call is the last action in a function body, then that
  12460. call is said to be a \emph{tail call}\index{subject}{tail call}.
  12461. For example, in the following
  12462. program, the recursive call to \code{tail\_sum} is a tail call.
  12463. \begin{center}
  12464. {\if\edition\racketEd
  12465. \begin{lstlisting}
  12466. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  12467. (if (eq? n 0)
  12468. r
  12469. (tail_sum (- n 1) (+ n r))))
  12470. (+ (tail_sum 3 0) 36)
  12471. \end{lstlisting}
  12472. \fi}
  12473. {\if\edition\pythonEd
  12474. \begin{lstlisting}
  12475. def tail_sum(n : int, r : int) -> int:
  12476. if n == 0:
  12477. return r
  12478. else:
  12479. return tail_sum(n - 1, n + r)
  12480. print( tail_sum(3, 0) + 36)
  12481. \end{lstlisting}
  12482. \fi}
  12483. \end{center}
  12484. At a tail call, the frame of the caller is no longer needed, so we can
  12485. pop the caller's frame before making the tail call. With this
  12486. approach, a recursive function that only makes tail calls will only
  12487. use a constant amount of stack space. Functional languages like
  12488. Racket typically rely heavily on recursive functions, so they
  12489. typically guarantee that all tail calls will be optimized in this way.
  12490. \index{subject}{frame}
  12491. Some care is needed with regards to argument passing in tail calls.
  12492. As mentioned above, for arguments beyond the sixth, the convention is
  12493. to use space in the caller's frame for passing arguments. But for a
  12494. tail call we pop the caller's frame and can no longer use it. An
  12495. alternative is to use space in the callee's frame for passing
  12496. arguments. However, this option is also problematic because the caller
  12497. and callee's frames overlap in memory. As we begin to copy the
  12498. arguments from their sources in the caller's frame, the target
  12499. locations in the callee's frame might collide with the sources for
  12500. later arguments! We solve this problem by using the heap instead of
  12501. the stack for passing more than six arguments, which we describe in
  12502. the Section~\ref{sec:limit-functions-r4}.
  12503. As mentioned above, for a tail call we pop the caller's frame prior to
  12504. making the tail call. The instructions for popping a frame are the
  12505. instructions that we usually place in the conclusion of a
  12506. function. Thus, we also need to place such code immediately before
  12507. each tail call. These instructions include restoring the callee-saved
  12508. registers, so it is fortunate that the argument passing registers are
  12509. all caller-saved registers!
  12510. One last note regarding which instruction to use to make the tail
  12511. call. When the callee is finished, it should not return to the current
  12512. function, but it should return to the function that called the current
  12513. one. Thus, the return address that is already on the stack is the
  12514. right one, and we should not use \key{callq} to make the tail call, as
  12515. that would unnecessarily overwrite the return address. Instead we can
  12516. simply use the \key{jmp} instruction. Like the indirect function call,
  12517. we write an \emph{indirect jump}\index{subject}{indirect jump} with a
  12518. register prefixed with an asterisk. We recommend using \code{rax} to
  12519. hold the jump target because the preceding conclusion can overwrite
  12520. just about everything else.
  12521. \begin{lstlisting}
  12522. jmp *%rax
  12523. \end{lstlisting}
  12524. \section{Shrink \LangFun{}}
  12525. \label{sec:shrink-r4}
  12526. The \code{shrink} pass performs a minor modification to ease the
  12527. later passes. This pass introduces an explicit \code{main} function.
  12528. %
  12529. \racket{It also changes the top \code{ProgramDefsExp} form to
  12530. \code{ProgramDefs}.}
  12531. {\if\edition\racketEd
  12532. \begin{lstlisting}
  12533. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  12534. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  12535. \end{lstlisting}
  12536. where $\itm{mainDef}$ is
  12537. \begin{lstlisting}
  12538. (Def 'main '() 'Integer '() |$\Exp'$|)
  12539. \end{lstlisting}
  12540. \fi}
  12541. {\if\edition\pythonEd
  12542. \begin{lstlisting}
  12543. Module(|$\Def\ldots\Stmt\ldots$|)
  12544. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  12545. \end{lstlisting}
  12546. where $\itm{mainDef}$ is
  12547. \begin{lstlisting}
  12548. FunctionDef('main', [], int, |$\Stmt'\ldots$|Return(Constant(0)))
  12549. \end{lstlisting}
  12550. \fi}
  12551. \section{Reveal Functions and the \LangFunRef{} language}
  12552. \label{sec:reveal-functions-r4}
  12553. The syntax of \LangFun{} is inconvenient for purposes of compilation
  12554. in that it conflates the use of function names and local
  12555. variables. This is a problem because we need to compile the use of a
  12556. function name differently than the use of a local variable; we need to
  12557. use \code{leaq} to convert the function name (a label in x86) to an
  12558. address in a register. Thus, we create a new pass that changes
  12559. function references from $\VAR{f}$ to $\FUNREF{f}$. This pass is named
  12560. \code{reveal\_functions} and the output language, \LangFunRef{}, is
  12561. defined in Figure~\ref{fig:f1-syntax}.
  12562. %% The concrete syntax for a
  12563. %% function reference is $\CFUNREF{f}$.
  12564. \begin{figure}[tp]
  12565. \centering
  12566. \fbox{
  12567. \begin{minipage}{0.96\textwidth}
  12568. {\if\edition\racketEd
  12569. \[
  12570. \begin{array}{lcl}
  12571. \Exp &::=& \ldots \MID \FUNREF{\Var}\\
  12572. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12573. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  12574. \end{array}
  12575. \]
  12576. \fi}
  12577. {\if\edition\pythonEd
  12578. \[
  12579. \begin{array}{lcl}
  12580. \Exp &::=& \FUNREF{\Var}\\
  12581. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  12582. \end{array}
  12583. \]
  12584. \fi}
  12585. \end{minipage}
  12586. }
  12587. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  12588. (Figure~\ref{fig:Rfun-syntax}).}
  12589. \label{fig:f1-syntax}
  12590. \end{figure}
  12591. %% Distinguishing between calls in tail position and non-tail position
  12592. %% requires the pass to have some notion of context. We recommend using
  12593. %% two mutually recursive functions, one for processing expressions in
  12594. %% tail position and another for the rest.
  12595. \racket{Placing this pass after \code{uniquify} will make sure that
  12596. there are no local variables and functions that share the same
  12597. name.}
  12598. %
  12599. The \code{reveal\_functions} pass should come before the
  12600. \code{remove\_complex\_operands} pass because function references
  12601. should be categorized as complex expressions.
  12602. \section{Limit Functions}
  12603. \label{sec:limit-functions-r4}
  12604. Recall that we wish to limit the number of function parameters to six
  12605. so that we do not need to use the stack for argument passing, which
  12606. makes it easier to implement efficient tail calls. However, because
  12607. the input language \LangFun{} supports arbitrary numbers of function
  12608. arguments, we have some work to do!
  12609. This pass transforms functions and function calls that involve more
  12610. than six arguments to pass the first five arguments as usual, but it
  12611. packs the rest of the arguments into a vector and passes it as the
  12612. sixth argument.
  12613. Each function definition with too many parameters is transformed as
  12614. follows.
  12615. {\if\edition\racketEd
  12616. \begin{lstlisting}
  12617. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  12618. |$\Rightarrow$|
  12619. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  12620. \end{lstlisting}
  12621. \fi}
  12622. {\if\edition\pythonEd
  12623. \begin{lstlisting}
  12624. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, |$\itm{body}$|)
  12625. |$\Rightarrow$|
  12626. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))], |$T_r$|, |$\itm{body}'$|)
  12627. \end{lstlisting}
  12628. \fi}
  12629. %
  12630. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  12631. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  12632. the $k$th element of the tuple, where $k = i - 6$.
  12633. %
  12634. {\if\edition\racketEd
  12635. \begin{lstlisting}
  12636. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  12637. \end{lstlisting}
  12638. \fi}
  12639. {\if\edition\pythonEd
  12640. \begin{lstlisting}
  12641. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|))
  12642. \end{lstlisting}
  12643. \fi}
  12644. For function calls with too many arguments, the \code{limit\_functions}
  12645. pass transforms them in the following way.
  12646. \begin{tabular}{lll}
  12647. \begin{minipage}{0.3\textwidth}
  12648. {\if\edition\racketEd
  12649. \begin{lstlisting}
  12650. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  12651. \end{lstlisting}
  12652. \fi}
  12653. {\if\edition\pythonEd
  12654. \begin{lstlisting}
  12655. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  12656. \end{lstlisting}
  12657. \fi}
  12658. \end{minipage}
  12659. &
  12660. $\Rightarrow$
  12661. &
  12662. \begin{minipage}{0.5\textwidth}
  12663. {\if\edition\racketEd
  12664. \begin{lstlisting}
  12665. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  12666. \end{lstlisting}
  12667. \fi}
  12668. {\if\edition\pythonEd
  12669. \begin{lstlisting}
  12670. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  12671. \end{lstlisting}
  12672. \fi}
  12673. \end{minipage}
  12674. \end{tabular}
  12675. \section{Remove Complex Operands}
  12676. \label{sec:rco-r4}
  12677. The primary decisions to make for this pass is whether to classify
  12678. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  12679. atomic or complex expressions. Recall that a simple expression will
  12680. eventually end up as just an immediate argument of an x86
  12681. instruction. Function application will be translated to a sequence of
  12682. instructions, so \racket{\code{Apply}}\python{\code{Call}} must be
  12683. classified as complex expression. On the other hand, the arguments of
  12684. \racket{\code{Apply}}\python{\code{Call}} should be atomic expressions.
  12685. %
  12686. Regarding \code{FunRef}, as discussed above, the function label needs
  12687. to be converted to an address using the \code{leaq} instruction. Thus,
  12688. even though \code{FunRef} seems rather simple, it needs to be
  12689. classified as a complex expression so that we generate an assignment
  12690. statement with a left-hand side that can serve as the target of the
  12691. \code{leaq}.
  12692. The output of this pass, \LangFunANF{}, extends \LangAllocANF{}
  12693. (Figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  12694. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions.
  12695. %
  12696. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  12697. % TODO: Return?
  12698. %% Figure~\ref{fig:Rfun-anf-syntax} defines the output language
  12699. %% \LangFunANF{} of this pass.
  12700. %% \begin{figure}[tp]
  12701. %% \centering
  12702. %% \fbox{
  12703. %% \begin{minipage}{0.96\textwidth}
  12704. %% \small
  12705. %% \[
  12706. %% \begin{array}{rcl}
  12707. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  12708. %% \MID \VOID{} } \\
  12709. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  12710. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  12711. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  12712. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  12713. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  12714. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  12715. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  12716. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  12717. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12718. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  12719. %% \end{array}
  12720. %% \]
  12721. %% \end{minipage}
  12722. %% }
  12723. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  12724. %% \label{fig:Rfun-anf-syntax}
  12725. %% \end{figure}
  12726. \section{Explicate Control and the \LangCFun{} language}
  12727. \label{sec:explicate-control-r4}
  12728. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  12729. output of \code{explicate\_control}.
  12730. %
  12731. \racket{(The concrete syntax is given in
  12732. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  12733. %
  12734. The auxiliary functions for assignment\racket{and tail contexts} should
  12735. be updated with cases for
  12736. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  12737. function for predicate context should be updated for
  12738. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  12739. \code{FunRef} can't be a Boolean.) In assignment and predicate
  12740. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  12741. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  12742. auxiliary function for processing function definitions. This code is
  12743. similar to the case for \code{Program} in \LangVec{}. The top-level
  12744. \code{explicate\_control} function that handles the \code{ProgramDefs}
  12745. form of \LangFun{} can then apply this new function to all the
  12746. function definitions.
  12747. {\if\edition\pythonEd
  12748. The translation of \code{Return} statements requires a new auxiliary
  12749. function to handle expressions in tail context, called
  12750. \code{explicate\_tail}. The function should take an expression and the
  12751. dictionary of basic blocks and produce a list of statements in the
  12752. \LangCFun{} language. The \code{explicate\_tail} function should
  12753. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  12754. and a default case for other kinds of expressions. The default case
  12755. should produce a \code{Return} statement. The case for \code{Call}
  12756. should change it into \code{TailCall}. The other cases should
  12757. recursively process their subexpressions and statements, choosing the
  12758. appropriate explicate functions for the various contexts.
  12759. \fi}
  12760. \newcommand{\CfunASTPython}{
  12761. \begin{array}{lcl}
  12762. \Exp &::= & \FUNREF{\itm{label}} \MID \CALL{\Atm}{\LS\Atm\code{,}\ldots\RS} \\
  12763. \Stmt &::= & \TAILCALL{\Atm}{\LS\Atm\code{,}\ldots\RS} \\
  12764. \Def &::=& \DEF{\itm{label}}{\LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS}{\LC\itm{label}\key{:}\Stmt^{*}\code{,}\ldots\RC}{\_}{\Type}{\_}
  12765. \end{array}
  12766. }
  12767. \begin{figure}[tp]
  12768. \fbox{
  12769. \begin{minipage}{0.96\textwidth}
  12770. \small
  12771. {\if\edition\racketEd
  12772. \[
  12773. \begin{array}{lcl}
  12774. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  12775. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  12776. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  12777. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  12778. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  12779. &\MID& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  12780. &\MID& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  12781. &\MID& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  12782. &\MID& \gray{ \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP }\\
  12783. &\MID& \FUNREF{\itm{label}} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  12784. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  12785. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  12786. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  12787. \MID \GOTO{\itm{label}} } \\
  12788. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  12789. &\MID& \TAILCALL{\Atm}{\Atm\ldots} \\
  12790. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  12791. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12792. \end{array}
  12793. \]
  12794. \fi}
  12795. {\if\edition\pythonEd
  12796. \[
  12797. \begin{array}{l}
  12798. \gray{\CifASTPython} \\ \hline
  12799. \gray{\CtupASTPython} \\ \hline
  12800. \CfunASTPython \\
  12801. \begin{array}{lcl}
  12802. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  12803. \end{array}
  12804. \end{array}
  12805. \]
  12806. \fi}
  12807. \end{minipage}
  12808. }
  12809. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  12810. \label{fig:c3-syntax}
  12811. \end{figure}
  12812. \section{Select Instructions and the \LangXIndCall{} Language}
  12813. \label{sec:select-r4}
  12814. \index{subject}{instruction selection}
  12815. The output of select instructions is a program in the \LangXIndCall{}
  12816. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  12817. \index{subject}{x86}
  12818. \begin{figure}[tp]
  12819. \fbox{
  12820. \begin{minipage}{0.96\textwidth}
  12821. \small
  12822. \[
  12823. \begin{array}{lcl}
  12824. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  12825. \itm{cc} & ::= & \gray{ \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  12826. \Instr &::=& \ldots
  12827. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  12828. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  12829. \Block &::= & \Instr\ldots \\
  12830. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  12831. \LangXIndCallM{} &::= & \Def\ldots
  12832. \end{array}
  12833. \]
  12834. \end{minipage}
  12835. }
  12836. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  12837. \label{fig:x86-3-concrete}
  12838. \end{figure}
  12839. \begin{figure}[tp]
  12840. \fbox{
  12841. \begin{minipage}{0.96\textwidth}
  12842. \small
  12843. {\if\edition\racketEd
  12844. \[
  12845. \begin{array}{lcl}
  12846. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  12847. \MID \BYTEREG{\Reg} } \\
  12848. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}} \\
  12849. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  12850. \MID \TAILJMP{\Arg}{\itm{int}}\\
  12851. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  12852. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  12853. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  12854. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12855. \end{array}
  12856. \]
  12857. \fi}
  12858. {\if\edition\pythonEd
  12859. \[
  12860. \begin{array}{lcl}
  12861. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  12862. \MID \BYTEREG{\Reg} } \\
  12863. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}} \\
  12864. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  12865. \MID \TAILJMP{\Arg}{\itm{int}}\\
  12866. &\MID& \BININSTR{\code{leaq}}{\Arg}{\REG{\Reg}}\\
  12867. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\LC\itm{label}\key{:}\,\Instr^{*}\code{,}\ldots\RC}{\_}{\Type}{\_} \\
  12868. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  12869. \end{array}
  12870. \]
  12871. \fi}
  12872. \end{minipage}
  12873. }
  12874. \caption{The abstract syntax of \LangXIndCall{} (extends
  12875. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  12876. \label{fig:x86-3}
  12877. \end{figure}
  12878. An assignment of a function reference to a variable becomes a
  12879. load-effective-address instruction as follows, where $\itm{lhs}'$
  12880. is the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{}
  12881. to \Arg{} in \LangXIndCallVar{}. \\
  12882. \begin{tabular}{lcl}
  12883. \begin{minipage}{0.35\textwidth}
  12884. \begin{lstlisting}
  12885. |$\itm{lhs}$| = (fun-ref |$f$|);
  12886. \end{lstlisting}
  12887. \end{minipage}
  12888. &
  12889. $\Rightarrow$\qquad\qquad
  12890. &
  12891. \begin{minipage}{0.3\textwidth}
  12892. \begin{lstlisting}
  12893. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  12894. \end{lstlisting}
  12895. \end{minipage}
  12896. \end{tabular} \\
  12897. Regarding function definitions, we need to remove the parameters and
  12898. instead perform parameter passing using the conventions discussed in
  12899. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  12900. registers. We recommend turning the parameters into local variables
  12901. and generating instructions at the beginning of the function to move
  12902. from the argument passing registers to these local variables.
  12903. {\if\edition\racketEd
  12904. \begin{lstlisting}
  12905. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  12906. |$\Rightarrow$|
  12907. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  12908. \end{lstlisting}
  12909. \fi}
  12910. {\if\edition\pythonEd
  12911. \begin{lstlisting}
  12912. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  12913. |$\Rightarrow$|
  12914. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  12915. \end{lstlisting}
  12916. \fi}
  12917. The basic blocks $B'$ are the same as $B$ except that the
  12918. \code{start} block is modified to add the instructions for moving from
  12919. the argument registers to the parameter variables. So the \code{start}
  12920. block of $B$ shown on the left is changed to the code on the right.
  12921. \begin{center}
  12922. \begin{minipage}{0.3\textwidth}
  12923. \begin{lstlisting}
  12924. start:
  12925. |$\itm{instr}_1$|
  12926. |$\cdots$|
  12927. |$\itm{instr}_n$|
  12928. \end{lstlisting}
  12929. \end{minipage}
  12930. $\Rightarrow$
  12931. \begin{minipage}{0.3\textwidth}
  12932. \begin{lstlisting}
  12933. start:
  12934. movq %rdi, |$x_1$|
  12935. |$\cdots$|
  12936. |$\itm{instr}_1$|
  12937. |$\cdots$|
  12938. |$\itm{instr}_n$|
  12939. \end{lstlisting}
  12940. \end{minipage}
  12941. \end{center}
  12942. By changing the parameters to local variables, we are giving the
  12943. register allocator control over which registers or stack locations to
  12944. use for them. If you implemented the move-biasing challenge
  12945. (Section~\ref{sec:move-biasing}), the register allocator will try to
  12946. assign the parameter variables to the corresponding argument register,
  12947. in which case the \code{patch\_instructions} pass will remove the
  12948. \code{movq} instruction. This happens in the example translation in
  12949. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  12950. the \code{add} function.
  12951. %
  12952. Also, note that the register allocator will perform liveness analysis
  12953. on this sequence of move instructions and build the interference
  12954. graph. So, for example, $x_1$ will be marked as interfering with
  12955. \code{rsi} and that will prevent the assignment of $x_1$ to
  12956. \code{rsi}, which is good, because that would overwrite the argument
  12957. that needs to move into $x_2$.
  12958. Next, consider the compilation of function calls. In the mirror image
  12959. of handling the parameters of function definitions, the arguments need
  12960. to be moved to the argument passing registers. The function call
  12961. itself is performed with an indirect function call. The return value
  12962. from the function is stored in \code{rax}, so it needs to be moved
  12963. into the \itm{lhs}.
  12964. \begin{lstlisting}
  12965. |\itm{lhs}| = |$\CALL{\itm{fun}}{\itm{arg}_1\ldots}$|
  12966. |$\Rightarrow$|
  12967. movq |$\itm{arg}_1$|, %rdi
  12968. movq |$\itm{arg}_2$|, %rsi
  12969. |$\vdots$|
  12970. callq *|\itm{fun}|
  12971. movq %rax, |\itm{lhs}|
  12972. \end{lstlisting}
  12973. The \code{IndirectCallq} AST node includes an integer for the arity of
  12974. the function, i.e., the number of parameters. That information is
  12975. useful in the \code{uncover\_live} pass for determining which
  12976. argument-passing registers are potentially read during the call.
  12977. For tail calls, the parameter passing is the same as non-tail calls:
  12978. generate instructions to move the arguments into to the argument
  12979. passing registers. After that we need to pop the frame from the
  12980. procedure call stack. However, we do not yet know how big the frame
  12981. is; that gets determined during register allocation. So instead of
  12982. generating those instructions here, we invent a new instruction that
  12983. means ``pop the frame and then do an indirect jump'', which we name
  12984. \code{TailJmp}. The abstract syntax for this instruction includes an
  12985. argument that specifies where to jump and an integer that represents
  12986. the arity of the function being called.
  12987. Recall that we use the label \code{start} for the initial block of a
  12988. program, and in Section~\ref{sec:select-Lvar} we recommended labeling
  12989. the conclusion of the program with \code{conclusion}, so that
  12990. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  12991. by a jump to \code{conclusion}. With the addition of function
  12992. definitions, there is a start block and conclusion for each function,
  12993. but their labels need to be unique. We recommend prepending the
  12994. function's name to \code{start} and \code{conclusion}, respectively,
  12995. to obtain unique labels.
  12996. \section{Register Allocation}
  12997. \label{sec:register-allocation-r4}
  12998. \subsection{Liveness Analysis}
  12999. \label{sec:liveness-analysis-r4}
  13000. \index{subject}{liveness analysis}
  13001. %% The rest of the passes need only minor modifications to handle the new
  13002. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  13003. %% \code{leaq}.
  13004. The \code{IndirectCallq} instruction should be treated like
  13005. \code{Callq} regarding its written locations $W$, in that they should
  13006. include all the caller-saved registers. Recall that the reason for
  13007. that is to force call-live variables to be assigned to callee-saved
  13008. registers or to be spilled to the stack.
  13009. Regarding the set of read locations $R$ the arity field of
  13010. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  13011. argument-passing registers should be considered as read by those
  13012. instructions.
  13013. \subsection{Build Interference Graph}
  13014. \label{sec:build-interference-r4}
  13015. With the addition of function definitions, we compute an interference
  13016. graph for each function (not just one for the whole program).
  13017. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  13018. spill vector-typed variables that are live during a call to the
  13019. \code{collect}. With the addition of functions to our language, we
  13020. need to revisit this issue. Many functions perform allocation and
  13021. therefore have calls to the collector inside of them. Thus, we should
  13022. not only spill a vector-typed variable when it is live during a call
  13023. to \code{collect}, but we should spill the variable if it is live
  13024. during any function call. Thus, in the \code{build\_interference} pass,
  13025. we recommend adding interference edges between call-live vector-typed
  13026. variables and the callee-saved registers (in addition to the usual
  13027. addition of edges between call-live variables and the caller-saved
  13028. registers).
  13029. \subsection{Allocate Registers}
  13030. The primary change to the \code{allocate\_registers} pass is adding an
  13031. auxiliary function for handling definitions (the \Def{} non-terminal
  13032. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  13033. logic is the same as described in
  13034. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  13035. allocation is performed many times, once for each function definition,
  13036. instead of just once for the whole program.
  13037. \section{Patch Instructions}
  13038. In \code{patch\_instructions}, you should deal with the x86
  13039. idiosyncrasy that the destination argument of \code{leaq} must be a
  13040. register. Additionally, you should ensure that the argument of
  13041. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  13042. code generation more convenient, because we trample many registers
  13043. before the tail call (as explained in the next section).
  13044. \section{Prelude and Conclusion}
  13045. %% For the \code{print\_x86} pass, the cases for \code{FunRef} and
  13046. %% \code{IndirectCallq} are straightforward: output their concrete
  13047. %% syntax.
  13048. %% \begin{lstlisting}
  13049. %% (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  13050. %% (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  13051. %% \end{lstlisting}
  13052. Now that register allocation is complete, we can translate the
  13053. \code{TailJmp} into a sequence of instructions. A straightforward
  13054. translation of \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}.
  13055. However, before the jump we need to pop the current frame. This
  13056. sequence of instructions is the same as the code for the conclusion of
  13057. a function, except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  13058. Regarding function definitions, you need to generate a prelude
  13059. and conclusion for each one. This code is similar to the prelude and
  13060. conclusion that you generated for the \code{main} function in
  13061. Chapter~\ref{ch:Lvec}. To review, the prelude of every function
  13062. should carry out the following steps.
  13063. % TODO: .align the functions!
  13064. \begin{enumerate}
  13065. %% \item Start with \code{.global} and \code{.align} directives followed
  13066. %% by the label for the function. (See Figure~\ref{fig:add-fun} for an
  13067. %% example.)
  13068. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  13069. pointer.
  13070. \item Push to the stack all of the callee-saved registers that were
  13071. used for register allocation.
  13072. \item Move the stack pointer \code{rsp} down by the size of the stack
  13073. frame for this function, which depends on the number of regular
  13074. spills. (Aligned to 16 bytes.)
  13075. \item Move the root stack pointer \code{r15} up by the size of the
  13076. root-stack frame for this function, which depends on the number of
  13077. spilled vectors. \label{root-stack-init}
  13078. \item Initialize to zero all of the entries in the root-stack frame.
  13079. \item Jump to the start block.
  13080. \end{enumerate}
  13081. The prelude of the \code{main} function has one additional task: call
  13082. the \code{initialize} function to set up the garbage collector and
  13083. move the value of the global \code{rootstack\_begin} in
  13084. \code{r15}. This should happen before step \ref{root-stack-init}
  13085. above, which depends on \code{r15}.
  13086. The conclusion of every function should do the following.
  13087. \begin{enumerate}
  13088. \item Move the stack pointer back up by the size of the stack frame
  13089. for this function.
  13090. \item Restore the callee-saved registers by popping them from the
  13091. stack.
  13092. \item Move the root stack pointer back down by the size of the
  13093. root-stack frame for this function.
  13094. \item Restore \code{rbp} by popping it from the stack.
  13095. \item Return to the caller with the \code{retq} instruction.
  13096. \end{enumerate}
  13097. \begin{exercise}\normalfont
  13098. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  13099. Create 5 new programs that use functions, including examples that pass
  13100. functions and return functions from other functions, recursive
  13101. functions, functions that create vectors, and functions that make tail
  13102. calls. Test your compiler on these new programs and all of your
  13103. previously created test programs.
  13104. \end{exercise}
  13105. \begin{figure}[tbp]
  13106. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13107. \node (Rfun) at (0,2) {\large \LangFun{}};
  13108. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  13109. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  13110. \node (F1-1) at (9,2) {\large \LangFunRef{}};
  13111. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13112. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  13113. \node (F1-4) at (3,0) {\large \LangFunANF{}};
  13114. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13115. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13116. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13117. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13118. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13119. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13120. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13121. \path[->,bend left=15] (Rfun) edge [above] node
  13122. {\ttfamily\footnotesize shrink} (Rfun-1);
  13123. \path[->,bend left=15] (Rfun-1) edge [above] node
  13124. {\ttfamily\footnotesize uniquify} (Rfun-2);
  13125. \path[->,bend left=15] (Rfun-2) edge [above] node
  13126. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13127. \path[->,bend left=15] (F1-1) edge [right] node
  13128. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13129. \path[->,bend right=15] (F1-2) edge [above] node
  13130. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  13131. \path[->,bend right=15] (F1-3) edge [above] node
  13132. {\ttfamily\footnotesize remove\_complex.} (F1-4);
  13133. \path[->,bend left=15] (F1-4) edge [right] node
  13134. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13135. \path[->,bend right=15] (C3-2) edge [left] node
  13136. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13137. \path[->,bend left=15] (x86-2) edge [left] node
  13138. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13139. \path[->,bend right=15] (x86-2-1) edge [below] node
  13140. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13141. \path[->,bend right=15] (x86-2-2) edge [left] node
  13142. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13143. \path[->,bend left=15] (x86-3) edge [above] node
  13144. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13145. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  13146. \end{tikzpicture}
  13147. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  13148. \label{fig:Rfun-passes}
  13149. \end{figure}
  13150. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  13151. compiling \LangFun{} to x86.
  13152. \section{An Example Translation}
  13153. \label{sec:functions-example}
  13154. Figure~\ref{fig:add-fun} shows an example translation of a simple
  13155. function in \LangFun{} to x86. The figure also includes the results of the
  13156. \code{explicate\_control} and \code{select\_instructions} passes.
  13157. \begin{figure}[htbp]
  13158. \begin{tabular}{ll}
  13159. \begin{minipage}{0.4\textwidth}
  13160. % s3_2.rkt
  13161. {\if\edition\racketEd
  13162. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13163. (define (add [x : Integer] [y : Integer])
  13164. : Integer
  13165. (+ x y))
  13166. (add 40 2)
  13167. \end{lstlisting}
  13168. \fi}
  13169. {\if\edition\pythonEd
  13170. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13171. def add(x:int, y:int) -> int:
  13172. return x + y
  13173. print(add(40, 2))
  13174. \end{lstlisting}
  13175. \fi}
  13176. $\Downarrow$
  13177. {\if\edition\racketEd
  13178. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13179. (define (add86 [x87 : Integer]
  13180. [y88 : Integer]) : Integer
  13181. add86start:
  13182. return (+ x87 y88);
  13183. )
  13184. (define (main) : Integer ()
  13185. mainstart:
  13186. tmp89 = (fun-ref add86);
  13187. (tail-call tmp89 40 2)
  13188. )
  13189. \end{lstlisting}
  13190. \fi}
  13191. {\if\edition\pythonEd
  13192. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13193. def add(x:int, y:int) -> int:
  13194. addstart:
  13195. return x + y
  13196. def main() -> int:
  13197. mainstart:
  13198. fun.0 = add
  13199. tmp.1 = fun.0(40, 2)
  13200. print(tmp.1)
  13201. return 0
  13202. \end{lstlisting}
  13203. \fi}
  13204. \end{minipage}
  13205. &
  13206. $\Rightarrow$
  13207. \begin{minipage}{0.5\textwidth}
  13208. {\if\edition\racketEd
  13209. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13210. (define (add86) : Integer
  13211. add86start:
  13212. movq %rdi, x87
  13213. movq %rsi, y88
  13214. movq x87, %rax
  13215. addq y88, %rax
  13216. jmp inc1389conclusion
  13217. )
  13218. (define (main) : Integer
  13219. mainstart:
  13220. leaq (fun-ref add86), tmp89
  13221. movq $40, %rdi
  13222. movq $2, %rsi
  13223. tail-jmp tmp89
  13224. )
  13225. \end{lstlisting}
  13226. \fi}
  13227. {\if\edition\pythonEd
  13228. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13229. def add() -> int:
  13230. addstart:
  13231. movq %rdi, x
  13232. movq %rsi, y
  13233. movq x, %rax
  13234. addq y, %rax
  13235. jmp addconclusion
  13236. def main() -> int:
  13237. mainstart:
  13238. leaq add, fun.0
  13239. movq $40, %rdi
  13240. movq $2, %rsi
  13241. callq *fun.0
  13242. movq %rax, tmp.1
  13243. movq tmp.1, %rdi
  13244. callq print_int
  13245. movq $0, %rax
  13246. jmp mainconclusion
  13247. \end{lstlisting}
  13248. \fi}
  13249. $\Downarrow$
  13250. \end{minipage}
  13251. \end{tabular}
  13252. \begin{tabular}{ll}
  13253. \begin{minipage}{0.3\textwidth}
  13254. {\if\edition\racketEd
  13255. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13256. .globl add86
  13257. .align 16
  13258. add86:
  13259. pushq %rbp
  13260. movq %rsp, %rbp
  13261. jmp add86start
  13262. add86start:
  13263. movq %rdi, %rax
  13264. addq %rsi, %rax
  13265. jmp add86conclusion
  13266. add86conclusion:
  13267. popq %rbp
  13268. retq
  13269. \end{lstlisting}
  13270. \fi}
  13271. {\if\edition\pythonEd
  13272. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13273. .align 16
  13274. add:
  13275. pushq %rbp
  13276. movq %rsp, %rbp
  13277. subq $0, %rsp
  13278. jmp addstart
  13279. addstart:
  13280. movq %rdi, %rdx
  13281. movq %rsi, %rcx
  13282. movq %rdx, %rax
  13283. addq %rcx, %rax
  13284. jmp addconclusion
  13285. addconclusion:
  13286. subq $0, %r15
  13287. addq $0, %rsp
  13288. popq %rbp
  13289. retq
  13290. \end{lstlisting}
  13291. \fi}
  13292. \end{minipage}
  13293. &
  13294. \begin{minipage}{0.5\textwidth}
  13295. {\if\edition\racketEd
  13296. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13297. .globl main
  13298. .align 16
  13299. main:
  13300. pushq %rbp
  13301. movq %rsp, %rbp
  13302. movq $16384, %rdi
  13303. movq $16384, %rsi
  13304. callq initialize
  13305. movq rootstack_begin(%rip), %r15
  13306. jmp mainstart
  13307. mainstart:
  13308. leaq add86(%rip), %rcx
  13309. movq $40, %rdi
  13310. movq $2, %rsi
  13311. movq %rcx, %rax
  13312. popq %rbp
  13313. jmp *%rax
  13314. mainconclusion:
  13315. popq %rbp
  13316. retq
  13317. \end{lstlisting}
  13318. \fi}
  13319. {\if\edition\pythonEd
  13320. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13321. .globl main
  13322. .align 16
  13323. main:
  13324. pushq %rbp
  13325. movq %rsp, %rbp
  13326. subq $0, %rsp
  13327. movq $65536, %rdi
  13328. movq $65536, %rsi
  13329. callq initialize
  13330. movq rootstack_begin(%rip), %r15
  13331. jmp mainstart
  13332. mainstart:
  13333. leaq add(%rip), %rcx
  13334. movq $40, %rdi
  13335. movq $2, %rsi
  13336. callq *%rcx
  13337. movq %rax, %rcx
  13338. movq %rcx, %rdi
  13339. callq print_int
  13340. movq $0, %rax
  13341. jmp mainconclusion
  13342. mainconclusion:
  13343. subq $0, %r15
  13344. addq $0, %rsp
  13345. popq %rbp
  13346. retq
  13347. \end{lstlisting}
  13348. \fi}
  13349. \end{minipage}
  13350. \end{tabular}
  13351. \caption{Example compilation of a simple function to x86.}
  13352. \label{fig:add-fun}
  13353. \end{figure}
  13354. % Challenge idea: inlining! (simple version)
  13355. % Further Reading
  13356. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13357. \chapter{Lexically Scoped Functions}
  13358. \label{ch:Rlam}
  13359. \index{subject}{lambda}
  13360. \index{subject}{lexical scoping}
  13361. This chapter studies lexically scoped functions as they appear in
  13362. functional languages such as Racket. By lexical scoping we mean that a
  13363. function's body may refer to variables whose binding site is outside
  13364. of the function, in an enclosing scope.
  13365. %
  13366. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  13367. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  13368. \key{lambda} form. The body of the \key{lambda}, refers to three
  13369. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  13370. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  13371. \code{y} is \racket{bound by the enclosing \key{let}}\python{a local variable of function\code{f}} and \code{x} is a
  13372. parameter of function \code{f}. The \key{lambda} is returned from the
  13373. function \code{f}. The main expression of the program includes two
  13374. calls to \code{f} with different arguments for \code{x}, first
  13375. \code{5} then \code{3}. The functions returned from \code{f} are bound
  13376. to variables \code{g} and \code{h}. Even though these two functions
  13377. were created by the same \code{lambda}, they are really different
  13378. functions because they use different values for \code{x}. Applying
  13379. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  13380. \code{15} produces \code{22}. The result of this program is \code{42}.
  13381. \begin{figure}[btp]
  13382. {\if\edition\racketEd
  13383. % lambda_test_21.rkt
  13384. \begin{lstlisting}
  13385. (define (f [x : Integer]) : (Integer -> Integer)
  13386. (let ([y 4])
  13387. (lambda: ([z : Integer]) : Integer
  13388. (+ x (+ y z)))))
  13389. (let ([g (f 5)])
  13390. (let ([h (f 3)])
  13391. (+ (g 11) (h 15))))
  13392. \end{lstlisting}
  13393. \fi}
  13394. {\if\edition\pythonEd
  13395. \begin{lstlisting}
  13396. def f(x : int) -> Callable[[int], int]:
  13397. y = 4
  13398. return lambda z: x + y + z
  13399. g = f(5)
  13400. h = f(3)
  13401. print( g(11) + h(15) )
  13402. \end{lstlisting}
  13403. \fi}
  13404. \caption{Example of a lexically scoped function.}
  13405. \label{fig:lexical-scoping}
  13406. \end{figure}
  13407. The approach that we take for implementing lexically scoped functions
  13408. is to compile them into top-level function definitions, translating
  13409. from \LangLam{} into \LangFun{}. However, the compiler must give
  13410. special treatment to variable occurrences such as \code{x} and
  13411. \code{y} in the body of the \code{lambda} of
  13412. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  13413. may not refer to variables defined outside of it. To identify such
  13414. variable occurrences, we review the standard notion of free variable.
  13415. \begin{definition}
  13416. A variable is \textbf{free in expression} $e$ if the variable occurs
  13417. inside $e$ but does not have an enclosing binding that is also in
  13418. $e$.\index{subject}{free variable}
  13419. \end{definition}
  13420. For example, in the expression \code{(+ x (+ y z))} the variables
  13421. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  13422. only \code{x} and \code{y} are free in the following expression
  13423. because \code{z} is bound by the \code{lambda}.
  13424. {\if\edition\racketEd
  13425. \begin{lstlisting}
  13426. (lambda: ([z : Integer]) : Integer
  13427. (+ x (+ y z)))
  13428. \end{lstlisting}
  13429. \fi}
  13430. {\if\edition\pythonEd
  13431. \begin{lstlisting}
  13432. lambda z: x + y + z
  13433. \end{lstlisting}
  13434. \fi}
  13435. So the free variables of a \code{lambda} are the ones that will need
  13436. special treatment. We need to arrange for some way to transport, at
  13437. runtime, the values of those variables from the point where the
  13438. \code{lambda} was created to the point where the \code{lambda} is
  13439. applied. An efficient solution to the problem, due to
  13440. \citet{Cardelli:1983aa}, is to bundle into a tuple the values of the
  13441. free variables together with the function pointer for the lambda's
  13442. code, an arrangement called a \emph{flat closure} (which we shorten to
  13443. just ``closure''). \index{subject}{closure}\index{subject}{flat closure} Fortunately,
  13444. we have all the ingredients to make closures, Chapter~\ref{ch:Lvec}
  13445. gave us tuples and Chapter~\ref{ch:Rfun} gave us function
  13446. pointers. The function pointer resides at index $0$ and the
  13447. values for the free variables will fill in the rest of the tuple.
  13448. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  13449. how closures work. It's a three-step dance. The program first calls
  13450. function \code{f}, which creates a closure for the \code{lambda}. The
  13451. closure is a tuple whose first element is a pointer to the top-level
  13452. function that we will generate for the \code{lambda}, the second
  13453. element is the value of \code{x}, which is \code{5}, and the third
  13454. element is \code{4}, the value of \code{y}. The closure does not
  13455. contain an element for \code{z} because \code{z} is not a free
  13456. variable of the \code{lambda}. Creating the closure is step 1 of the
  13457. dance. The closure is returned from \code{f} and bound to \code{g}, as
  13458. shown in Figure~\ref{fig:closures}.
  13459. %
  13460. The second call to \code{f} creates another closure, this time with
  13461. \code{3} in the second slot (for \code{x}). This closure is also
  13462. returned from \code{f} but bound to \code{h}, which is also shown in
  13463. Figure~\ref{fig:closures}.
  13464. \begin{figure}[tbp]
  13465. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  13466. \caption{Example closure representation for the \key{lambda}'s
  13467. in Figure~\ref{fig:lexical-scoping}.}
  13468. \label{fig:closures}
  13469. \end{figure}
  13470. Continuing with the example, consider the application of \code{g} to
  13471. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  13472. obtain the function pointer in the first element of the closure and
  13473. call it, passing in the closure itself and then the regular arguments,
  13474. in this case \code{11}. This technique for applying a closure is step
  13475. 2 of the dance.
  13476. %
  13477. But doesn't this \code{lambda} only take 1 argument, for parameter
  13478. \code{z}? The third and final step of the dance is generating a
  13479. top-level function for a \code{lambda}. We add an additional
  13480. parameter for the closure and we insert an initialization at the beginning
  13481. of the function for each free variable, to bind those variables to the
  13482. appropriate elements from the closure parameter.
  13483. %
  13484. This three-step dance is known as \emph{closure conversion}. We
  13485. discuss the details of closure conversion in
  13486. Section~\ref{sec:closure-conversion} and the code generated from the
  13487. example in Section~\ref{sec:example-lambda}. But first we define the
  13488. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  13489. \section{The \LangLam{} Language}
  13490. \label{sec:r5}
  13491. \python{UNDER CONSTRUCTION}
  13492. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  13493. functions and lexical scoping, is defined in
  13494. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  13495. the \key{lambda} form to the grammar for \LangFun{}, which already has
  13496. syntax for function application.
  13497. \newcommand{\LlambdaGrammarRacket}{
  13498. \begin{array}{lcl}
  13499. \Exp &::=& \LP \key{procedure-arity}~\Exp\RP \\
  13500. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp}
  13501. \end{array}
  13502. }
  13503. \newcommand{\LlambdaASTRacket}{
  13504. \begin{array}{lcl}
  13505. \itm{op} &::=& \code{procedure-arity} \\
  13506. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}
  13507. \end{array}
  13508. }
  13509. % include AnnAssign in ASTPython
  13510. \begin{figure}[tp]
  13511. \centering
  13512. \fbox{
  13513. \begin{minipage}{0.96\textwidth}
  13514. \small
  13515. \[
  13516. \begin{array}{l}
  13517. \gray{\LintGrammarRacket{}} \\ \hline
  13518. \gray{\LvarGrammarRacket{}} \\ \hline
  13519. \gray{\LifGrammarRacket{}} \\ \hline
  13520. \gray{\LwhileGrammarRacket} \\ \hline
  13521. \gray{\LtupGrammarRacket} \\ \hline
  13522. \gray{\LfunGrammarRacket} \\ \hline
  13523. \LlambdaGrammarRacket \\
  13524. \begin{array}{lcl}
  13525. \LangLamM{} &::=& \Def\ldots \; \Exp
  13526. \end{array}
  13527. \end{array}
  13528. \]
  13529. \end{minipage}
  13530. }
  13531. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  13532. with \key{lambda}.}
  13533. \label{fig:Rlam-concrete-syntax}
  13534. \end{figure}
  13535. \begin{figure}[tp]
  13536. \centering
  13537. \fbox{
  13538. \begin{minipage}{0.96\textwidth}
  13539. \small
  13540. \[
  13541. \begin{array}{l}
  13542. \gray{\LintOpAST} \\ \hline
  13543. \gray{\LvarASTRacket{}} \\ \hline
  13544. \gray{\LifASTRacket{}} \\ \hline
  13545. \gray{\LwhileASTRacket{}} \\ \hline
  13546. \gray{\LtupASTRacket{}} \\ \hline
  13547. \gray{\LfunASTRacket} \\ \hline
  13548. \LlambdaASTRacket \\
  13549. \begin{array}{lcl}
  13550. \LangLamM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  13551. \end{array}
  13552. \end{array}
  13553. \]
  13554. \end{minipage}
  13555. }
  13556. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  13557. \label{fig:Rlam-syntax}
  13558. \end{figure}
  13559. \index{subject}{interpreter}
  13560. \label{sec:interp-Rlambda}
  13561. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  13562. \LangLam{}. The case for \key{lambda} saves the current environment
  13563. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  13564. the environment from the \key{lambda}, the \code{lam-env}, when
  13565. interpreting the body of the \key{lambda}. The \code{lam-env}
  13566. environment is extended with the mapping of parameters to argument
  13567. values.
  13568. \begin{figure}[tbp]
  13569. \begin{lstlisting}
  13570. (define interp-Rlambda_class
  13571. (class interp-Rfun_class
  13572. (super-new)
  13573. (define/override (interp-op op)
  13574. (match op
  13575. ['procedure-arity
  13576. (lambda (v)
  13577. (match v
  13578. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  13579. [else (error 'interp-op "expected a function, not ~a" v)]))]
  13580. [else (super interp-op op)]))
  13581. (define/override ((interp-exp env) e)
  13582. (define recur (interp-exp env))
  13583. (match e
  13584. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  13585. `(function ,xs ,body ,env)]
  13586. [else ((super interp-exp env) e)]))
  13587. ))
  13588. (define (interp-Rlambda p)
  13589. (send (new interp-Rlambda_class) interp-program p))
  13590. \end{lstlisting}
  13591. \caption{Interpreter for \LangLam{}.}
  13592. \label{fig:interp-Rlambda}
  13593. \end{figure}
  13594. \label{sec:type-check-r5}
  13595. \index{subject}{type checking}
  13596. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  13597. \key{lambda} form. The body of the \key{lambda} is checked in an
  13598. environment that includes the current environment (because it is
  13599. lexically scoped) and also includes the \key{lambda}'s parameters. We
  13600. require the body's type to match the declared return type.
  13601. \begin{figure}[tbp]
  13602. \begin{lstlisting}
  13603. (define (type-check-Rlambda env)
  13604. (lambda (e)
  13605. (match e
  13606. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  13607. (define-values (new-body bodyT)
  13608. ((type-check-exp (append (map cons xs Ts) env)) body))
  13609. (define ty `(,@Ts -> ,rT))
  13610. (cond
  13611. [(equal? rT bodyT)
  13612. (values (HasType (Lambda params rT new-body) ty) ty)]
  13613. [else
  13614. (error "mismatch in return type" bodyT rT)])]
  13615. ...
  13616. )))
  13617. \end{lstlisting}
  13618. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  13619. \label{fig:type-check-Rlambda}
  13620. \end{figure}
  13621. \section{Assignment and Lexically Scoped Functions}
  13622. \label{sec:assignment-scoping}
  13623. The combination of lexically-scoped functions and assignment to
  13624. variables raises a challenge with our approach to implementing
  13625. lexically-scoped functions. Consider the following example in which
  13626. function \code{f} has a free variable \code{x} that is changed after
  13627. \code{f} is created but before the call to \code{f}.
  13628. % loop_test_11.rkt
  13629. {\if\edition\racketEd
  13630. \begin{lstlisting}
  13631. (let ([x 0])
  13632. (let ([y 0])
  13633. (let ([z 20])
  13634. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  13635. (begin
  13636. (set! x 10)
  13637. (set! y 12)
  13638. (f y))))))
  13639. \end{lstlisting}
  13640. \fi}
  13641. {\if\edition\pythonEd
  13642. % assign_free.py
  13643. \begin{lstlisting}
  13644. x = 0
  13645. y = 0
  13646. z = 20
  13647. f : Callable[[int],int] = lambda a: a + x + z
  13648. x = 10
  13649. y = 12
  13650. print( f(y) )
  13651. \end{lstlisting}
  13652. \fi}
  13653. The correct output for this example is \code{42} because the call to
  13654. \code{f} is required to use the current value of \code{x} (which is
  13655. \code{10}). Unfortunately, the closure conversion pass
  13656. (Section~\ref{sec:closure-conversion}) generates code for the
  13657. \code{lambda} that copies the old value of \code{x} into a
  13658. closure. Thus, if we naively add support for assignment to our current
  13659. compiler, the output of this program would be \code{32}.
  13660. A first attempt at solving this problem would be to save a pointer to
  13661. \code{x} in the closure and change the occurrences of \code{x} inside
  13662. the lambda to dereference the pointer. Of course, this would require
  13663. assigning \code{x} to the stack and not to a register. However, the
  13664. problem goes a bit deeper.
  13665. %% Consider the following example in which we
  13666. %% create a counter abstraction by creating a pair of functions that
  13667. %% share the free variable \code{x}.
  13668. Consider the following example that returns a function that refers to
  13669. a local variable of the enclosing function.
  13670. \begin{center}
  13671. \begin{minipage}{\textwidth}
  13672. {\if\edition\racketEd
  13673. % similar to loop_test_10.rkt
  13674. %% \begin{lstlisting}
  13675. %% (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  13676. %% (vector
  13677. %% (lambda: () : Integer x)
  13678. %% (lambda: () : Void (set! x (+ 1 x)))))
  13679. %% (let ([counter (f 0)])
  13680. %% (let ([get (vector-ref counter 0)])
  13681. %% (let ([inc (vector-ref counter 1)])
  13682. %% (begin
  13683. %% (inc)
  13684. %% (get)))))
  13685. %% \end{lstlisting}
  13686. \begin{lstlisting}
  13687. (define (f []) : Integer
  13688. (let ([x 0])
  13689. (let ([g (lambda: () : Integer x)])
  13690. (begin
  13691. (set! x 42)
  13692. g))))
  13693. ((f))
  13694. \end{lstlisting}
  13695. \fi}
  13696. {\if\edition\pythonEd
  13697. % counter.py
  13698. \begin{lstlisting}
  13699. def f():
  13700. x = 0
  13701. g = lambda: x
  13702. x = 42
  13703. return g
  13704. print( f()() )
  13705. \end{lstlisting}
  13706. \fi}
  13707. \end{minipage}
  13708. \end{center}
  13709. In this example, the lifetime of \code{x} extends beyond the lifetime
  13710. of the call to \code{f}. Thus, if we were to store \code{x} on the
  13711. stack frame for the call to \code{f}, it would be gone by the time we
  13712. call \code{g}, leaving us with dangling pointers for
  13713. \code{x}. This example demonstrates that when a variable occurs free
  13714. inside a function, its lifetime becomes indefinite. Thus, the value of
  13715. the variable needs to live on the heap. The verb
  13716. \emph{box}\index{subject}{box} is often used for allocating a single
  13717. value on the heap, producing a pointer, and
  13718. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  13719. {\if\edition\racketEd
  13720. We recommend solving these problems by boxing the local variables that
  13721. are in the intersection of 1) variables that appear on the
  13722. left-hand-side of a \code{set!} and 2) variables that occur free
  13723. inside a \code{lambda}.
  13724. \fi}
  13725. {\if\edition\pythonEd
  13726. We recommend solving these problems by boxing the local variables that
  13727. are in the intersection of 1) variables whose values may change and 2)
  13728. variables that occur free inside a \code{lambda}.
  13729. \fi}
  13730. We shall introduce a new pass named
  13731. \code{convert\_assignments} in Section~\ref{sec:convert-assignments}
  13732. to perform this translation. But before diving into the compiler
  13733. passes, we one more problem to discuss.
  13734. \section{Reveal Functions and the $F_2$ language}
  13735. \label{sec:reveal-functions-r5}
  13736. To support the \code{procedure-arity} operator we need to communicate
  13737. the arity of a function to the point of closure creation. We can
  13738. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  13739. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  13740. output of this pass is the language $F_2$, whose syntax is defined in
  13741. Figure~\ref{fig:f2-syntax}.
  13742. \begin{figure}[tp]
  13743. \centering
  13744. \fbox{
  13745. \begin{minipage}{0.96\textwidth}
  13746. \[
  13747. \begin{array}{lcl}
  13748. \Exp &::=& \ldots \MID \FUNREFARITY{\Var}{\Int}\\
  13749. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13750. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  13751. \end{array}
  13752. \]
  13753. \end{minipage}
  13754. }
  13755. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  13756. (Figure~\ref{fig:Rlam-syntax}).}
  13757. \label{fig:f2-syntax}
  13758. \end{figure}
  13759. \section{Convert Assignments}
  13760. \label{sec:convert-assignments}
  13761. [UNDER CONSTRUCTION: This section was just moved into this location
  13762. and may need to be updated. -Jeremy]
  13763. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  13764. the combination of assignments and lexically-scoped functions requires
  13765. that we box those variables that are both assigned-to and that appear
  13766. free inside a \code{lambda}. The purpose of the
  13767. \code{convert-assignments} pass is to carry out that transformation.
  13768. We recommend placing this pass after \code{uniquify} but before
  13769. \code{reveal\_functions}.
  13770. Consider again the first example from
  13771. Section~\ref{sec:assignment-scoping}:
  13772. \begin{lstlisting}
  13773. (let ([x 0])
  13774. (let ([y 0])
  13775. (let ([z 20])
  13776. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  13777. (begin
  13778. (set! x 10)
  13779. (set! y 12)
  13780. (f y))))))
  13781. \end{lstlisting}
  13782. The variables \code{x} and \code{y} are assigned-to. The variables
  13783. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  13784. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  13785. The boxing of \code{x} consists of three transformations: initialize
  13786. \code{x} with a vector, replace reads from \code{x} with
  13787. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  13788. \code{vector-set!}. The output of \code{convert-assignments} for this
  13789. example is as follows.
  13790. \begin{lstlisting}
  13791. (define (main) : Integer
  13792. (let ([x0 (vector 0)])
  13793. (let ([y1 0])
  13794. (let ([z2 20])
  13795. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  13796. (+ a3 (+ (vector-ref x0 0) z2)))])
  13797. (begin
  13798. (vector-set! x0 0 10)
  13799. (set! y1 12)
  13800. (f4 y1)))))))
  13801. \end{lstlisting}
  13802. \paragraph{Assigned \& Free}
  13803. We recommend defining an auxiliary function named
  13804. \code{assigned\&free} that takes an expression and simultaneously
  13805. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  13806. that occur free within lambda's, and 3) a new version of the
  13807. expression that records which bound variables occurred in the
  13808. intersection of $A$ and $F$. You can use the struct
  13809. \code{AssignedFree} to do this. Consider the case for
  13810. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  13811. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  13812. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  13813. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  13814. \begin{lstlisting}
  13815. (Let |$x$| |$rhs$| |$body$|)
  13816. |$\Rightarrow$|
  13817. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  13818. \end{lstlisting}
  13819. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  13820. The set of assigned variables for this \code{Let} is
  13821. $A_r \cup (A_b - \{x\})$
  13822. and the set of variables free in lambda's is
  13823. $F_r \cup (F_b - \{x\})$.
  13824. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  13825. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  13826. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  13827. and $F_r$.
  13828. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  13829. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  13830. recursively processing \itm{body}. Wrap each of parameter that occurs
  13831. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  13832. Let $P$ be the set of parameter names in \itm{params}. The result is
  13833. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  13834. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  13835. variables of an expression (see Chapter~\ref{ch:Rlam}).
  13836. \paragraph{Convert Assignments}
  13837. Next we discuss the \code{convert-assignment} pass with its auxiliary
  13838. functions for expressions and definitions. The function for
  13839. expressions, \code{cnvt-assign-exp}, should take an expression and a
  13840. set of assigned-and-free variables (obtained from the result of
  13841. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  13842. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  13843. \code{vector-ref}.
  13844. \begin{lstlisting}
  13845. (Var |$x$|)
  13846. |$\Rightarrow$|
  13847. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  13848. \end{lstlisting}
  13849. %
  13850. In the case for $\LET{\LP\code{AssignedFree}\,
  13851. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  13852. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  13853. \itm{body'} but with $x$ added to the set of assigned-and-free
  13854. variables. Translate the let-expression as follows to bind $x$ to a
  13855. boxed value.
  13856. \begin{lstlisting}
  13857. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  13858. |$\Rightarrow$|
  13859. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  13860. \end{lstlisting}
  13861. %
  13862. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  13863. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  13864. variables, translate the \code{set!} into a \code{vector-set!}
  13865. as follows.
  13866. \begin{lstlisting}
  13867. (SetBang |$x$| |$\itm{rhs}$|)
  13868. |$\Rightarrow$|
  13869. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  13870. \end{lstlisting}
  13871. %
  13872. The case for \code{Lambda} is non-trivial, but it is similar to the
  13873. case for function definitions, which we discuss next.
  13874. The auxiliary function for definitions, \code{cnvt-assign-def},
  13875. applies assignment conversion to function definitions.
  13876. We translate a function definition as follows.
  13877. \begin{lstlisting}
  13878. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  13879. |$\Rightarrow$|
  13880. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  13881. \end{lstlisting}
  13882. So it remains to explain \itm{params'} and $\itm{body}_4$.
  13883. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  13884. \code{assigned\&free} on $\itm{body_1}$.
  13885. Let $P$ be the parameter names in \itm{params}.
  13886. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  13887. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  13888. as the set of assigned-and-free variables.
  13889. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  13890. in a sequence of let-expressions that box the parameters
  13891. that are in $A_b \cap F_b$.
  13892. %
  13893. Regarding \itm{params'}, change the names of the parameters that are
  13894. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  13895. variables can retain the original names). Recall the second example in
  13896. Section~\ref{sec:assignment-scoping} involving a counter
  13897. abstraction. The following is the output of assignment version for
  13898. function \code{f}.
  13899. \begin{lstlisting}
  13900. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  13901. (vector
  13902. (lambda: () : Integer x1)
  13903. (lambda: () : Void (set! x1 (+ 1 x1)))))
  13904. |$\Rightarrow$|
  13905. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  13906. (let ([x1 (vector param_x1)])
  13907. (vector (lambda: () : Integer (vector-ref x1 0))
  13908. (lambda: () : Void
  13909. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  13910. \end{lstlisting}
  13911. \section{Closure Conversion}
  13912. \label{sec:closure-conversion}
  13913. \index{subject}{closure conversion}
  13914. The compiling of lexically-scoped functions into top-level function
  13915. definitions is accomplished in the pass \code{convert-to-closures}
  13916. that comes after \code{reveal\_functions} and before
  13917. \code{limit-functions}.
  13918. As usual, we implement the pass as a recursive function over the
  13919. AST. All of the action is in the cases for \key{Lambda} and
  13920. \key{Apply}. We transform a \key{Lambda} expression into an expression
  13921. that creates a closure, that is, a vector whose first element is a
  13922. function pointer and the rest of the elements are the free variables
  13923. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  13924. using \code{vector} so that we can distinguish closures from vectors
  13925. in Section~\ref{sec:optimize-closures} and to record the arity. In
  13926. the generated code below, the \itm{name} is a unique symbol generated
  13927. to identify the function and the \itm{arity} is the number of
  13928. parameters (the length of \itm{ps}).
  13929. \begin{lstlisting}
  13930. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  13931. |$\Rightarrow$|
  13932. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  13933. \end{lstlisting}
  13934. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  13935. create a top-level function definition for each \key{Lambda}, as
  13936. shown below.\\
  13937. \begin{minipage}{0.8\textwidth}
  13938. \begin{lstlisting}
  13939. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  13940. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  13941. ...
  13942. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  13943. |\itm{body'}|)...))
  13944. \end{lstlisting}
  13945. \end{minipage}\\
  13946. The \code{clos} parameter refers to the closure. Translate the type
  13947. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  13948. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  13949. $\itm{fvts}$ are the types of the free variables in the lambda and the
  13950. underscore \code{\_} is a dummy type that we use because it is rather
  13951. difficult to give a type to the function in the closure's
  13952. type.\footnote{To give an accurate type to a closure, we would need to
  13953. add existential types to the type checker~\citep{Minamide:1996ys}.}
  13954. The dummy type is considered to be equal to any other type during type
  13955. checking. The sequence of \key{Let} forms bind the free variables to
  13956. their values obtained from the closure.
  13957. Closure conversion turns functions into vectors, so the type
  13958. annotations in the program must also be translated. We recommend
  13959. defining a auxiliary recursive function for this purpose. Function
  13960. types should be translated as follows.
  13961. \begin{lstlisting}
  13962. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  13963. |$\Rightarrow$|
  13964. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  13965. \end{lstlisting}
  13966. The above type says that the first thing in the vector is a function
  13967. pointer. The first parameter of the function pointer is a vector (a
  13968. closure) and the rest of the parameters are the ones from the original
  13969. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  13970. the closure omits the types of the free variables because 1) those
  13971. types are not available in this context and 2) we do not need them in
  13972. the code that is generated for function application.
  13973. We transform function application into code that retrieves the
  13974. function pointer from the closure and then calls the function, passing
  13975. in the closure as the first argument. We bind $e'$ to a temporary
  13976. variable to avoid code duplication.
  13977. \begin{lstlisting}
  13978. (Apply |$e$| |\itm{es}|)
  13979. |$\Rightarrow$|
  13980. (Let |\itm{tmp}| |$e'$|
  13981. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  13982. \end{lstlisting}
  13983. There is also the question of what to do with references top-level
  13984. function definitions. To maintain a uniform translation of function
  13985. application, we turn function references into closures.
  13986. \begin{tabular}{lll}
  13987. \begin{minipage}{0.3\textwidth}
  13988. \begin{lstlisting}
  13989. (FunRefArity |$f$| |$n$|)
  13990. \end{lstlisting}
  13991. \end{minipage}
  13992. &
  13993. $\Rightarrow$
  13994. &
  13995. \begin{minipage}{0.5\textwidth}
  13996. \begin{lstlisting}
  13997. (Closure |$n$| (FunRef |$f$|) '())
  13998. \end{lstlisting}
  13999. \end{minipage}
  14000. \end{tabular} \\
  14001. %
  14002. The top-level function definitions need to be updated as well to take
  14003. an extra closure parameter.
  14004. \section{An Example Translation}
  14005. \label{sec:example-lambda}
  14006. Figure~\ref{fig:lexical-functions-example} shows the result of
  14007. \code{reveal\_functions} and \code{convert-to-closures} for the example
  14008. program demonstrating lexical scoping that we discussed at the
  14009. beginning of this chapter.
  14010. \begin{figure}[tbp]
  14011. \begin{minipage}{0.8\textwidth}
  14012. % tests/lambda_test_6.rkt
  14013. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14014. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  14015. (let ([y8 4])
  14016. (lambda: ([z9 : Integer]) : Integer
  14017. (+ x7 (+ y8 z9)))))
  14018. (define (main) : Integer
  14019. (let ([g0 ((fun-ref-arity f6 1) 5)])
  14020. (let ([h1 ((fun-ref-arity f6 1) 3)])
  14021. (+ (g0 11) (h1 15)))))
  14022. \end{lstlisting}
  14023. $\Rightarrow$
  14024. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14025. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  14026. (let ([y8 4])
  14027. (closure 1 (list (fun-ref lambda2) x7 y8))))
  14028. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  14029. (let ([x7 (vector-ref fvs3 1)])
  14030. (let ([y8 (vector-ref fvs3 2)])
  14031. (+ x7 (+ y8 z9)))))
  14032. (define (main) : Integer
  14033. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  14034. ((vector-ref clos5 0) clos5 5))])
  14035. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  14036. ((vector-ref clos6 0) clos6 3))])
  14037. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  14038. \end{lstlisting}
  14039. \end{minipage}
  14040. \caption{Example of closure conversion.}
  14041. \label{fig:lexical-functions-example}
  14042. \end{figure}
  14043. \begin{exercise}\normalfont
  14044. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  14045. Create 5 new programs that use \key{lambda} functions and make use of
  14046. lexical scoping. Test your compiler on these new programs and all of
  14047. your previously created test programs.
  14048. \end{exercise}
  14049. \section{Expose Allocation}
  14050. \label{sec:expose-allocation-r5}
  14051. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  14052. that allocates and initializes a vector, similar to the translation of
  14053. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  14054. The only difference is replacing the use of
  14055. \ALLOC{\itm{len}}{\itm{type}} with
  14056. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  14057. \section{Explicate Control and \LangCLam{}}
  14058. \label{sec:explicate-r5}
  14059. The output language of \code{explicate\_control} is \LangCLam{} whose
  14060. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  14061. difference with respect to \LangCFun{} is the addition of the
  14062. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  14063. of \code{AllocateClosure} in the \code{explicate\_control} pass is
  14064. similar to the handling of other expressions such as primitive
  14065. operators.
  14066. \begin{figure}[tp]
  14067. \fbox{
  14068. \begin{minipage}{0.96\textwidth}
  14069. \small
  14070. {\if\edition\racketEd
  14071. \[
  14072. \begin{array}{lcl}
  14073. \Exp &::= & \ldots
  14074. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  14075. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  14076. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  14077. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  14078. \MID \GOTO{\itm{label}} } \\
  14079. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  14080. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  14081. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  14082. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  14083. \end{array}
  14084. \]
  14085. \fi}
  14086. \end{minipage}
  14087. }
  14088. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  14089. \label{fig:c4-syntax}
  14090. \end{figure}
  14091. \section{Select Instructions}
  14092. \label{sec:select-instructions-Rlambda}
  14093. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  14094. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  14095. (Section~\ref{sec:select-instructions-gc}). The only difference is
  14096. that you should place the \itm{arity} in the tag that is stored at
  14097. position $0$ of the vector. Recall that in
  14098. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  14099. was not used. We store the arity in the $5$ bits starting at position
  14100. $58$.
  14101. Compile the \code{procedure-arity} operator into a sequence of
  14102. instructions that access the tag from position $0$ of the vector and
  14103. extract the $5$-bits starting at position $58$ from the tag.
  14104. \begin{figure}[p]
  14105. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14106. \node (Rfun) at (0,2) {\large \LangLam{}};
  14107. \node (Rfun-2) at (3,2) {\large \LangLam{}};
  14108. \node (Rfun-3) at (6,2) {\large \LangLam{}};
  14109. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  14110. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  14111. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  14112. \node (F1-3) at (6,0) {\large \LangFunRef{}};
  14113. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  14114. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14115. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  14116. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14117. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14118. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14119. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14120. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14121. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14122. \path[->,bend left=15] (Rfun) edge [above] node
  14123. {\ttfamily\footnotesize shrink} (Rfun-2);
  14124. \path[->,bend left=15] (Rfun-2) edge [above] node
  14125. {\ttfamily\footnotesize uniquify} (Rfun-3);
  14126. \path[->,bend left=15] (Rfun-3) edge [above] node
  14127. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  14128. \path[->,bend left=15] (F1-0) edge [right] node
  14129. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  14130. \path[->,bend left=15] (F1-1) edge [below] node
  14131. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  14132. \path[->,bend right=15] (F1-2) edge [above] node
  14133. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  14134. \path[->,bend right=15] (F1-3) edge [above] node
  14135. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  14136. \path[->,bend right=15] (F1-4) edge [above] node
  14137. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  14138. \path[->,bend right=15] (F1-5) edge [right] node
  14139. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14140. \path[->,bend left=15] (C3-2) edge [left] node
  14141. {\ttfamily\footnotesize select\_instr.} (x86-2);
  14142. \path[->,bend right=15] (x86-2) edge [left] node
  14143. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14144. \path[->,bend right=15] (x86-2-1) edge [below] node
  14145. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  14146. \path[->,bend right=15] (x86-2-2) edge [left] node
  14147. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  14148. \path[->,bend left=15] (x86-3) edge [above] node
  14149. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  14150. \path[->,bend left=15] (x86-4) edge [right] node
  14151. {\ttfamily\footnotesize print\_x86} (x86-5);
  14152. \end{tikzpicture}
  14153. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  14154. functions.}
  14155. \label{fig:Rlambda-passes}
  14156. \end{figure}
  14157. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  14158. for the compilation of \LangLam{}.
  14159. \clearpage
  14160. \section{Challenge: Optimize Closures}
  14161. \label{sec:optimize-closures}
  14162. In this chapter we compiled lexically-scoped functions into a
  14163. relatively efficient representation: flat closures. However, even this
  14164. representation comes with some overhead. For example, consider the
  14165. following program with a function \code{tail\_sum} that does not have
  14166. any free variables and where all the uses of \code{tail\_sum} are in
  14167. applications where we know that only \code{tail\_sum} is being applied
  14168. (and not any other functions).
  14169. \begin{center}
  14170. \begin{minipage}{0.95\textwidth}
  14171. \begin{lstlisting}
  14172. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  14173. (if (eq? n 0)
  14174. r
  14175. (tail_sum (- n 1) (+ n r))))
  14176. (+ (tail_sum 5 0) 27)
  14177. \end{lstlisting}
  14178. \end{minipage}
  14179. \end{center}
  14180. As described in this chapter, we uniformly apply closure conversion to
  14181. all functions, obtaining the following output for this program.
  14182. \begin{center}
  14183. \begin{minipage}{0.95\textwidth}
  14184. \begin{lstlisting}
  14185. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  14186. (if (eq? n2 0)
  14187. r3
  14188. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  14189. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  14190. (define (main) : Integer
  14191. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  14192. ((vector-ref clos6 0) clos6 5 0)) 27))
  14193. \end{lstlisting}
  14194. \end{minipage}
  14195. \end{center}
  14196. In the previous Chapter, there would be no allocation in the program
  14197. and the calls to \code{tail\_sum} would be direct calls. In contrast,
  14198. the above program allocates memory for each \code{closure} and the
  14199. calls to \code{tail\_sum} are indirect. These two differences incur
  14200. considerable overhead in a program such as this one, where the
  14201. allocations and indirect calls occur inside a tight loop.
  14202. One might think that this problem is trivial to solve: can't we just
  14203. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  14204. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  14205. e'_n$)} instead of treating it like a call to a closure? We would
  14206. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  14207. %
  14208. However, this problem is not so trivial because a global function may
  14209. ``escape'' and become involved in applications that also involve
  14210. closures. Consider the following example in which the application
  14211. \code{(f 41)} needs to be compiled into a closure application, because
  14212. the \code{lambda} may get bound to \code{f}, but the \code{inc}
  14213. function might also get bound to \code{f}.
  14214. \begin{lstlisting}
  14215. (define (inc [x : Integer]) : Integer
  14216. (+ x 1))
  14217. (let ([y (read)])
  14218. (let ([f (if (eq? (read) 0)
  14219. inc
  14220. (lambda: ([x : Integer]) : Integer (- x y)))])
  14221. (f 41)))
  14222. \end{lstlisting}
  14223. If a global function name is used in any way other than as the
  14224. operator in a direct call, then we say that the function
  14225. \emph{escapes}. If a global function does not escape, then we do not
  14226. need to perform closure conversion on the function.
  14227. \begin{exercise}\normalfont
  14228. Implement an auxiliary function for detecting which global
  14229. functions escape. Using that function, implement an improved version
  14230. of closure conversion that does not apply closure conversion to
  14231. global functions that do not escape but instead compiles them as
  14232. regular functions. Create several new test cases that check whether
  14233. you properly detect whether global functions escape or not.
  14234. \end{exercise}
  14235. So far we have reduced the overhead of calling global functions, but
  14236. it would also be nice to reduce the overhead of calling a
  14237. \code{lambda} when we can determine at compile time which
  14238. \code{lambda} will be called. We refer to such calls as \emph{known
  14239. calls}. Consider the following example in which a \code{lambda} is
  14240. bound to \code{f} and then applied.
  14241. \begin{lstlisting}
  14242. (let ([y (read)])
  14243. (let ([f (lambda: ([x : Integer]) : Integer
  14244. (+ x y))])
  14245. (f 21)))
  14246. \end{lstlisting}
  14247. Closure conversion compiles \code{(f 21)} into an indirect call:
  14248. \begin{lstlisting}
  14249. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  14250. (let ([y2 (vector-ref fvs6 1)])
  14251. (+ x3 y2)))
  14252. (define (main) : Integer
  14253. (let ([y2 (read)])
  14254. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  14255. ((vector-ref f4 0) f4 21))))
  14256. \end{lstlisting}
  14257. but we can instead compile the application \code{(f 21)} into a direct call
  14258. to \code{lambda5}:
  14259. \begin{lstlisting}
  14260. (define (main) : Integer
  14261. (let ([y2 (read)])
  14262. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  14263. ((fun-ref lambda5) f4 21))))
  14264. \end{lstlisting}
  14265. The problem of determining which lambda will be called from a
  14266. particular application is quite challenging in general and the topic
  14267. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  14268. following exercise we recommend that you compile an application to a
  14269. direct call when the operator is a variable and the variable is
  14270. \code{let}-bound to a closure. This can be accomplished by maintaining
  14271. an environment mapping \code{let}-bound variables to function names.
  14272. Extend the environment whenever you encounter a closure on the
  14273. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  14274. to the name of the global function for the closure. This pass should
  14275. come after closure conversion.
  14276. \begin{exercise}\normalfont
  14277. Implement a compiler pass, named \code{optimize-known-calls}, that
  14278. compiles known calls into direct calls. Verify that your compiler is
  14279. successful in this regard on several example programs.
  14280. \end{exercise}
  14281. These exercises only scratches the surface of optimizing of
  14282. closures. A good next step for the interested reader is to look at the
  14283. work of \citet{Keep:2012ab}.
  14284. \section{Further Reading}
  14285. The notion of lexically scoped anonymous functions predates modern
  14286. computers by about a decade. They were invented by
  14287. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  14288. foundation for logic. Anonymous functions were included in the
  14289. LISP~\citep{McCarthy:1960dz} programming language but were initially
  14290. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  14291. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  14292. compile Scheme programs. However, environments were represented as
  14293. linked lists, so variable lookup was linear in the size of the
  14294. environment. In this chapter we represent environments using flat
  14295. closures, which were invented by
  14296. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  14297. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  14298. closures, variable lookup is constant time but the time to create a
  14299. closure is proportional to the number of its free variables. Flat
  14300. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  14301. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  14302. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14303. \chapter{Dynamic Typing}
  14304. \label{ch:Rdyn}
  14305. \index{subject}{dynamic typing}
  14306. \if\edition\racketEd
  14307. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  14308. typed language that is a subset of Racket. This is in contrast to the
  14309. previous chapters, which have studied the compilation of Typed
  14310. Racket. In dynamically typed languages such as \LangDyn{}, a given
  14311. expression may produce a value of a different type each time it is
  14312. executed. Consider the following example with a conditional \code{if}
  14313. expression that may return a Boolean or an integer depending on the
  14314. input to the program.
  14315. % part of dynamic_test_25.rkt
  14316. \begin{lstlisting}
  14317. (not (if (eq? (read) 1) #f 0))
  14318. \end{lstlisting}
  14319. Languages that allow expressions to produce different kinds of values
  14320. are called \emph{polymorphic}, a word composed of the Greek roots
  14321. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  14322. are several kinds of polymorphism in programming languages, such as
  14323. subtype polymorphism and parametric
  14324. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  14325. study in this chapter does not have a special name but it is the kind
  14326. that arises in dynamically typed languages.
  14327. Another characteristic of dynamically typed languages is that
  14328. primitive operations, such as \code{not}, are often defined to operate
  14329. on many different types of values. In fact, in Racket, the \code{not}
  14330. operator produces a result for any kind of value: given \code{\#f} it
  14331. returns \code{\#t} and given anything else it returns \code{\#f}.
  14332. Furthermore, even when primitive operations restrict their inputs to
  14333. values of a certain type, this restriction is enforced at runtime
  14334. instead of during compilation. For example, the following vector
  14335. reference results in a run-time contract violation because the index
  14336. must be in integer, not a Boolean such as \code{\#t}.
  14337. \begin{lstlisting}
  14338. (vector-ref (vector 42) #t)
  14339. \end{lstlisting}
  14340. \begin{figure}[tp]
  14341. \centering
  14342. \fbox{
  14343. \begin{minipage}{0.97\textwidth}
  14344. \[
  14345. \begin{array}{rcl}
  14346. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  14347. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  14348. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  14349. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  14350. &\MID& \key{\#t} \MID \key{\#f}
  14351. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  14352. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  14353. \MID \CUNIOP{\key{not}}{\Exp} \\
  14354. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  14355. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  14356. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  14357. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  14358. &\MID& \LP\Exp \; \Exp\ldots\RP
  14359. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  14360. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  14361. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  14362. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  14363. \LangDynM{} &::=& \Def\ldots\; \Exp
  14364. \end{array}
  14365. \]
  14366. \end{minipage}
  14367. }
  14368. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  14369. \label{fig:r7-concrete-syntax}
  14370. \end{figure}
  14371. \begin{figure}[tp]
  14372. \centering
  14373. \fbox{
  14374. \begin{minipage}{0.96\textwidth}
  14375. \small
  14376. \[
  14377. \begin{array}{lcl}
  14378. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  14379. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  14380. &\MID& \BOOL{\itm{bool}}
  14381. \MID \IF{\Exp}{\Exp}{\Exp} \\
  14382. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  14383. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  14384. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  14385. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  14386. \end{array}
  14387. \]
  14388. \end{minipage}
  14389. }
  14390. \caption{The abstract syntax of \LangDyn{}.}
  14391. \label{fig:r7-syntax}
  14392. \end{figure}
  14393. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  14394. defined in Figures~\ref{fig:r7-concrete-syntax} and
  14395. \ref{fig:r7-syntax}.
  14396. %
  14397. There is no type checker for \LangDyn{} because it is not a statically
  14398. typed language (it's dynamically typed!).
  14399. The definitional interpreter for \LangDyn{} is presented in
  14400. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  14401. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  14402. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  14403. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  14404. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  14405. value} that combines an underlying value with a tag that identifies
  14406. what kind of value it is. We define the following struct
  14407. to represented tagged values.
  14408. \begin{lstlisting}
  14409. (struct Tagged (value tag) #:transparent)
  14410. \end{lstlisting}
  14411. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  14412. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  14413. but don't always capture all the information that a type does. For
  14414. example, a vector of type \code{(Vector Any Any)} is tagged with
  14415. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  14416. is tagged with \code{Procedure}.
  14417. Next consider the match case for \code{vector-ref}. The
  14418. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  14419. is used to ensure that the first argument is a vector and the second
  14420. is an integer. If they are not, a \code{trapped-error} is raised.
  14421. Recall from Section~\ref{sec:interp_Lint} that when a definition
  14422. interpreter raises a \code{trapped-error} error, the compiled code
  14423. must also signal an error by exiting with return code \code{255}. A
  14424. \code{trapped-error} is also raised if the index is not less than
  14425. length of the vector.
  14426. \begin{figure}[tbp]
  14427. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14428. (define ((interp-Rdyn-exp env) ast)
  14429. (define recur (interp-Rdyn-exp env))
  14430. (match ast
  14431. [(Var x) (lookup x env)]
  14432. [(Int n) (Tagged n 'Integer)]
  14433. [(Bool b) (Tagged b 'Boolean)]
  14434. [(Lambda xs rt body)
  14435. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  14436. [(Prim 'vector es)
  14437. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  14438. [(Prim 'vector-ref (list e1 e2))
  14439. (define vec (recur e1)) (define i (recur e2))
  14440. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  14441. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  14442. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  14443. (vector-ref (Tagged-value vec) (Tagged-value i))]
  14444. [(Prim 'vector-set! (list e1 e2 e3))
  14445. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  14446. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  14447. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  14448. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  14449. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  14450. (Tagged (void) 'Void)]
  14451. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  14452. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  14453. [(Prim 'or (list e1 e2))
  14454. (define v1 (recur e1))
  14455. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  14456. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  14457. [(Prim op (list e1))
  14458. #:when (set-member? type-predicates op)
  14459. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  14460. [(Prim op es)
  14461. (define args (map recur es))
  14462. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  14463. (unless (for/or ([expected-tags (op-tags op)])
  14464. (equal? expected-tags tags))
  14465. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  14466. (tag-value
  14467. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  14468. [(If q t f)
  14469. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  14470. [(Apply f es)
  14471. (define new-f (recur f)) (define args (map recur es))
  14472. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  14473. (match f-val
  14474. [`(function ,xs ,body ,lam-env)
  14475. (unless (eq? (length xs) (length args))
  14476. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  14477. (define new-env (append (map cons xs args) lam-env))
  14478. ((interp-Rdyn-exp new-env) body)]
  14479. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  14480. \end{lstlisting}
  14481. \caption{Interpreter for the \LangDyn{} language.}
  14482. \label{fig:interp-Rdyn}
  14483. \end{figure}
  14484. \begin{figure}[tbp]
  14485. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14486. (define (interp-op op)
  14487. (match op
  14488. ['+ fx+]
  14489. ['- fx-]
  14490. ['read read-fixnum]
  14491. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  14492. ['< (lambda (v1 v2)
  14493. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  14494. ['<= (lambda (v1 v2)
  14495. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  14496. ['> (lambda (v1 v2)
  14497. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  14498. ['>= (lambda (v1 v2)
  14499. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  14500. ['boolean? boolean?]
  14501. ['integer? fixnum?]
  14502. ['void? void?]
  14503. ['vector? vector?]
  14504. ['vector-length vector-length]
  14505. ['procedure? (match-lambda
  14506. [`(functions ,xs ,body ,env) #t] [else #f])]
  14507. [else (error 'interp-op "unknown operator" op)]))
  14508. (define (op-tags op)
  14509. (match op
  14510. ['+ '((Integer Integer))]
  14511. ['- '((Integer Integer) (Integer))]
  14512. ['read '(())]
  14513. ['not '((Boolean))]
  14514. ['< '((Integer Integer))]
  14515. ['<= '((Integer Integer))]
  14516. ['> '((Integer Integer))]
  14517. ['>= '((Integer Integer))]
  14518. ['vector-length '((Vector))]))
  14519. (define type-predicates
  14520. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  14521. (define (tag-value v)
  14522. (cond [(boolean? v) (Tagged v 'Boolean)]
  14523. [(fixnum? v) (Tagged v 'Integer)]
  14524. [(procedure? v) (Tagged v 'Procedure)]
  14525. [(vector? v) (Tagged v 'Vector)]
  14526. [(void? v) (Tagged v 'Void)]
  14527. [else (error 'tag-value "unidentified value ~a" v)]))
  14528. (define (check-tag val expected ast)
  14529. (define tag (Tagged-tag val))
  14530. (unless (eq? tag expected)
  14531. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  14532. \end{lstlisting}
  14533. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  14534. \label{fig:interp-Rdyn-aux}
  14535. \end{figure}
  14536. \clearpage
  14537. \section{Representation of Tagged Values}
  14538. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  14539. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  14540. values at the bit level. Because almost every operation in \LangDyn{}
  14541. involves manipulating tagged values, the representation must be
  14542. efficient. Recall that all of our values are 64 bits. We shall steal
  14543. the 3 right-most bits to encode the tag. We use $001$ to identify
  14544. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  14545. and $101$ for the void value. We define the following auxiliary
  14546. function for mapping types to tag codes.
  14547. \begin{align*}
  14548. \itm{tagof}(\key{Integer}) &= 001 \\
  14549. \itm{tagof}(\key{Boolean}) &= 100 \\
  14550. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  14551. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  14552. \itm{tagof}(\key{Void}) &= 101
  14553. \end{align*}
  14554. This stealing of 3 bits comes at some price: our integers are reduced
  14555. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  14556. affect vectors and procedures because those values are addresses, and
  14557. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  14558. they are always $000$. Thus, we do not lose information by overwriting
  14559. the rightmost 3 bits with the tag and we can simply zero-out the tag
  14560. to recover the original address.
  14561. To make tagged values into first-class entities, we can give them a
  14562. type, called \code{Any}, and define operations such as \code{Inject}
  14563. and \code{Project} for creating and using them, yielding the \LangAny{}
  14564. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  14565. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  14566. in greater detail.
  14567. \section{The \LangAny{} Language}
  14568. \label{sec:Rany-lang}
  14569. \newcommand{\LAnyAST}{
  14570. \begin{array}{lcl}
  14571. \Type &::= & \key{Any} \\
  14572. \itm{op} &::= & \code{any-vector-length}
  14573. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  14574. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  14575. \MID \code{procedure?} \MID \code{void?} \\
  14576. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  14577. \end{array}
  14578. }
  14579. \begin{figure}[tp]
  14580. \centering
  14581. \fbox{
  14582. \begin{minipage}{0.96\textwidth}
  14583. \small
  14584. \[
  14585. \begin{array}{l}
  14586. \gray{\LintOpAST} \\ \hline
  14587. \gray{\LvarASTRacket{}} \\ \hline
  14588. \gray{\LifASTRacket{}} \\ \hline
  14589. \gray{\LwhileASTRacket{}} \\ \hline
  14590. \gray{\LtupASTRacket{}} \\ \hline
  14591. \gray{\LfunASTRacket} \\ \hline
  14592. \gray{\LlambdaASTRacket} \\ \hline
  14593. \LAnyAST \\
  14594. \begin{array}{lcl}
  14595. %% \Type &::= & \ldots \MID \key{Any} \\
  14596. %% \itm{op} &::= & \ldots \MID \code{any-vector-length}
  14597. %% \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  14598. %% &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  14599. %% \MID \code{procedure?} \MID \code{void?} \\
  14600. %% \Exp &::=& \ldots
  14601. %% \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  14602. %% &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  14603. %% \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  14604. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  14605. \end{array}
  14606. \end{array}
  14607. \]
  14608. \end{minipage}
  14609. }
  14610. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  14611. \label{fig:Rany-syntax}
  14612. \end{figure}
  14613. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  14614. (The concrete syntax of \LangAny{} is in the Appendix,
  14615. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  14616. converts the value produced by expression $e$ of type $T$ into a
  14617. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  14618. produced by expression $e$ into a value of type $T$ or else halts the
  14619. program if the type tag is not equivalent to $T$.
  14620. %
  14621. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  14622. restricted to a flat type $\FType$, which simplifies the
  14623. implementation and corresponds with what is needed for compiling \LangDyn{}.
  14624. The \code{any-vector} operators adapt the vector operations so that
  14625. they can be applied to a value of type \code{Any}. They also
  14626. generalize the vector operations in that the index is not restricted
  14627. to be a literal integer in the grammar but is allowed to be any
  14628. expression.
  14629. The type predicates such as \key{boolean?} expect their argument to
  14630. produce a tagged value; they return \key{\#t} if the tag corresponds
  14631. to the predicate and they return \key{\#f} otherwise.
  14632. The type checker for \LangAny{} is shown in
  14633. Figures~\ref{fig:type-check-Rany-part-1} and
  14634. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  14635. Figure~\ref{fig:type-check-Rany-aux}.
  14636. %
  14637. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  14638. auxiliary functions \code{apply-inject} and \code{apply-project} are
  14639. in Figure~\ref{fig:apply-project}.
  14640. \begin{figure}[btp]
  14641. \begin{lstlisting}[basicstyle=\ttfamily\small]
  14642. (define type-check-Rany_class
  14643. (class type-check-Rlambda_class
  14644. (super-new)
  14645. (inherit check-type-equal?)
  14646. (define/override (type-check-exp env)
  14647. (lambda (e)
  14648. (define recur (type-check-exp env))
  14649. (match e
  14650. [(Inject e1 ty)
  14651. (unless (flat-ty? ty)
  14652. (error 'type-check "may only inject from flat type, not ~a" ty))
  14653. (define-values (new-e1 e-ty) (recur e1))
  14654. (check-type-equal? e-ty ty e)
  14655. (values (Inject new-e1 ty) 'Any)]
  14656. [(Project e1 ty)
  14657. (unless (flat-ty? ty)
  14658. (error 'type-check "may only project to flat type, not ~a" ty))
  14659. (define-values (new-e1 e-ty) (recur e1))
  14660. (check-type-equal? e-ty 'Any e)
  14661. (values (Project new-e1 ty) ty)]
  14662. [(Prim 'any-vector-length (list e1))
  14663. (define-values (e1^ t1) (recur e1))
  14664. (check-type-equal? t1 'Any e)
  14665. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  14666. [(Prim 'any-vector-ref (list e1 e2))
  14667. (define-values (e1^ t1) (recur e1))
  14668. (define-values (e2^ t2) (recur e2))
  14669. (check-type-equal? t1 'Any e)
  14670. (check-type-equal? t2 'Integer e)
  14671. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  14672. [(Prim 'any-vector-set! (list e1 e2 e3))
  14673. (define-values (e1^ t1) (recur e1))
  14674. (define-values (e2^ t2) (recur e2))
  14675. (define-values (e3^ t3) (recur e3))
  14676. (check-type-equal? t1 'Any e)
  14677. (check-type-equal? t2 'Integer e)
  14678. (check-type-equal? t3 'Any e)
  14679. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  14680. \end{lstlisting}
  14681. \caption{Type checker for the \LangAny{} language, part 1.}
  14682. \label{fig:type-check-Rany-part-1}
  14683. \end{figure}
  14684. \begin{figure}[btp]
  14685. \begin{lstlisting}[basicstyle=\ttfamily\small]
  14686. [(ValueOf e ty)
  14687. (define-values (new-e e-ty) (recur e))
  14688. (values (ValueOf new-e ty) ty)]
  14689. [(Prim pred (list e1))
  14690. #:when (set-member? (type-predicates) pred)
  14691. (define-values (new-e1 e-ty) (recur e1))
  14692. (check-type-equal? e-ty 'Any e)
  14693. (values (Prim pred (list new-e1)) 'Boolean)]
  14694. [(If cnd thn els)
  14695. (define-values (cnd^ Tc) (recur cnd))
  14696. (define-values (thn^ Tt) (recur thn))
  14697. (define-values (els^ Te) (recur els))
  14698. (check-type-equal? Tc 'Boolean cnd)
  14699. (check-type-equal? Tt Te e)
  14700. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  14701. [(Exit) (values (Exit) '_)]
  14702. [(Prim 'eq? (list arg1 arg2))
  14703. (define-values (e1 t1) (recur arg1))
  14704. (define-values (e2 t2) (recur arg2))
  14705. (match* (t1 t2)
  14706. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  14707. [(other wise) (check-type-equal? t1 t2 e)])
  14708. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  14709. [else ((super type-check-exp env) e)])))
  14710. ))
  14711. \end{lstlisting}
  14712. \caption{Type checker for the \LangAny{} language, part 2.}
  14713. \label{fig:type-check-Rany-part-2}
  14714. \end{figure}
  14715. \begin{figure}[tbp]
  14716. \begin{lstlisting}
  14717. (define/override (operator-types)
  14718. (append
  14719. '((integer? . ((Any) . Boolean))
  14720. (vector? . ((Any) . Boolean))
  14721. (procedure? . ((Any) . Boolean))
  14722. (void? . ((Any) . Boolean))
  14723. (tag-of-any . ((Any) . Integer))
  14724. (make-any . ((_ Integer) . Any))
  14725. )
  14726. (super operator-types)))
  14727. (define/public (type-predicates)
  14728. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  14729. (define/public (combine-types t1 t2)
  14730. (match (list t1 t2)
  14731. [(list '_ t2) t2]
  14732. [(list t1 '_) t1]
  14733. [(list `(Vector ,ts1 ...)
  14734. `(Vector ,ts2 ...))
  14735. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  14736. (combine-types t1 t2)))]
  14737. [(list `(,ts1 ... -> ,rt1)
  14738. `(,ts2 ... -> ,rt2))
  14739. `(,@(for/list ([t1 ts1] [t2 ts2])
  14740. (combine-types t1 t2))
  14741. -> ,(combine-types rt1 rt2))]
  14742. [else t1]))
  14743. (define/public (flat-ty? ty)
  14744. (match ty
  14745. [(or `Integer `Boolean '_ `Void) #t]
  14746. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  14747. [`(,ts ... -> ,rt)
  14748. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  14749. [else #f]))
  14750. \end{lstlisting}
  14751. \caption{Auxiliary methods for type checking \LangAny{}.}
  14752. \label{fig:type-check-Rany-aux}
  14753. \end{figure}
  14754. \begin{figure}[btp]
  14755. \begin{lstlisting}
  14756. (define interp-Rany_class
  14757. (class interp-Rlambda_class
  14758. (super-new)
  14759. (define/override (interp-op op)
  14760. (match op
  14761. ['boolean? (match-lambda
  14762. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  14763. [else #f])]
  14764. ['integer? (match-lambda
  14765. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  14766. [else #f])]
  14767. ['vector? (match-lambda
  14768. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  14769. [else #f])]
  14770. ['procedure? (match-lambda
  14771. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  14772. [else #f])]
  14773. ['eq? (match-lambda*
  14774. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  14775. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  14776. [ls (apply (super interp-op op) ls)])]
  14777. ['any-vector-ref (lambda (v i)
  14778. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  14779. ['any-vector-set! (lambda (v i a)
  14780. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  14781. ['any-vector-length (lambda (v)
  14782. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  14783. [else (super interp-op op)]))
  14784. (define/override ((interp-exp env) e)
  14785. (define recur (interp-exp env))
  14786. (match e
  14787. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  14788. [(Project e ty2) (apply-project (recur e) ty2)]
  14789. [else ((super interp-exp env) e)]))
  14790. ))
  14791. (define (interp-Rany p)
  14792. (send (new interp-Rany_class) interp-program p))
  14793. \end{lstlisting}
  14794. \caption{Interpreter for \LangAny{}.}
  14795. \label{fig:interp-Rany}
  14796. \end{figure}
  14797. \begin{figure}[tbp]
  14798. \begin{lstlisting}
  14799. (define/public (apply-inject v tg) (Tagged v tg))
  14800. (define/public (apply-project v ty2)
  14801. (define tag2 (any-tag ty2))
  14802. (match v
  14803. [(Tagged v1 tag1)
  14804. (cond
  14805. [(eq? tag1 tag2)
  14806. (match ty2
  14807. [`(Vector ,ts ...)
  14808. (define l1 ((interp-op 'vector-length) v1))
  14809. (cond
  14810. [(eq? l1 (length ts)) v1]
  14811. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  14812. l1 (length ts))])]
  14813. [`(,ts ... -> ,rt)
  14814. (match v1
  14815. [`(function ,xs ,body ,env)
  14816. (cond [(eq? (length xs) (length ts)) v1]
  14817. [else
  14818. (error 'apply-project "arity mismatch ~a != ~a"
  14819. (length xs) (length ts))])]
  14820. [else (error 'apply-project "expected function not ~a" v1)])]
  14821. [else v1])]
  14822. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  14823. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  14824. \end{lstlisting}
  14825. \caption{Auxiliary functions for injection and projection.}
  14826. \label{fig:apply-project}
  14827. \end{figure}
  14828. \clearpage
  14829. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  14830. \label{sec:compile-r7}
  14831. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  14832. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  14833. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  14834. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  14835. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  14836. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  14837. the Boolean \code{\#t}, which must be injected to produce an
  14838. expression of type \key{Any}.
  14839. %
  14840. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  14841. addition, is representative of compilation for many primitive
  14842. operations: the arguments have type \key{Any} and must be projected to
  14843. \key{Integer} before the addition can be performed.
  14844. The compilation of \key{lambda} (third row of
  14845. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  14846. produce type annotations: we simply use \key{Any}.
  14847. %
  14848. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  14849. has to account for some differences in behavior between \LangDyn{} and
  14850. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  14851. kind of values can be used in various places. For example, the
  14852. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  14853. the arguments need not be of the same type (in that case the
  14854. result is \code{\#f}).
  14855. \begin{figure}[btp]
  14856. \centering
  14857. \begin{tabular}{|lll|} \hline
  14858. \begin{minipage}{0.27\textwidth}
  14859. \begin{lstlisting}
  14860. #t
  14861. \end{lstlisting}
  14862. \end{minipage}
  14863. &
  14864. $\Rightarrow$
  14865. &
  14866. \begin{minipage}{0.65\textwidth}
  14867. \begin{lstlisting}
  14868. (inject #t Boolean)
  14869. \end{lstlisting}
  14870. \end{minipage}
  14871. \\[2ex]\hline
  14872. \begin{minipage}{0.27\textwidth}
  14873. \begin{lstlisting}
  14874. (+ |$e_1$| |$e_2$|)
  14875. \end{lstlisting}
  14876. \end{minipage}
  14877. &
  14878. $\Rightarrow$
  14879. &
  14880. \begin{minipage}{0.65\textwidth}
  14881. \begin{lstlisting}
  14882. (inject
  14883. (+ (project |$e'_1$| Integer)
  14884. (project |$e'_2$| Integer))
  14885. Integer)
  14886. \end{lstlisting}
  14887. \end{minipage}
  14888. \\[2ex]\hline
  14889. \begin{minipage}{0.27\textwidth}
  14890. \begin{lstlisting}
  14891. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  14892. \end{lstlisting}
  14893. \end{minipage}
  14894. &
  14895. $\Rightarrow$
  14896. &
  14897. \begin{minipage}{0.65\textwidth}
  14898. \begin{lstlisting}
  14899. (inject
  14900. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  14901. (Any|$\ldots$|Any -> Any))
  14902. \end{lstlisting}
  14903. \end{minipage}
  14904. \\[2ex]\hline
  14905. \begin{minipage}{0.27\textwidth}
  14906. \begin{lstlisting}
  14907. (|$e_0$| |$e_1 \ldots e_n$|)
  14908. \end{lstlisting}
  14909. \end{minipage}
  14910. &
  14911. $\Rightarrow$
  14912. &
  14913. \begin{minipage}{0.65\textwidth}
  14914. \begin{lstlisting}
  14915. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  14916. \end{lstlisting}
  14917. \end{minipage}
  14918. \\[2ex]\hline
  14919. \begin{minipage}{0.27\textwidth}
  14920. \begin{lstlisting}
  14921. (vector-ref |$e_1$| |$e_2$|)
  14922. \end{lstlisting}
  14923. \end{minipage}
  14924. &
  14925. $\Rightarrow$
  14926. &
  14927. \begin{minipage}{0.65\textwidth}
  14928. \begin{lstlisting}
  14929. (any-vector-ref |$e_1'$| |$e_2'$|)
  14930. \end{lstlisting}
  14931. \end{minipage}
  14932. \\[2ex]\hline
  14933. \begin{minipage}{0.27\textwidth}
  14934. \begin{lstlisting}
  14935. (if |$e_1$| |$e_2$| |$e_3$|)
  14936. \end{lstlisting}
  14937. \end{minipage}
  14938. &
  14939. $\Rightarrow$
  14940. &
  14941. \begin{minipage}{0.65\textwidth}
  14942. \begin{lstlisting}
  14943. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  14944. \end{lstlisting}
  14945. \end{minipage}
  14946. \\[2ex]\hline
  14947. \begin{minipage}{0.27\textwidth}
  14948. \begin{lstlisting}
  14949. (eq? |$e_1$| |$e_2$|)
  14950. \end{lstlisting}
  14951. \end{minipage}
  14952. &
  14953. $\Rightarrow$
  14954. &
  14955. \begin{minipage}{0.65\textwidth}
  14956. \begin{lstlisting}
  14957. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  14958. \end{lstlisting}
  14959. \end{minipage}
  14960. \\[2ex]\hline
  14961. \begin{minipage}{0.27\textwidth}
  14962. \begin{lstlisting}
  14963. (not |$e_1$|)
  14964. \end{lstlisting}
  14965. \end{minipage}
  14966. &
  14967. $\Rightarrow$
  14968. &
  14969. \begin{minipage}{0.65\textwidth}
  14970. \begin{lstlisting}
  14971. (if (eq? |$e'_1$| (inject #f Boolean))
  14972. (inject #t Boolean) (inject #f Boolean))
  14973. \end{lstlisting}
  14974. \end{minipage}
  14975. \\[2ex]\hline
  14976. \end{tabular}
  14977. \caption{Cast Insertion}
  14978. \label{fig:compile-r7-Rany}
  14979. \end{figure}
  14980. \section{Reveal Casts}
  14981. \label{sec:reveal-casts-Rany}
  14982. % TODO: define R'_6
  14983. In the \code{reveal-casts} pass we recommend compiling \code{project}
  14984. into an \code{if} expression that checks whether the value's tag
  14985. matches the target type; if it does, the value is converted to a value
  14986. of the target type by removing the tag; if it does not, the program
  14987. exits. To perform these actions we need a new primitive operation,
  14988. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  14989. The \code{tag-of-any} operation retrieves the type tag from a tagged
  14990. value of type \code{Any}. The \code{ValueOf} form retrieves the
  14991. underlying value from a tagged value. The \code{ValueOf} form
  14992. includes the type for the underlying value which is used by the type
  14993. checker. Finally, the \code{Exit} form ends the execution of the
  14994. program.
  14995. If the target type of the projection is \code{Boolean} or
  14996. \code{Integer}, then \code{Project} can be translated as follows.
  14997. \begin{center}
  14998. \begin{minipage}{1.0\textwidth}
  14999. \begin{lstlisting}
  15000. (Project |$e$| |$\FType$|)
  15001. |$\Rightarrow$|
  15002. (Let |$\itm{tmp}$| |$e'$|
  15003. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  15004. (Int |$\itm{tagof}(\FType)$|)))
  15005. (ValueOf |$\itm{tmp}$| |$\FType$|)
  15006. (Exit)))
  15007. \end{lstlisting}
  15008. \end{minipage}
  15009. \end{center}
  15010. If the target type of the projection is a vector or function type,
  15011. then there is a bit more work to do. For vectors, check that the
  15012. length of the vector type matches the length of the vector (using the
  15013. \code{vector-length} primitive). For functions, check that the number
  15014. of parameters in the function type matches the function's arity (using
  15015. \code{procedure-arity}).
  15016. Regarding \code{inject}, we recommend compiling it to a slightly
  15017. lower-level primitive operation named \code{make-any}. This operation
  15018. takes a tag instead of a type.
  15019. \begin{center}
  15020. \begin{minipage}{1.0\textwidth}
  15021. \begin{lstlisting}
  15022. (Inject |$e$| |$\FType$|)
  15023. |$\Rightarrow$|
  15024. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  15025. \end{lstlisting}
  15026. \end{minipage}
  15027. \end{center}
  15028. The type predicates (\code{boolean?}, etc.) can be translated into
  15029. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  15030. translation of \code{Project}.
  15031. The \code{any-vector-ref} and \code{any-vector-set!} operations
  15032. combine the projection action with the vector operation. Also, the
  15033. read and write operations allow arbitrary expressions for the index so
  15034. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  15035. cannot guarantee that the index is within bounds. Thus, we insert code
  15036. to perform bounds checking at runtime. The translation for
  15037. \code{any-vector-ref} is as follows and the other two operations are
  15038. translated in a similar way.
  15039. \begin{lstlisting}
  15040. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  15041. |$\Rightarrow$|
  15042. (Let |$v$| |$e'_1$|
  15043. (Let |$i$| |$e'_2$|
  15044. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  15045. (If (Prim '< (list (Var |$i$|)
  15046. (Prim 'any-vector-length (list (Var |$v$|)))))
  15047. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  15048. (Exit))))
  15049. \end{lstlisting}
  15050. \section{Remove Complex Operands}
  15051. \label{sec:rco-Rany}
  15052. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  15053. The subexpression of \code{ValueOf} must be atomic.
  15054. \section{Explicate Control and \LangCAny{}}
  15055. \label{sec:explicate-Rany}
  15056. The output of \code{explicate\_control} is the \LangCAny{} language whose
  15057. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  15058. form that we added to \LangAny{} remains an expression and the \code{Exit}
  15059. expression becomes a $\Tail$. Also, note that the index argument of
  15060. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  15061. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  15062. \begin{figure}[tp]
  15063. \fbox{
  15064. \begin{minipage}{0.96\textwidth}
  15065. \small
  15066. \[
  15067. \begin{array}{lcl}
  15068. \Exp &::= & \ldots
  15069. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  15070. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  15071. &\MID& \VALUEOF{\Exp}{\FType} \\
  15072. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  15073. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  15074. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  15075. \MID \GOTO{\itm{label}} } \\
  15076. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  15077. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  15078. \MID \LP\key{Exit}\RP \\
  15079. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  15080. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  15081. \end{array}
  15082. \]
  15083. \end{minipage}
  15084. }
  15085. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  15086. \label{fig:c5-syntax}
  15087. \end{figure}
  15088. \section{Select Instructions}
  15089. \label{sec:select-Rany}
  15090. In the \code{select\_instructions} pass we translate the primitive
  15091. operations on the \code{Any} type to x86 instructions that involve
  15092. manipulating the 3 tag bits of the tagged value.
  15093. \paragraph{Make-any}
  15094. We recommend compiling the \key{make-any} primitive as follows if the
  15095. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  15096. shifts the destination to the left by the number of bits specified its
  15097. source argument (in this case $3$, the length of the tag) and it
  15098. preserves the sign of the integer. We use the \key{orq} instruction to
  15099. combine the tag and the value to form the tagged value. \\
  15100. \begin{lstlisting}
  15101. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  15102. |$\Rightarrow$|
  15103. movq |$e'$|, |\itm{lhs'}|
  15104. salq $3, |\itm{lhs'}|
  15105. orq $|$\itm{tag}$|, |\itm{lhs'}|
  15106. \end{lstlisting}
  15107. The instruction selection for vectors and procedures is different
  15108. because their is no need to shift them to the left. The rightmost 3
  15109. bits are already zeros as described at the beginning of this
  15110. chapter. So we just combine the value and the tag using \key{orq}. \\
  15111. \begin{lstlisting}
  15112. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  15113. |$\Rightarrow$|
  15114. movq |$e'$|, |\itm{lhs'}|
  15115. orq $|$\itm{tag}$|, |\itm{lhs'}|
  15116. \end{lstlisting}
  15117. \paragraph{Tag-of-any}
  15118. Recall that the \code{tag-of-any} operation extracts the type tag from
  15119. a value of type \code{Any}. The type tag is the bottom three bits, so
  15120. we obtain the tag by taking the bitwise-and of the value with $111$
  15121. ($7$ in decimal).
  15122. \begin{lstlisting}
  15123. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  15124. |$\Rightarrow$|
  15125. movq |$e'$|, |\itm{lhs'}|
  15126. andq $7, |\itm{lhs'}|
  15127. \end{lstlisting}
  15128. \paragraph{ValueOf}
  15129. Like \key{make-any}, the instructions for \key{ValueOf} are different
  15130. depending on whether the type $T$ is a pointer (vector or procedure)
  15131. or not (Integer or Boolean). The following shows the instruction
  15132. selection for Integer and Boolean. We produce an untagged value by
  15133. shifting it to the right by 3 bits.
  15134. \begin{lstlisting}
  15135. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  15136. |$\Rightarrow$|
  15137. movq |$e'$|, |\itm{lhs'}|
  15138. sarq $3, |\itm{lhs'}|
  15139. \end{lstlisting}
  15140. %
  15141. In the case for vectors and procedures, there is no need to
  15142. shift. Instead we just need to zero-out the rightmost 3 bits. We
  15143. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  15144. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  15145. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  15146. then apply \code{andq} with the tagged value to get the desired
  15147. result. \\
  15148. \begin{lstlisting}
  15149. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  15150. |$\Rightarrow$|
  15151. movq $|$-8$|, |\itm{lhs'}|
  15152. andq |$e'$|, |\itm{lhs'}|
  15153. \end{lstlisting}
  15154. %% \paragraph{Type Predicates} We leave it to the reader to
  15155. %% devise a sequence of instructions to implement the type predicates
  15156. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  15157. \paragraph{Any-vector-length}
  15158. \begin{lstlisting}
  15159. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  15160. |$\Longrightarrow$|
  15161. movq |$\neg 111$|, %r11
  15162. andq |$a_1'$|, %r11
  15163. movq 0(%r11), %r11
  15164. andq $126, %r11
  15165. sarq $1, %r11
  15166. movq %r11, |$\itm{lhs'}$|
  15167. \end{lstlisting}
  15168. \paragraph{Any-vector-ref}
  15169. The index may be an arbitrary atom so instead of computing the offset
  15170. at compile time, instructions need to be generated to compute the
  15171. offset at runtime as follows. Note the use of the new instruction
  15172. \code{imulq}.
  15173. \begin{center}
  15174. \begin{minipage}{0.96\textwidth}
  15175. \begin{lstlisting}
  15176. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  15177. |$\Longrightarrow$|
  15178. movq |$\neg 111$|, %r11
  15179. andq |$a_1'$|, %r11
  15180. movq |$a_2'$|, %rax
  15181. addq $1, %rax
  15182. imulq $8, %rax
  15183. addq %rax, %r11
  15184. movq 0(%r11) |$\itm{lhs'}$|
  15185. \end{lstlisting}
  15186. \end{minipage}
  15187. \end{center}
  15188. \paragraph{Any-vector-set!}
  15189. The code generation for \code{any-vector-set!} is similar to the other
  15190. \code{any-vector} operations.
  15191. \section{Register Allocation for \LangAny{}}
  15192. \label{sec:register-allocation-Rany}
  15193. \index{subject}{register allocation}
  15194. There is an interesting interaction between tagged values and garbage
  15195. collection that has an impact on register allocation. A variable of
  15196. type \code{Any} might refer to a vector and therefore it might be a
  15197. root that needs to be inspected and copied during garbage
  15198. collection. Thus, we need to treat variables of type \code{Any} in a
  15199. similar way to variables of type \code{Vector} for purposes of
  15200. register allocation. In particular,
  15201. \begin{itemize}
  15202. \item If a variable of type \code{Any} is live during a function call,
  15203. then it must be spilled. This can be accomplished by changing
  15204. \code{build\_interference} to mark all variables of type \code{Any}
  15205. that are live after a \code{callq} as interfering with all the
  15206. registers.
  15207. \item If a variable of type \code{Any} is spilled, it must be spilled
  15208. to the root stack instead of the normal procedure call stack.
  15209. \end{itemize}
  15210. Another concern regarding the root stack is that the garbage collector
  15211. needs to differentiate between (1) plain old pointers to tuples, (2) a
  15212. tagged value that points to a tuple, and (3) a tagged value that is
  15213. not a tuple. We enable this differentiation by choosing not to use the
  15214. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  15215. reserved for identifying plain old pointers to tuples. That way, if
  15216. one of the first three bits is set, then we have a tagged value and
  15217. inspecting the tag can differentiation between vectors ($010$) and the
  15218. other kinds of values.
  15219. \begin{exercise}\normalfont
  15220. Expand your compiler to handle \LangAny{} as discussed in the last few
  15221. sections. Create 5 new programs that use the \code{Any} type and the
  15222. new operations (\code{inject}, \code{project}, \code{boolean?},
  15223. etc.). Test your compiler on these new programs and all of your
  15224. previously created test programs.
  15225. \end{exercise}
  15226. \begin{exercise}\normalfont
  15227. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  15228. Create tests for \LangDyn{} by adapting ten of your previous test programs
  15229. by removing type annotations. Add 5 more tests programs that
  15230. specifically rely on the language being dynamically typed. That is,
  15231. they should not be legal programs in a statically typed language, but
  15232. nevertheless, they should be valid \LangDyn{} programs that run to
  15233. completion without error.
  15234. \end{exercise}
  15235. \begin{figure}[p]
  15236. \begin{tikzpicture}[baseline=(current bounding box.center)]
  15237. \node (Rfun) at (0,4) {\large \LangDyn{}};
  15238. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  15239. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  15240. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  15241. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  15242. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  15243. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  15244. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  15245. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  15246. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  15247. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  15248. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  15249. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  15250. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  15251. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  15252. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  15253. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  15254. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  15255. \path[->,bend left=15] (Rfun) edge [above] node
  15256. {\ttfamily\footnotesize shrink} (Rfun-2);
  15257. \path[->,bend left=15] (Rfun-2) edge [above] node
  15258. {\ttfamily\footnotesize uniquify} (Rfun-3);
  15259. \path[->,bend left=15] (Rfun-3) edge [above] node
  15260. {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  15261. \path[->,bend right=15] (Rfun-4) edge [left] node
  15262. {\ttfamily\footnotesize cast\_insert} (Rfun-5);
  15263. \path[->,bend left=15] (Rfun-5) edge [above] node
  15264. {\ttfamily\footnotesize check\_bounds} (Rfun-6);
  15265. \path[->,bend left=15] (Rfun-6) edge [left] node
  15266. {\ttfamily\footnotesize reveal\_casts} (Rfun-7);
  15267. \path[->,bend left=15] (Rfun-7) edge [below] node
  15268. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15269. \path[->,bend right=15] (F1-2) edge [above] node
  15270. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15271. \path[->,bend right=15] (F1-3) edge [above] node
  15272. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  15273. \path[->,bend right=15] (F1-4) edge [above] node
  15274. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  15275. \path[->,bend right=15] (F1-5) edge [right] node
  15276. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15277. \path[->,bend left=15] (C3-2) edge [left] node
  15278. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15279. \path[->,bend right=15] (x86-2) edge [left] node
  15280. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15281. \path[->,bend right=15] (x86-2-1) edge [below] node
  15282. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15283. \path[->,bend right=15] (x86-2-2) edge [left] node
  15284. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15285. \path[->,bend left=15] (x86-3) edge [above] node
  15286. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15287. \path[->,bend left=15] (x86-4) edge [right] node
  15288. {\ttfamily\footnotesize print\_x86} (x86-5);
  15289. \end{tikzpicture}
  15290. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  15291. \label{fig:Rdyn-passes}
  15292. \end{figure}
  15293. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  15294. for the compilation of \LangDyn{}.
  15295. % Further Reading
  15296. \fi % racketEd
  15297. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15298. {\if\edition\pythonEd
  15299. \chapter{Objects}
  15300. \label{ch:Robject}
  15301. \index{subject}{objects}
  15302. \index{subject}{classes}
  15303. \fi}
  15304. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15305. \chapter{Gradual Typing}
  15306. \label{ch:Rgrad}
  15307. \index{subject}{gradual typing}
  15308. \if\edition\racketEd
  15309. This chapter studies a language, \LangGrad{}, in which the programmer
  15310. can choose between static and dynamic type checking in different parts
  15311. of a program, thereby mixing the statically typed \LangLoop{} language
  15312. with the dynamically typed \LangDyn{}. There are several approaches to
  15313. mixing static and dynamic typing, including multi-language
  15314. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  15315. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  15316. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  15317. programmer controls the amount of static versus dynamic checking by
  15318. adding or removing type annotations on parameters and
  15319. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  15320. %
  15321. The concrete syntax of \LangGrad{} is defined in
  15322. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  15323. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  15324. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  15325. non-terminals that make type annotations optional. The return types
  15326. are not optional in the abstract syntax; the parser fills in
  15327. \code{Any} when the return type is not specified in the concrete
  15328. syntax.
  15329. \begin{figure}[tp]
  15330. \centering
  15331. \fbox{
  15332. \begin{minipage}{0.96\textwidth}
  15333. \small
  15334. \[
  15335. \begin{array}{lcl}
  15336. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  15337. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  15338. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  15339. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  15340. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  15341. &\MID& \gray{\key{\#t} \MID \key{\#f}
  15342. \MID (\key{and}\;\Exp\;\Exp)
  15343. \MID (\key{or}\;\Exp\;\Exp)
  15344. \MID (\key{not}\;\Exp) } \\
  15345. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  15346. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  15347. (\key{vector-ref}\;\Exp\;\Int)} \\
  15348. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  15349. \MID (\Exp \; \Exp\ldots) } \\
  15350. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  15351. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  15352. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  15353. \MID \CBEGIN{\Exp\ldots}{\Exp}
  15354. \MID \CWHILE{\Exp}{\Exp} } \\
  15355. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  15356. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  15357. \end{array}
  15358. \]
  15359. \end{minipage}
  15360. }
  15361. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  15362. \label{fig:Rgrad-concrete-syntax}
  15363. \end{figure}
  15364. \begin{figure}[tp]
  15365. \centering
  15366. \fbox{
  15367. \begin{minipage}{0.96\textwidth}
  15368. \small
  15369. \[
  15370. \begin{array}{lcl}
  15371. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  15372. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  15373. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  15374. &\MID& \gray{ \BOOL{\itm{bool}}
  15375. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  15376. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  15377. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  15378. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  15379. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  15380. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  15381. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  15382. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  15383. \end{array}
  15384. \]
  15385. \end{minipage}
  15386. }
  15387. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  15388. \label{fig:Rgrad-syntax}
  15389. \end{figure}
  15390. Both the type checker and the interpreter for \LangGrad{} require some
  15391. interesting changes to enable gradual typing, which we discuss in the
  15392. next two sections in the context of the \code{map} example from
  15393. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map} we
  15394. revised the \code{map} example, omitting the type annotations from
  15395. the \code{inc} function.
  15396. \begin{figure}[btp]
  15397. % gradual_test_9.rkt
  15398. \begin{lstlisting}
  15399. (define (map [f : (Integer -> Integer)]
  15400. [v : (Vector Integer Integer)])
  15401. : (Vector Integer Integer)
  15402. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  15403. (define (inc x) (+ x 1))
  15404. (vector-ref (map inc (vector 0 41)) 1)
  15405. \end{lstlisting}
  15406. \caption{A partially-typed version of the \code{map} example.}
  15407. \label{fig:gradual-map}
  15408. \end{figure}
  15409. \section{Type Checking \LangGrad{} and \LangCast{}}
  15410. \label{sec:gradual-type-check}
  15411. The type checker for \LangGrad{} uses the \code{Any} type for missing
  15412. parameter and return types. For example, the \code{x} parameter of
  15413. \code{inc} in Figure~\ref{fig:gradual-map} is given the type
  15414. \code{Any} and the return type of \code{inc} is \code{Any}. Next
  15415. consider the \code{+} operator inside \code{inc}. It expects both
  15416. arguments to have type \code{Integer}, but its first argument \code{x}
  15417. has type \code{Any}. In a gradually typed language, such differences
  15418. are allowed so long as the types are \emph{consistent}, that is, they
  15419. are equal except in places where there is an \code{Any} type. The type
  15420. \code{Any} is consistent with every other type.
  15421. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  15422. \begin{figure}[tbp]
  15423. \begin{lstlisting}
  15424. (define/public (consistent? t1 t2)
  15425. (match* (t1 t2)
  15426. [('Integer 'Integer) #t]
  15427. [('Boolean 'Boolean) #t]
  15428. [('Void 'Void) #t]
  15429. [('Any t2) #t]
  15430. [(t1 'Any) #t]
  15431. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  15432. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  15433. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  15434. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  15435. (consistent? rt1 rt2))]
  15436. [(other wise) #f]))
  15437. \end{lstlisting}
  15438. \caption{The consistency predicate on types.}
  15439. \label{fig:consistent}
  15440. \end{figure}
  15441. Returning to the \code{map} example of
  15442. Figure~\ref{fig:gradual-map}, the \code{inc} function has type
  15443. \code{(Any -> Any)} but parameter \code{f} of \code{map} has type
  15444. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  15445. because the two types are consistent. In particular, \code{->} is
  15446. equal to \code{->} and because \code{Any} is consistent with
  15447. \code{Integer}.
  15448. Next consider a program with an error, such as applying the
  15449. \code{map} to a function that sometimes returns a Boolean, as
  15450. shown in Figure~\ref{fig:map-maybe-inc}. The type checker for
  15451. \LangGrad{} accepts this program because the type of \code{maybe-inc} is
  15452. consistent with the type of parameter \code{f} of \code{map}, that
  15453. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  15454. Integer)}. One might say that a gradual type checker is optimistic
  15455. in that it accepts programs that might execute without a runtime type
  15456. error.
  15457. %
  15458. Unfortunately, running this program with input \code{1} triggers an
  15459. error when the \code{maybe-inc} function returns \code{\#t}. \LangGrad{}
  15460. performs checking at runtime to ensure the integrity of the static
  15461. types, such as the \code{(Integer -> Integer)} annotation on parameter
  15462. \code{f} of \code{map}. This runtime checking is carried out by a
  15463. new \code{Cast} form that is inserted by the type checker. Thus, the
  15464. output of the type checker is a program in the \LangCast{} language, which
  15465. adds \code{Cast} to \LangLoop{}, as shown in
  15466. Figure~\ref{fig:Rgrad-prime-syntax}.
  15467. \begin{figure}[tp]
  15468. \centering
  15469. \fbox{
  15470. \begin{minipage}{0.96\textwidth}
  15471. \small
  15472. \[
  15473. \begin{array}{lcl}
  15474. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  15475. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  15476. \end{array}
  15477. \]
  15478. \end{minipage}
  15479. }
  15480. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  15481. \label{fig:Rgrad-prime-syntax}
  15482. \end{figure}
  15483. \begin{figure}[tbp]
  15484. \begin{lstlisting}
  15485. (define (map [f : (Integer -> Integer)]
  15486. [v : (Vector Integer Integer)])
  15487. : (Vector Integer Integer)
  15488. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  15489. (define (inc x) (+ x 1))
  15490. (define (true) #t)
  15491. (define (maybe-inc x) (if (eq? 0 (read)) (inc x) (true)))
  15492. (vector-ref (map maybe-inc (vector 0 41)) 0)
  15493. \end{lstlisting}
  15494. \caption{A variant of the \code{map} example with an error.}
  15495. \label{fig:map-maybe-inc}
  15496. \end{figure}
  15497. Figure~\ref{fig:map-cast} shows the output of the type checker for
  15498. \code{map} and \code{maybe-inc}. The idea is that \code{Cast} is
  15499. inserted every time the type checker sees two types that are
  15500. consistent but not equal. In the \code{inc} function, \code{x} is
  15501. cast to \code{Integer} and the result of the \code{+} is cast to
  15502. \code{Any}. In the call to \code{map}, the \code{inc} argument
  15503. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  15504. \begin{figure}[btp]
  15505. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15506. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  15507. : (Vector Integer Integer)
  15508. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  15509. (define (inc [x : Any]) : Any
  15510. (cast (+ (cast x Any Integer) 1) Integer Any))
  15511. (define (true) : Any (cast #t Boolean Any))
  15512. (define (maybe-inc [x : Any]) : Any
  15513. (if (eq? 0 (read)) (inc x) (true)))
  15514. (vector-ref (map (cast maybe-inc (Any -> Any) (Integer -> Integer))
  15515. (vector 0 41)) 0)
  15516. \end{lstlisting}
  15517. \caption{Output of type checking \code{map}
  15518. and \code{maybe-inc}.}
  15519. \label{fig:map-cast}
  15520. \end{figure}
  15521. The type checker for \LangGrad{} is defined in
  15522. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  15523. and \ref{fig:type-check-Rgradual-3}.
  15524. \begin{figure}[tbp]
  15525. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15526. (define type-check-gradual_class
  15527. (class type-check-Rwhile_class
  15528. (super-new)
  15529. (inherit operator-types type-predicates)
  15530. (define/override (type-check-exp env)
  15531. (lambda (e)
  15532. (define recur (type-check-exp env))
  15533. (match e
  15534. [(Prim 'vector-length (list e1))
  15535. (define-values (e1^ t) (recur e1))
  15536. (match t
  15537. [`(Vector ,ts ...)
  15538. (values (Prim 'vector-length (list e1^)) 'Integer)]
  15539. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  15540. [(Prim 'vector-ref (list e1 e2))
  15541. (define-values (e1^ t1) (recur e1))
  15542. (define-values (e2^ t2) (recur e2))
  15543. (check-consistent? t2 'Integer e)
  15544. (match t1
  15545. [`(Vector ,ts ...)
  15546. (match e2^
  15547. [(Int i)
  15548. (unless (and (0 . <= . i) (i . < . (length ts)))
  15549. (error 'type-check "invalid index ~a in ~a" i e))
  15550. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  15551. [else (define e1^^ (make-cast e1^ t1 'Any))
  15552. (define e2^^ (make-cast e2^ t2 'Integer))
  15553. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  15554. ['Any
  15555. (define e2^^ (make-cast e2^ t2 'Integer))
  15556. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  15557. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  15558. [(Prim 'vector-set! (list e1 e2 e3) )
  15559. (define-values (e1^ t1) (recur e1))
  15560. (define-values (e2^ t2) (recur e2))
  15561. (define-values (e3^ t3) (recur e3))
  15562. (check-consistent? t2 'Integer e)
  15563. (match t1
  15564. [`(Vector ,ts ...)
  15565. (match e2^
  15566. [(Int i)
  15567. (unless (and (0 . <= . i) (i . < . (length ts)))
  15568. (error 'type-check "invalid index ~a in ~a" i e))
  15569. (check-consistent? (list-ref ts i) t3 e)
  15570. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  15571. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  15572. [else
  15573. (define e1^^ (make-cast e1^ t1 'Any))
  15574. (define e2^^ (make-cast e2^ t2 'Integer))
  15575. (define e3^^ (make-cast e3^ t3 'Any))
  15576. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  15577. ['Any
  15578. (define e2^^ (make-cast e2^ t2 'Integer))
  15579. (define e3^^ (make-cast e3^ t3 'Any))
  15580. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  15581. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  15582. \end{lstlisting}
  15583. \caption{Type checker for the \LangGrad{} language, part 1.}
  15584. \label{fig:type-check-Rgradual-1}
  15585. \end{figure}
  15586. \begin{figure}[tbp]
  15587. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15588. [(Prim 'eq? (list e1 e2))
  15589. (define-values (e1^ t1) (recur e1))
  15590. (define-values (e2^ t2) (recur e2))
  15591. (check-consistent? t1 t2 e)
  15592. (define T (meet t1 t2))
  15593. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  15594. 'Boolean)]
  15595. [(Prim 'not (list e1))
  15596. (define-values (e1^ t1) (recur e1))
  15597. (match t1
  15598. ['Any
  15599. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  15600. (Bool #t) (Bool #f)))]
  15601. [else
  15602. (define-values (t-ret new-es^)
  15603. (type-check-op 'not (list t1) (list e1^) e))
  15604. (values (Prim 'not new-es^) t-ret)])]
  15605. [(Prim 'and (list e1 e2))
  15606. (recur (If e1 e2 (Bool #f)))]
  15607. [(Prim 'or (list e1 e2))
  15608. (define tmp (gensym 'tmp))
  15609. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  15610. [(Prim op es)
  15611. #:when (not (set-member? explicit-prim-ops op))
  15612. (define-values (new-es ts)
  15613. (for/lists (exprs types) ([e es])
  15614. (recur e)))
  15615. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  15616. (values (Prim op new-es^) t-ret)]
  15617. [(If e1 e2 e3)
  15618. (define-values (e1^ T1) (recur e1))
  15619. (define-values (e2^ T2) (recur e2))
  15620. (define-values (e3^ T3) (recur e3))
  15621. (check-consistent? T2 T3 e)
  15622. (match T1
  15623. ['Boolean
  15624. (define Tif (join T2 T3))
  15625. (values (If e1^ (make-cast e2^ T2 Tif)
  15626. (make-cast e3^ T3 Tif)) Tif)]
  15627. ['Any
  15628. (define Tif (meet T2 T3))
  15629. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  15630. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  15631. Tif)]
  15632. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  15633. [(HasType e1 T)
  15634. (define-values (e1^ T1) (recur e1))
  15635. (check-consistent? T1 T)
  15636. (values (make-cast e1^ T1 T) T)]
  15637. [(SetBang x e1)
  15638. (define-values (e1^ T1) (recur e1))
  15639. (define varT (dict-ref env x))
  15640. (check-consistent? T1 varT e)
  15641. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  15642. [(WhileLoop e1 e2)
  15643. (define-values (e1^ T1) (recur e1))
  15644. (check-consistent? T1 'Boolean e)
  15645. (define-values (e2^ T2) ((type-check-exp env) e2))
  15646. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  15647. \end{lstlisting}
  15648. \caption{Type checker for the \LangGrad{} language, part 2.}
  15649. \label{fig:type-check-Rgradual-2}
  15650. \end{figure}
  15651. \begin{figure}[tbp]
  15652. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15653. [(Apply e1 e2s)
  15654. (define-values (e1^ T1) (recur e1))
  15655. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  15656. (match T1
  15657. [`(,T1ps ... -> ,T1rt)
  15658. (for ([T2 T2s] [Tp T1ps])
  15659. (check-consistent? T2 Tp e))
  15660. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  15661. (make-cast e2 src tgt)))
  15662. (values (Apply e1^ e2s^^) T1rt)]
  15663. [`Any
  15664. (define e1^^ (make-cast e1^ 'Any
  15665. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  15666. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  15667. (make-cast e2 src 'Any)))
  15668. (values (Apply e1^^ e2s^^) 'Any)]
  15669. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  15670. [(Lambda params Tr e1)
  15671. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  15672. (match p
  15673. [`[,x : ,T] (values x T)]
  15674. [(? symbol? x) (values x 'Any)])))
  15675. (define-values (e1^ T1)
  15676. ((type-check-exp (append (map cons xs Ts) env)) e1))
  15677. (check-consistent? Tr T1 e)
  15678. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  15679. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  15680. [else ((super type-check-exp env) e)]
  15681. )))
  15682. \end{lstlisting}
  15683. \caption{Type checker for the \LangGrad{} language, part 3.}
  15684. \label{fig:type-check-Rgradual-3}
  15685. \end{figure}
  15686. \begin{figure}[tbp]
  15687. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15688. (define/public (join t1 t2)
  15689. (match* (t1 t2)
  15690. [('Integer 'Integer) 'Integer]
  15691. [('Boolean 'Boolean) 'Boolean]
  15692. [('Void 'Void) 'Void]
  15693. [('Any t2) t2]
  15694. [(t1 'Any) t1]
  15695. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  15696. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  15697. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  15698. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  15699. -> ,(join rt1 rt2))]))
  15700. (define/public (meet t1 t2)
  15701. (match* (t1 t2)
  15702. [('Integer 'Integer) 'Integer]
  15703. [('Boolean 'Boolean) 'Boolean]
  15704. [('Void 'Void) 'Void]
  15705. [('Any t2) 'Any]
  15706. [(t1 'Any) 'Any]
  15707. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  15708. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  15709. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  15710. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  15711. -> ,(meet rt1 rt2))]))
  15712. (define/public (make-cast e src tgt)
  15713. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  15714. (define/public (check-consistent? t1 t2 e)
  15715. (unless (consistent? t1 t2)
  15716. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  15717. (define/override (type-check-op op arg-types args e)
  15718. (match (dict-ref (operator-types) op)
  15719. [`(,param-types . ,return-type)
  15720. (for ([at arg-types] [pt param-types])
  15721. (check-consistent? at pt e))
  15722. (values return-type
  15723. (for/list ([e args] [s arg-types] [t param-types])
  15724. (make-cast e s t)))]
  15725. [else (error 'type-check-op "unrecognized ~a" op)]))
  15726. (define explicit-prim-ops
  15727. (set-union
  15728. (type-predicates)
  15729. (set 'procedure-arity 'eq?
  15730. 'vector 'vector-length 'vector-ref 'vector-set!
  15731. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  15732. (define/override (fun-def-type d)
  15733. (match d
  15734. [(Def f params rt info body)
  15735. (define ps
  15736. (for/list ([p params])
  15737. (match p
  15738. [`[,x : ,T] T]
  15739. [(? symbol?) 'Any]
  15740. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  15741. `(,@ps -> ,rt)]
  15742. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  15743. \end{lstlisting}
  15744. \caption{Auxiliary functions for type checking \LangGrad{}.}
  15745. \label{fig:type-check-Rgradual-aux}
  15746. \end{figure}
  15747. \clearpage
  15748. \section{Interpreting \LangCast{}}
  15749. \label{sec:interp-casts}
  15750. The runtime behavior of first-order casts is straightforward, that is,
  15751. casts involving simple types such as \code{Integer} and
  15752. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  15753. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  15754. puts the integer into a tagged value
  15755. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  15756. \code{Integer} is accomplished with the \code{Project} operator, that
  15757. is, by checking the value's tag and either retrieving the underlying
  15758. integer or signaling an error if it the tag is not the one for
  15759. integers (Figure~\ref{fig:apply-project}).
  15760. %
  15761. Things get more interesting for higher-order casts, that is, casts
  15762. involving function or vector types.
  15763. Consider the cast of the function \code{maybe-inc} from \code{(Any ->
  15764. Any)} to \code{(Integer -> Integer)}. When a function flows through
  15765. this cast at runtime, we can't know in general whether the function
  15766. will always return an integer.\footnote{Predicting the return value of
  15767. a function is equivalent to the halting problem, which is
  15768. undecidable.} The \LangCast{} interpreter therefore delays the checking
  15769. of the cast until the function is applied. This is accomplished by
  15770. wrapping \code{maybe-inc} in a new function that casts its parameter
  15771. from \code{Integer} to \code{Any}, applies \code{maybe-inc}, and then
  15772. casts the return value from \code{Any} to \code{Integer}.
  15773. Turning our attention to casts involving vector types, we consider the
  15774. example in Figure~\ref{fig:map-bang} that defines a
  15775. partially-typed version of \code{map} whose parameter \code{v} has
  15776. type \code{(Vector Any Any)} and that updates \code{v} in place
  15777. instead of returning a new vector. So we name this function
  15778. \code{map!}. We apply \code{map!} to a vector of integers, so
  15779. the type checker inserts a cast from \code{(Vector Integer Integer)}
  15780. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  15781. cast between vector types would be a build a new vector whose elements
  15782. are the result of casting each of the original elements to the
  15783. appropriate target type. However, this approach is only valid for
  15784. immutable vectors; and our vectors are mutable. In the example of
  15785. Figure~\ref{fig:map-bang}, if the cast created a new vector, then
  15786. the updates inside of \code{map!} would happen to the new vector
  15787. and not the original one.
  15788. \begin{figure}[tbp]
  15789. % gradual_test_11.rkt
  15790. \begin{lstlisting}
  15791. (define (map! [f : (Any -> Any)]
  15792. [v : (Vector Any Any)]) : Void
  15793. (begin
  15794. (vector-set! v 0 (f (vector-ref v 0)))
  15795. (vector-set! v 1 (f (vector-ref v 1)))))
  15796. (define (inc x) (+ x 1))
  15797. (let ([v (vector 0 41)])
  15798. (begin (map! inc v) (vector-ref v 1)))
  15799. \end{lstlisting}
  15800. \caption{An example involving casts on vectors.}
  15801. \label{fig:map-bang}
  15802. \end{figure}
  15803. Instead the interpreter needs to create a new kind of value, a
  15804. \emph{vector proxy}, that intercepts every vector operation. On a
  15805. read, the proxy reads from the underlying vector and then applies a
  15806. cast to the resulting value. On a write, the proxy casts the argument
  15807. value and then performs the write to the underlying vector. For the
  15808. first \code{(vector-ref v 0)} in \code{map!}, the proxy casts
  15809. \code{0} from \code{Integer} to \code{Any}. For the first
  15810. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  15811. to \code{Integer}.
  15812. The final category of cast that we need to consider are casts between
  15813. the \code{Any} type and either a function or a vector
  15814. type. Figure~\ref{fig:map-any} shows a variant of \code{map!}
  15815. in which parameter \code{v} does not have a type annotation, so it is
  15816. given type \code{Any}. In the call to \code{map!}, the vector has
  15817. type \code{(Vector Integer Integer)} so the type checker inserts a
  15818. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  15819. thought is to use \code{Inject}, but that doesn't work because
  15820. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  15821. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  15822. to \code{Any}.
  15823. \begin{figure}[tbp]
  15824. \begin{lstlisting}
  15825. (define (map! [f : (Any -> Any)] v) : Void
  15826. (begin
  15827. (vector-set! v 0 (f (vector-ref v 0)))
  15828. (vector-set! v 1 (f (vector-ref v 1)))))
  15829. (define (inc x) (+ x 1))
  15830. (let ([v (vector 0 41)])
  15831. (begin (map! inc v) (vector-ref v 1)))
  15832. \end{lstlisting}
  15833. \caption{Casting a vector to \code{Any}.}
  15834. \label{fig:map-any}
  15835. \end{figure}
  15836. The \LangCast{} interpreter uses an auxiliary function named
  15837. \code{apply-cast} to cast a value from a source type to a target type,
  15838. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  15839. of the kinds of casts that we've discussed in this section.
  15840. \begin{figure}[tbp]
  15841. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15842. (define/public (apply-cast v s t)
  15843. (match* (s t)
  15844. [(t1 t2) #:when (equal? t1 t2) v]
  15845. [('Any t2)
  15846. (match t2
  15847. [`(,ts ... -> ,rt)
  15848. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  15849. (define v^ (apply-project v any->any))
  15850. (apply-cast v^ any->any `(,@ts -> ,rt))]
  15851. [`(Vector ,ts ...)
  15852. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  15853. (define v^ (apply-project v vec-any))
  15854. (apply-cast v^ vec-any `(Vector ,@ts))]
  15855. [else (apply-project v t2)])]
  15856. [(t1 'Any)
  15857. (match t1
  15858. [`(,ts ... -> ,rt)
  15859. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  15860. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  15861. (apply-inject v^ (any-tag any->any))]
  15862. [`(Vector ,ts ...)
  15863. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  15864. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  15865. (apply-inject v^ (any-tag vec-any))]
  15866. [else (apply-inject v (any-tag t1))])]
  15867. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  15868. (define x (gensym 'x))
  15869. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  15870. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  15871. (define cast-writes
  15872. (for/list ([t1 ts1] [t2 ts2])
  15873. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  15874. `(vector-proxy ,(vector v (apply vector cast-reads)
  15875. (apply vector cast-writes)))]
  15876. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  15877. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  15878. `(function ,xs ,(Cast
  15879. (Apply (Value v)
  15880. (for/list ([x xs][t1 ts1][t2 ts2])
  15881. (Cast (Var x) t2 t1)))
  15882. rt1 rt2) ())]
  15883. ))
  15884. \end{lstlisting}
  15885. \caption{The \code{apply-cast} auxiliary method.}
  15886. \label{fig:apply-cast}
  15887. \end{figure}
  15888. The interpreter for \LangCast{} is defined in
  15889. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  15890. dispatching to \code{apply-cast}. To handle the addition of vector
  15891. proxies, we update the vector primitives in \code{interp-op} using the
  15892. functions in Figure~\ref{fig:guarded-vector}.
  15893. \begin{figure}[tbp]
  15894. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15895. (define interp-Rcast_class
  15896. (class interp-Rwhile_class
  15897. (super-new)
  15898. (inherit apply-fun apply-inject apply-project)
  15899. (define/override (interp-op op)
  15900. (match op
  15901. ['vector-length guarded-vector-length]
  15902. ['vector-ref guarded-vector-ref]
  15903. ['vector-set! guarded-vector-set!]
  15904. ['any-vector-ref (lambda (v i)
  15905. (match v [`(tagged ,v^ ,tg)
  15906. (guarded-vector-ref v^ i)]))]
  15907. ['any-vector-set! (lambda (v i a)
  15908. (match v [`(tagged ,v^ ,tg)
  15909. (guarded-vector-set! v^ i a)]))]
  15910. ['any-vector-length (lambda (v)
  15911. (match v [`(tagged ,v^ ,tg)
  15912. (guarded-vector-length v^)]))]
  15913. [else (super interp-op op)]
  15914. ))
  15915. (define/override ((interp-exp env) e)
  15916. (define (recur e) ((interp-exp env) e))
  15917. (match e
  15918. [(Value v) v]
  15919. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  15920. [else ((super interp-exp env) e)]))
  15921. ))
  15922. (define (interp-Rcast p)
  15923. (send (new interp-Rcast_class) interp-program p))
  15924. \end{lstlisting}
  15925. \caption{The interpreter for \LangCast{}.}
  15926. \label{fig:interp-Rcast}
  15927. \end{figure}
  15928. \begin{figure}[tbp]
  15929. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15930. (define (guarded-vector-ref vec i)
  15931. (match vec
  15932. [`(vector-proxy ,proxy)
  15933. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  15934. (define rd (vector-ref (vector-ref proxy 1) i))
  15935. (apply-fun rd (list val) 'guarded-vector-ref)]
  15936. [else (vector-ref vec i)]))
  15937. (define (guarded-vector-set! vec i arg)
  15938. (match vec
  15939. [`(vector-proxy ,proxy)
  15940. (define wr (vector-ref (vector-ref proxy 2) i))
  15941. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  15942. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  15943. [else (vector-set! vec i arg)]))
  15944. (define (guarded-vector-length vec)
  15945. (match vec
  15946. [`(vector-proxy ,proxy)
  15947. (guarded-vector-length (vector-ref proxy 0))]
  15948. [else (vector-length vec)]))
  15949. \end{lstlisting}
  15950. \caption{The guarded-vector auxiliary functions.}
  15951. \label{fig:guarded-vector}
  15952. \end{figure}
  15953. \section{Lower Casts}
  15954. \label{sec:lower-casts}
  15955. The next step in the journey towards x86 is the \code{lower-casts}
  15956. pass that translates the casts in \LangCast{} to the lower-level
  15957. \code{Inject} and \code{Project} operators and a new operator for
  15958. creating vector proxies, extending the \LangLoop{} language to create
  15959. \LangProxy{}. We recommend creating an auxiliary function named
  15960. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  15961. and a target type, and translates it to expression in \LangProxy{} that has
  15962. the same behavior as casting the expression from the source to the
  15963. target type in the interpreter.
  15964. The \code{lower-cast} function can follow a code structure similar to
  15965. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  15966. the interpreter for \LangCast{} because it must handle the same cases as
  15967. \code{apply-cast} and it needs to mimic the behavior of
  15968. \code{apply-cast}. The most interesting cases are those concerning the
  15969. casts between two vector types and between two function types.
  15970. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  15971. type to another vector type is accomplished by creating a proxy that
  15972. intercepts the operations on the underlying vector. Here we make the
  15973. creation of the proxy explicit with the \code{vector-proxy} primitive
  15974. operation. It takes three arguments, the first is an expression for
  15975. the vector, the second is a vector of functions for casting an element
  15976. that is being read from the vector, and the third is a vector of
  15977. functions for casting an element that is being written to the vector.
  15978. You can create the functions using \code{Lambda}. Also, as we shall
  15979. see in the next section, we need to differentiate these vectors from
  15980. the user-created ones, so we recommend using a new primitive operator
  15981. named \code{raw-vector} instead of \code{vector} to create these
  15982. vectors of functions. Figure~\ref{fig:map-bang-lower-cast} shows
  15983. the output of \code{lower-casts} on the example in
  15984. Figure~\ref{fig:map-bang} that involved casting a vector of
  15985. integers to a vector of \code{Any}.
  15986. \begin{figure}[tbp]
  15987. \begin{lstlisting}
  15988. (define (map! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  15989. (begin
  15990. (vector-set! v 0 (f (vector-ref v 0)))
  15991. (vector-set! v 1 (f (vector-ref v 1)))))
  15992. (define (inc [x : Any]) : Any
  15993. (inject (+ (project x Integer) 1) Integer))
  15994. (let ([v (vector 0 41)])
  15995. (begin
  15996. (map! inc (vector-proxy v
  15997. (raw-vector (lambda: ([x9 : Integer]) : Any
  15998. (inject x9 Integer))
  15999. (lambda: ([x9 : Integer]) : Any
  16000. (inject x9 Integer)))
  16001. (raw-vector (lambda: ([x9 : Any]) : Integer
  16002. (project x9 Integer))
  16003. (lambda: ([x9 : Any]) : Integer
  16004. (project x9 Integer)))))
  16005. (vector-ref v 1)))
  16006. \end{lstlisting}
  16007. \caption{Output of \code{lower-casts} on the example in
  16008. Figure~\ref{fig:map-bang}.}
  16009. \label{fig:map-bang-lower-cast}
  16010. \end{figure}
  16011. A cast from one function type to another function type is accomplished
  16012. by generating a \code{Lambda} whose parameter and return types match
  16013. the target function type. The body of the \code{Lambda} should cast
  16014. the parameters from the target type to the source type (yes,
  16015. backwards! functions are contravariant\index{subject}{contravariant} in the
  16016. parameters), then call the underlying function, and finally cast the
  16017. result from the source return type to the target return type.
  16018. Figure~\ref{fig:map-lower-cast} shows the output of the
  16019. \code{lower-casts} pass on the \code{map} example in
  16020. Figure~\ref{fig:gradual-map}. Note that the \code{inc} argument
  16021. in the call to \code{map} is wrapped in a \code{lambda}.
  16022. \begin{figure}[tbp]
  16023. \begin{lstlisting}
  16024. (define (map [f : (Integer -> Integer)]
  16025. [v : (Vector Integer Integer)])
  16026. : (Vector Integer Integer)
  16027. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16028. (define (inc [x : Any]) : Any
  16029. (inject (+ (project x Integer) 1) Integer))
  16030. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  16031. (project (inc (inject x9 Integer)) Integer))
  16032. (vector 0 41)) 1)
  16033. \end{lstlisting}
  16034. \caption{Output of \code{lower-casts} on the example in
  16035. Figure~\ref{fig:gradual-map}.}
  16036. \label{fig:map-lower-cast}
  16037. \end{figure}
  16038. \section{Differentiate Proxies}
  16039. \label{sec:differentiate-proxies}
  16040. So far the job of differentiating vectors and vector proxies has been
  16041. the job of the interpreter. For example, the interpreter for \LangCast{}
  16042. implements \code{vector-ref} using the \code{guarded-vector-ref}
  16043. function in Figure~\ref{fig:guarded-vector}. In the
  16044. \code{differentiate-proxies} pass we shift this responsibility to the
  16045. generated code.
  16046. We begin by designing the output language $R^p_8$. In
  16047. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  16048. proxies. In $R^p_8$ we return the \code{Vector} type to
  16049. its original meaning, as the type of real vectors, and we introduce a
  16050. new type, \code{PVector}, whose values can be either real vectors or
  16051. vector proxies. This new type comes with a suite of new primitive
  16052. operations for creating and using values of type \code{PVector}. We
  16053. don't need to introduce a new type to represent vector proxies. A
  16054. proxy is represented by a vector containing three things: 1) the
  16055. underlying vector, 2) a vector of functions for casting elements that
  16056. are read from the vector, and 3) a vector of functions for casting
  16057. values to be written to the vector. So we define the following
  16058. abbreviation for the type of a vector proxy:
  16059. \[
  16060. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  16061. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  16062. \to (\key{PVector}~ T' \ldots)
  16063. \]
  16064. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  16065. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  16066. %
  16067. Next we describe each of the new primitive operations.
  16068. \begin{description}
  16069. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  16070. (\key{PVector} $T \ldots$)]\ \\
  16071. %
  16072. This operation brands a vector as a value of the \code{PVector} type.
  16073. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  16074. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  16075. %
  16076. This operation brands a vector proxy as value of the \code{PVector} type.
  16077. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  16078. \code{Boolean}] \ \\
  16079. %
  16080. returns true if the value is a vector proxy and false if it is a
  16081. real vector.
  16082. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  16083. (\key{Vector} $T \ldots$)]\ \\
  16084. %
  16085. Assuming that the input is a vector (and not a proxy), this
  16086. operation returns the vector.
  16087. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  16088. $\to$ \code{Boolean}]\ \\
  16089. %
  16090. Given a vector proxy, this operation returns the length of the
  16091. underlying vector.
  16092. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  16093. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  16094. %
  16095. Given a vector proxy, this operation returns the $i$th element of
  16096. the underlying vector.
  16097. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  16098. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  16099. proxy, this operation writes a value to the $i$th element of the
  16100. underlying vector.
  16101. \end{description}
  16102. Now to discuss the translation that differentiates vectors from
  16103. proxies. First, every type annotation in the program must be
  16104. translated (recursively) to replace \code{Vector} with \code{PVector}.
  16105. Next, we must insert uses of \code{PVector} operations in the
  16106. appropriate places. For example, we wrap every vector creation with an
  16107. \code{inject-vector}.
  16108. \begin{lstlisting}
  16109. (vector |$e_1 \ldots e_n$|)
  16110. |$\Rightarrow$|
  16111. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  16112. \end{lstlisting}
  16113. The \code{raw-vector} operator that we introduced in the previous
  16114. section does not get injected.
  16115. \begin{lstlisting}
  16116. (raw-vector |$e_1 \ldots e_n$|)
  16117. |$\Rightarrow$|
  16118. (vector |$e'_1 \ldots e'_n$|)
  16119. \end{lstlisting}
  16120. The \code{vector-proxy} primitive translates as follows.
  16121. \begin{lstlisting}
  16122. (vector-proxy |$e_1~e_2~e_3$|)
  16123. |$\Rightarrow$|
  16124. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  16125. \end{lstlisting}
  16126. We translate the vector operations into conditional expressions that
  16127. check whether the value is a proxy and then dispatch to either the
  16128. appropriate proxy vector operation or the regular vector operation.
  16129. For example, the following is the translation for \code{vector-ref}.
  16130. \begin{lstlisting}
  16131. (vector-ref |$e_1$| |$i$|)
  16132. |$\Rightarrow$|
  16133. (let ([|$v~e_1$|])
  16134. (if (proxy? |$v$|)
  16135. (proxy-vector-ref |$v$| |$i$|)
  16136. (vector-ref (project-vector |$v$|) |$i$|)
  16137. \end{lstlisting}
  16138. Note in the case of a real vector, we must apply \code{project-vector}
  16139. before the \code{vector-ref}.
  16140. \section{Reveal Casts}
  16141. \label{sec:reveal-casts-gradual}
  16142. Recall that the \code{reveal-casts} pass
  16143. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  16144. \code{Inject} and \code{Project} into lower-level operations. In
  16145. particular, \code{Project} turns into a conditional expression that
  16146. inspects the tag and retrieves the underlying value. Here we need to
  16147. augment the translation of \code{Project} to handle the situation when
  16148. the target type is \code{PVector}. Instead of using
  16149. \code{vector-length} we need to use \code{proxy-vector-length}.
  16150. \begin{lstlisting}
  16151. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  16152. |$\Rightarrow$|
  16153. (let |$\itm{tmp}$| |$e'$|
  16154. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  16155. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  16156. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  16157. (exit)))
  16158. \end{lstlisting}
  16159. \section{Closure Conversion}
  16160. \label{sec:closure-conversion-gradual}
  16161. The closure conversion pass only requires one minor adjustment. The
  16162. auxiliary function that translates type annotations needs to be
  16163. updated to handle the \code{PVector} type.
  16164. \section{Explicate Control}
  16165. \label{sec:explicate-control-gradual}
  16166. Update the \code{explicate\_control} pass to handle the new primitive
  16167. operations on the \code{PVector} type.
  16168. \section{Select Instructions}
  16169. \label{sec:select-instructions-gradual}
  16170. Recall that the \code{select\_instructions} pass is responsible for
  16171. lowering the primitive operations into x86 instructions. So we need
  16172. to translate the new \code{PVector} operations to x86. To do so, the
  16173. first question we need to answer is how will we differentiate the two
  16174. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  16175. We need just one bit to accomplish this, and use the bit in position
  16176. $57$ of the 64-bit tag at the front of every vector (see
  16177. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  16178. for \code{inject-vector} we leave it that way.
  16179. \begin{lstlisting}
  16180. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  16181. |$\Rightarrow$|
  16182. movq |$e'_1$|, |$\itm{lhs'}$|
  16183. \end{lstlisting}
  16184. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  16185. \begin{lstlisting}
  16186. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  16187. |$\Rightarrow$|
  16188. movq |$e'_1$|, %r11
  16189. movq |$(1 << 57)$|, %rax
  16190. orq 0(%r11), %rax
  16191. movq %rax, 0(%r11)
  16192. movq %r11, |$\itm{lhs'}$|
  16193. \end{lstlisting}
  16194. The \code{proxy?} operation consumes the information so carefully
  16195. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  16196. isolates the $57$th bit to tell whether the value is a real vector or
  16197. a proxy.
  16198. \begin{lstlisting}
  16199. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  16200. |$\Rightarrow$|
  16201. movq |$e_1'$|, %r11
  16202. movq 0(%r11), %rax
  16203. sarq $57, %rax
  16204. andq $1, %rax
  16205. movq %rax, |$\itm{lhs'}$|
  16206. \end{lstlisting}
  16207. The \code{project-vector} operation is straightforward to translate,
  16208. so we leave it up to the reader.
  16209. Regarding the \code{proxy-vector} operations, the runtime provides
  16210. procedures that implement them (they are recursive functions!) so
  16211. here we simply need to translate these vector operations into the
  16212. appropriate function call. For example, here is the translation for
  16213. \code{proxy-vector-ref}.
  16214. \begin{lstlisting}
  16215. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  16216. |$\Rightarrow$|
  16217. movq |$e_1'$|, %rdi
  16218. movq |$e_2'$|, %rsi
  16219. callq proxy_vector_ref
  16220. movq %rax, |$\itm{lhs'}$|
  16221. \end{lstlisting}
  16222. We have another batch of vector operations to deal with, those for the
  16223. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  16224. \code{any-vector-ref} when there is a \code{vector-ref} on something
  16225. of type \code{Any}, and similarly for \code{any-vector-set!} and
  16226. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  16227. Section~\ref{sec:select-Rany} we selected instructions for these
  16228. operations based on the idea that the underlying value was a real
  16229. vector. But in the current setting, the underlying value is of type
  16230. \code{PVector}. So \code{any-vector-ref} can be translates to
  16231. pseudo-x86 as follows. We begin by projecting the underlying value out
  16232. of the tagged value and then call the \code{proxy\_vector\_ref}
  16233. procedure in the runtime.
  16234. \begin{lstlisting}
  16235. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  16236. movq |$\neg 111$|, %rdi
  16237. andq |$e_1'$|, %rdi
  16238. movq |$e_2'$|, %rsi
  16239. callq proxy_vector_ref
  16240. movq %rax, |$\itm{lhs'}$|
  16241. \end{lstlisting}
  16242. The \code{any-vector-set!} and \code{any-vector-length} operators can
  16243. be translated in a similar way.
  16244. \begin{exercise}\normalfont
  16245. Implement a compiler for the gradually-typed \LangGrad{} language by
  16246. extending and adapting your compiler for \LangLoop{}. Create 10 new
  16247. partially-typed test programs. In addition to testing with these
  16248. new programs, also test your compiler on all the tests for \LangLoop{}
  16249. and tests for \LangDyn{}. Sometimes you may get a type checking error
  16250. on the \LangDyn{} programs but you can adapt them by inserting
  16251. a cast to the \code{Any} type around each subexpression
  16252. causing a type error. While \LangDyn{} does not have explicit casts,
  16253. you can induce one by wrapping the subexpression \code{e}
  16254. with a call to an un-annotated identity function, like this:
  16255. \code{((lambda (x) x) e)}.
  16256. \end{exercise}
  16257. \begin{figure}[p]
  16258. \begin{tikzpicture}[baseline=(current bounding box.center)]
  16259. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  16260. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  16261. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  16262. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  16263. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  16264. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  16265. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  16266. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  16267. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  16268. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  16269. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  16270. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  16271. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  16272. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  16273. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  16274. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  16275. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  16276. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  16277. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  16278. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  16279. \path[->,bend right=15] (Rgradual) edge [above] node
  16280. {\ttfamily\footnotesize type\_check} (Rgradualp);
  16281. \path[->,bend right=15] (Rgradualp) edge [above] node
  16282. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  16283. \path[->,bend right=15] (Rwhilepp) edge [right] node
  16284. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  16285. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  16286. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  16287. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  16288. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  16289. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  16290. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  16291. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  16292. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  16293. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  16294. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16295. \path[->,bend left=15] (F1-1) edge [below] node
  16296. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  16297. \path[->,bend right=15] (F1-2) edge [above] node
  16298. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  16299. \path[->,bend right=15] (F1-3) edge [above] node
  16300. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  16301. \path[->,bend right=15] (F1-4) edge [above] node
  16302. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  16303. \path[->,bend right=15] (F1-5) edge [right] node
  16304. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16305. \path[->,bend left=15] (C3-2) edge [left] node
  16306. {\ttfamily\footnotesize select\_instr.} (x86-2);
  16307. \path[->,bend right=15] (x86-2) edge [left] node
  16308. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16309. \path[->,bend right=15] (x86-2-1) edge [below] node
  16310. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  16311. \path[->,bend right=15] (x86-2-2) edge [left] node
  16312. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  16313. \path[->,bend left=15] (x86-3) edge [above] node
  16314. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  16315. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  16316. \end{tikzpicture}
  16317. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  16318. \label{fig:Rgradual-passes}
  16319. \end{figure}
  16320. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  16321. for the compilation of \LangGrad{}.
  16322. \section{Further Reading}
  16323. This chapter just scratches the surface of gradual typing. The basic
  16324. approach described here is missing two key ingredients that one would
  16325. want in a implementation of gradual typing: blame
  16326. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  16327. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  16328. problem addressed by blame tracking is that when a cast on a
  16329. higher-order value fails, it often does so at a point in the program
  16330. that is far removed from the original cast. Blame tracking is a
  16331. technique for propagating extra information through casts and proxies
  16332. so that when a cast fails, the error message can point back to the
  16333. original location of the cast in the source program.
  16334. The problem addressed by space-efficient casts also relates to
  16335. higher-order casts. It turns out that in partially typed programs, a
  16336. function or vector can flow through very-many casts at runtime. With
  16337. the approach described in this chapter, each cast adds another
  16338. \code{lambda} wrapper or a vector proxy. Not only does this take up
  16339. considerable space, but it also makes the function calls and vector
  16340. operations slow. For example, a partially-typed version of quicksort
  16341. could, in the worst case, build a chain of proxies of length $O(n)$
  16342. around the vector, changing the overall time complexity of the
  16343. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  16344. solution to this problem by representing casts using the coercion
  16345. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  16346. long chains of proxies by compressing them into a concise normal
  16347. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  16348. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  16349. the Grift compiler.
  16350. \begin{center}
  16351. \url{https://github.com/Gradual-Typing/Grift}
  16352. \end{center}
  16353. There are also interesting interactions between gradual typing and
  16354. other language features, such as parametetric polymorphism,
  16355. information-flow types, and type inference, to name a few. We
  16356. recommend the reader to the online gradual typing bibliography:
  16357. \begin{center}
  16358. \url{http://samth.github.io/gradual-typing-bib/}
  16359. \end{center}
  16360. % TODO: challenge problem:
  16361. % type analysis and type specialization?
  16362. % coercions?
  16363. \fi
  16364. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16365. \chapter{Parametric Polymorphism}
  16366. \label{ch:Rpoly}
  16367. \index{subject}{parametric polymorphism}
  16368. \index{subject}{generics}
  16369. \if\edition\racketEd
  16370. This chapter studies the compilation of parametric
  16371. polymorphism\index{subject}{parametric polymorphism}
  16372. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  16373. Racket. Parametric polymorphism enables improved code reuse by
  16374. parameterizing functions and data structures with respect to the types
  16375. that they operate on. For example, Figure~\ref{fig:map-poly}
  16376. revisits the \code{map} example but this time gives it a more
  16377. fitting type. This \code{map} function is parameterized with
  16378. respect to the element type of the vector. The type of \code{map}
  16379. is the following polymorphic type as specified by the \code{All} and
  16380. the type parameter \code{a}.
  16381. \begin{lstlisting}
  16382. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  16383. \end{lstlisting}
  16384. The idea is that \code{map} can be used at \emph{all} choices of a
  16385. type for parameter \code{a}. In Figure~\ref{fig:map-poly} we apply
  16386. \code{map} to a vector of integers, a choice of \code{Integer} for
  16387. \code{a}, but we could have just as well applied \code{map} to a
  16388. vector of Booleans (and a function on Booleans).
  16389. \begin{figure}[tbp]
  16390. % poly_test_2.rkt
  16391. \begin{lstlisting}
  16392. (: map (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  16393. (define (map f v)
  16394. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16395. (define (inc [x : Integer]) : Integer (+ x 1))
  16396. (vector-ref (map inc (vector 0 41)) 1)
  16397. \end{lstlisting}
  16398. \caption{The \code{map} example using parametric polymorphism.}
  16399. \label{fig:map-poly}
  16400. \end{figure}
  16401. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  16402. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  16403. syntax. We add a second form for function definitions in which a type
  16404. declaration comes before the \code{define}. In the abstract syntax,
  16405. the return type in the \code{Def} is \code{Any}, but that should be
  16406. ignored in favor of the return type in the type declaration. (The
  16407. \code{Any} comes from using the same parser as in
  16408. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  16409. enables the use of an \code{All} type for a function, thereby making
  16410. it polymorphic. The grammar for types is extended to include
  16411. polymorphic types and type variables.
  16412. \begin{figure}[tp]
  16413. \centering
  16414. \fbox{
  16415. \begin{minipage}{0.96\textwidth}
  16416. \small
  16417. \[
  16418. \begin{array}{lcl}
  16419. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  16420. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  16421. &\MID& \LP\key{:}~\Var~\Type\RP \\
  16422. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  16423. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  16424. \end{array}
  16425. \]
  16426. \end{minipage}
  16427. }
  16428. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  16429. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  16430. \label{fig:Rpoly-concrete-syntax}
  16431. \end{figure}
  16432. \begin{figure}[tp]
  16433. \centering
  16434. \fbox{
  16435. \begin{minipage}{0.96\textwidth}
  16436. \small
  16437. \[
  16438. \begin{array}{lcl}
  16439. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  16440. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  16441. &\MID& \DECL{\Var}{\Type} \\
  16442. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  16443. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  16444. \end{array}
  16445. \]
  16446. \end{minipage}
  16447. }
  16448. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  16449. (Figure~\ref{fig:Lwhile-syntax}).}
  16450. \label{fig:Rpoly-syntax}
  16451. \end{figure}
  16452. By including polymorphic types in the $\Type$ non-terminal we choose
  16453. to make them first-class which has interesting repercussions on the
  16454. compiler. Many languages with polymorphism, such as
  16455. C++~\citep{stroustrup88:_param_types} and Standard
  16456. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  16457. it is useful to see an example of first-class polymorphism. In
  16458. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  16459. whose parameter is a polymorphic function. The occurrence of a
  16460. polymorphic type underneath a function type is enabled by the normal
  16461. recursive structure of the grammar for $\Type$ and the categorization
  16462. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  16463. applies the polymorphic function to a Boolean and to an integer.
  16464. \begin{figure}[tbp]
  16465. \begin{lstlisting}
  16466. (: apply-twice ((All (b) (b -> b)) -> Integer))
  16467. (define (apply-twice f)
  16468. (if (f #t) (f 42) (f 777)))
  16469. (: id (All (a) (a -> a)))
  16470. (define (id x) x)
  16471. (apply-twice id)
  16472. \end{lstlisting}
  16473. \caption{An example illustrating first-class polymorphism.}
  16474. \label{fig:apply-twice}
  16475. \end{figure}
  16476. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  16477. three new responsibilities (compared to \LangLoop{}). The type checking of
  16478. function application is extended to handle the case where the operator
  16479. expression is a polymorphic function. In that case the type arguments
  16480. are deduced by matching the type of the parameters with the types of
  16481. the arguments.
  16482. %
  16483. The \code{match-types} auxiliary function carries out this deduction
  16484. by recursively descending through a parameter type \code{pt} and the
  16485. corresponding argument type \code{at}, making sure that they are equal
  16486. except when there is a type parameter on the left (in the parameter
  16487. type). If it's the first time that the type parameter has been
  16488. encountered, then the algorithm deduces an association of the type
  16489. parameter to the corresponding type on the right (in the argument
  16490. type). If it's not the first time that the type parameter has been
  16491. encountered, the algorithm looks up its deduced type and makes sure
  16492. that it is equal to the type on the right.
  16493. %
  16494. Once the type arguments are deduced, the operator expression is
  16495. wrapped in an \code{Inst} AST node (for instantiate) that records the
  16496. type of the operator, but more importantly, records the deduced type
  16497. arguments. The return type of the application is the return type of
  16498. the polymorphic function, but with the type parameters replaced by the
  16499. deduced type arguments, using the \code{subst-type} function.
  16500. The second responsibility of the type checker is extending the
  16501. function \code{type-equal?} to handle the \code{All} type. This is
  16502. not quite a simple as equal on other types, such as function and
  16503. vector types, because two polymorphic types can be syntactically
  16504. different even though they are equivalent types. For example,
  16505. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  16506. Two polymorphic types should be considered equal if they differ only
  16507. in the choice of the names of the type parameters. The
  16508. \code{type-equal?} function in Figure~\ref{fig:type-check-Lvar0-aux}
  16509. renames the type parameters of the first type to match the type
  16510. parameters of the second type.
  16511. The third responsibility of the type checker is making sure that only
  16512. defined type variables appear in type annotations. The
  16513. \code{check-well-formed} function defined in
  16514. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  16515. sure that each type variable has been defined.
  16516. The output language of the type checker is \LangInst{}, defined in
  16517. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  16518. declaration and polymorphic function into a single definition, using
  16519. the \code{Poly} form, to make polymorphic functions more convenient to
  16520. process in next pass of the compiler.
  16521. \begin{figure}[tp]
  16522. \centering
  16523. \fbox{
  16524. \begin{minipage}{0.96\textwidth}
  16525. \small
  16526. \[
  16527. \begin{array}{lcl}
  16528. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  16529. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  16530. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  16531. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  16532. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  16533. \end{array}
  16534. \]
  16535. \end{minipage}
  16536. }
  16537. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  16538. (Figure~\ref{fig:Lwhile-syntax}).}
  16539. \label{fig:Rpoly-prime-syntax}
  16540. \end{figure}
  16541. The output of the type checker on the polymorphic \code{map}
  16542. example is listed in Figure~\ref{fig:map-type-check}.
  16543. \begin{figure}[tbp]
  16544. % poly_test_2.rkt
  16545. \begin{lstlisting}
  16546. (poly (a) (define (map [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  16547. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  16548. (define (inc [x : Integer]) : Integer (+ x 1))
  16549. (vector-ref ((inst map (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  16550. (Integer))
  16551. inc (vector 0 41)) 1)
  16552. \end{lstlisting}
  16553. \caption{Output of the type checker on the \code{map} example.}
  16554. \label{fig:map-type-check}
  16555. \end{figure}
  16556. \begin{figure}[tbp]
  16557. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  16558. (define type-check-poly-class
  16559. (class type-check-Rwhile-class
  16560. (super-new)
  16561. (inherit check-type-equal?)
  16562. (define/override (type-check-apply env e1 es)
  16563. (define-values (e^ ty) ((type-check-exp env) e1))
  16564. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  16565. ((type-check-exp env) e)))
  16566. (match ty
  16567. [`(,ty^* ... -> ,rt)
  16568. (for ([arg-ty ty*] [param-ty ty^*])
  16569. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  16570. (values e^ es^ rt)]
  16571. [`(All ,xs (,tys ... -> ,rt))
  16572. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  16573. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  16574. (match-types env^^ param-ty arg-ty)))
  16575. (define targs
  16576. (for/list ([x xs])
  16577. (match (dict-ref env^^ x (lambda () #f))
  16578. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  16579. x (Apply e1 es))]
  16580. [ty ty])))
  16581. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  16582. [else (error 'type-check "expected a function, not ~a" ty)]))
  16583. (define/override ((type-check-exp env) e)
  16584. (match e
  16585. [(Lambda `([,xs : ,Ts] ...) rT body)
  16586. (for ([T Ts]) ((check-well-formed env) T))
  16587. ((check-well-formed env) rT)
  16588. ((super type-check-exp env) e)]
  16589. [(HasType e1 ty)
  16590. ((check-well-formed env) ty)
  16591. ((super type-check-exp env) e)]
  16592. [else ((super type-check-exp env) e)]))
  16593. (define/override ((type-check-def env) d)
  16594. (verbose 'type-check "poly/def" d)
  16595. (match d
  16596. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  16597. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  16598. (for ([p ps]) ((check-well-formed ts-env) p))
  16599. ((check-well-formed ts-env) rt)
  16600. (define new-env (append ts-env (map cons xs ps) env))
  16601. (define-values (body^ ty^) ((type-check-exp new-env) body))
  16602. (check-type-equal? ty^ rt body)
  16603. (Generic ts (Def f p:t* rt info body^))]
  16604. [else ((super type-check-def env) d)]))
  16605. (define/override (type-check-program p)
  16606. (match p
  16607. [(Program info body)
  16608. (type-check-program (ProgramDefsExp info '() body))]
  16609. [(ProgramDefsExp info ds body)
  16610. (define ds^ (combine-decls-defs ds))
  16611. (define new-env (for/list ([d ds^])
  16612. (cons (def-name d) (fun-def-type d))))
  16613. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  16614. (define-values (body^ ty) ((type-check-exp new-env) body))
  16615. (check-type-equal? ty 'Integer body)
  16616. (ProgramDefsExp info ds^^ body^)]))
  16617. ))
  16618. \end{lstlisting}
  16619. \caption{Type checker for the \LangPoly{} language.}
  16620. \label{fig:type-check-Lvar0}
  16621. \end{figure}
  16622. \begin{figure}[tbp]
  16623. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  16624. (define/override (type-equal? t1 t2)
  16625. (match* (t1 t2)
  16626. [(`(All ,xs ,T1) `(All ,ys ,T2))
  16627. (define env (map cons xs ys))
  16628. (type-equal? (subst-type env T1) T2)]
  16629. [(other wise)
  16630. (super type-equal? t1 t2)]))
  16631. (define/public (match-types env pt at)
  16632. (match* (pt at)
  16633. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  16634. [('Void 'Void) env] [('Any 'Any) env]
  16635. [(`(Vector ,pts ...) `(Vector ,ats ...))
  16636. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  16637. (match-types env^ pt1 at1))]
  16638. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  16639. (define env^ (match-types env prt art))
  16640. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  16641. (match-types env^^ pt1 at1))]
  16642. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  16643. (define env^ (append (map cons pxs axs) env))
  16644. (match-types env^ pt1 at1)]
  16645. [((? symbol? x) at)
  16646. (match (dict-ref env x (lambda () #f))
  16647. [#f (error 'type-check "undefined type variable ~a" x)]
  16648. ['Type (cons (cons x at) env)]
  16649. [t^ (check-type-equal? at t^ 'matching) env])]
  16650. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  16651. (define/public (subst-type env pt)
  16652. (match pt
  16653. ['Integer 'Integer] ['Boolean 'Boolean]
  16654. ['Void 'Void] ['Any 'Any]
  16655. [`(Vector ,ts ...)
  16656. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  16657. [`(,ts ... -> ,rt)
  16658. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  16659. [`(All ,xs ,t)
  16660. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  16661. [(? symbol? x) (dict-ref env x)]
  16662. [else (error 'type-check "expected a type not ~a" pt)]))
  16663. (define/public (combine-decls-defs ds)
  16664. (match ds
  16665. ['() '()]
  16666. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  16667. (unless (equal? name f)
  16668. (error 'type-check "name mismatch, ~a != ~a" name f))
  16669. (match type
  16670. [`(All ,xs (,ps ... -> ,rt))
  16671. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  16672. (cons (Generic xs (Def name params^ rt info body))
  16673. (combine-decls-defs ds^))]
  16674. [`(,ps ... -> ,rt)
  16675. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  16676. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  16677. [else (error 'type-check "expected a function type, not ~a" type) ])]
  16678. [`(,(Def f params rt info body) . ,ds^)
  16679. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  16680. \end{lstlisting}
  16681. \caption{Auxiliary functions for type checking \LangPoly{}.}
  16682. \label{fig:type-check-Lvar0-aux}
  16683. \end{figure}
  16684. \begin{figure}[tbp]
  16685. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  16686. (define/public ((check-well-formed env) ty)
  16687. (match ty
  16688. ['Integer (void)]
  16689. ['Boolean (void)]
  16690. ['Void (void)]
  16691. [(? symbol? a)
  16692. (match (dict-ref env a (lambda () #f))
  16693. ['Type (void)]
  16694. [else (error 'type-check "undefined type variable ~a" a)])]
  16695. [`(Vector ,ts ...)
  16696. (for ([t ts]) ((check-well-formed env) t))]
  16697. [`(,ts ... -> ,t)
  16698. (for ([t ts]) ((check-well-formed env) t))
  16699. ((check-well-formed env) t)]
  16700. [`(All ,xs ,t)
  16701. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  16702. ((check-well-formed env^) t)]
  16703. [else (error 'type-check "unrecognized type ~a" ty)]))
  16704. \end{lstlisting}
  16705. \caption{Well-formed types.}
  16706. \label{fig:well-formed-types}
  16707. \end{figure}
  16708. % TODO: interpreter for R'_10
  16709. \section{Compiling Polymorphism}
  16710. \label{sec:compiling-poly}
  16711. Broadly speaking, there are four approaches to compiling parametric
  16712. polymorphism, which we describe below.
  16713. \begin{description}
  16714. \item[Monomorphization] generates a different version of a polymorphic
  16715. function for each set of type arguments that it is used with,
  16716. producing type-specialized code. This approach results in the most
  16717. efficient code but requires whole-program compilation (no separate
  16718. compilation) and increases code size. For our current purposes
  16719. monomorphization is a non-starter because, with first-class
  16720. polymorphism, it is sometimes not possible to determine which
  16721. generic functions are used with which type arguments during
  16722. compilation. (It can be done at runtime, with just-in-time
  16723. compilation.) This approach is used to compile C++
  16724. templates~\citep{stroustrup88:_param_types} and polymorphic
  16725. functions in NESL~\citep{Blelloch:1993aa} and
  16726. ML~\citep{Weeks:2006aa}.
  16727. \item[Uniform representation] generates one version of each
  16728. polymorphic function but requires all values have a common ``boxed''
  16729. format, such as the tagged values of type \code{Any} in
  16730. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  16731. similarly to code in a dynamically typed language (like \LangDyn{}),
  16732. in which primitive operators require their arguments to be projected
  16733. from \code{Any} and their results are injected into \code{Any}. (In
  16734. object-oriented languages, the projection is accomplished via
  16735. virtual method dispatch.) The uniform representation approach is
  16736. compatible with separate compilation and with first-class
  16737. polymorphism. However, it produces the least-efficient code because
  16738. it introduces overhead in the entire program, including
  16739. non-polymorphic code. This approach is used in implementations of
  16740. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  16741. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  16742. Java~\citep{Bracha:1998fk}.
  16743. \item[Mixed representation] generates one version of each polymorphic
  16744. function, using a boxed representation for type
  16745. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  16746. and conversions are performed at the boundaries between monomorphic
  16747. and polymorphic (e.g. when a polymorphic function is instantiated
  16748. and called). This approach is compatible with separate compilation
  16749. and first-class polymorphism and maintains the efficiency of
  16750. monomorphic code. The tradeoff is increased overhead at the boundary
  16751. between monomorphic and polymorphic code. This approach is used in
  16752. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  16753. Java 5 with the addition of autoboxing.
  16754. \item[Type passing] uses the unboxed representation in both
  16755. monomorphic and polymorphic code. Each polymorphic function is
  16756. compiled to a single function with extra parameters that describe
  16757. the type arguments. The type information is used by the generated
  16758. code to know how to access the unboxed values at runtime. This
  16759. approach is used in implementation of the Napier88
  16760. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  16761. passing is compatible with separate compilation and first-class
  16762. polymorphism and maintains the efficiency for monomorphic
  16763. code. There is runtime overhead in polymorphic code from dispatching
  16764. on type information.
  16765. \end{description}
  16766. In this chapter we use the mixed representation approach, partly
  16767. because of its favorable attributes, and partly because it is
  16768. straightforward to implement using the tools that we have already
  16769. built to support gradual typing. To compile polymorphic functions, we
  16770. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  16771. \LangCast{}.
  16772. \section{Erase Types}
  16773. \label{sec:erase-types}
  16774. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  16775. represent type variables. For example, Figure~\ref{fig:map-erase}
  16776. shows the output of the \code{erase-types} pass on the polymorphic
  16777. \code{map} (Figure~\ref{fig:map-poly}). The occurrences of
  16778. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  16779. \code{All} types are removed from the type of \code{map}.
  16780. \begin{figure}[tbp]
  16781. \begin{lstlisting}
  16782. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  16783. : (Vector Any Any)
  16784. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16785. (define (inc [x : Integer]) : Integer (+ x 1))
  16786. (vector-ref ((cast map
  16787. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  16788. ((Integer -> Integer) (Vector Integer Integer)
  16789. -> (Vector Integer Integer)))
  16790. inc (vector 0 41)) 1)
  16791. \end{lstlisting}
  16792. \caption{The polymorphic \code{map} example after type erasure.}
  16793. \label{fig:map-erase}
  16794. \end{figure}
  16795. This process of type erasure creates a challenge at points of
  16796. instantiation. For example, consider the instantiation of
  16797. \code{map} in Figure~\ref{fig:map-type-check}.
  16798. The type of \code{map} is
  16799. \begin{lstlisting}
  16800. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  16801. \end{lstlisting}
  16802. and it is instantiated to
  16803. \begin{lstlisting}
  16804. ((Integer -> Integer) (Vector Integer Integer)
  16805. -> (Vector Integer Integer))
  16806. \end{lstlisting}
  16807. After erasure, the type of \code{map} is
  16808. \begin{lstlisting}
  16809. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  16810. \end{lstlisting}
  16811. but we need to convert it to the instantiated type. This is easy to
  16812. do in the target language \LangCast{} with a single \code{cast}. In
  16813. Figure~\ref{fig:map-erase}, the instantiation of \code{map}
  16814. has been compiled to a \code{cast} from the type of \code{map} to
  16815. the instantiated type. The source and target type of a cast must be
  16816. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  16817. because both the source and target are obtained from the same
  16818. polymorphic type of \code{map}, replacing the type parameters with
  16819. \code{Any} in the former and with the deduced type arguments in the
  16820. later. (Recall that the \code{Any} type is consistent with any type.)
  16821. To implement the \code{erase-types} pass, we recommend defining a
  16822. recursive auxiliary function named \code{erase-type} that applies the
  16823. following two transformations. It replaces type variables with
  16824. \code{Any}
  16825. \begin{lstlisting}
  16826. |$x$|
  16827. |$\Rightarrow$|
  16828. Any
  16829. \end{lstlisting}
  16830. and it removes the polymorphic \code{All} types.
  16831. \begin{lstlisting}
  16832. (All |$xs$| |$T_1$|)
  16833. |$\Rightarrow$|
  16834. |$T'_1$|
  16835. \end{lstlisting}
  16836. Apply the \code{erase-type} function to all of the type annotations in
  16837. the program.
  16838. Regarding the translation of expressions, the case for \code{Inst} is
  16839. the interesting one. We translate it into a \code{Cast}, as shown
  16840. below. The type of the subexpression $e$ is the polymorphic type
  16841. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  16842. $T$, the type $T'$. The target type $T''$ is the result of
  16843. substituting the arguments types $ts$ for the type parameters $xs$ in
  16844. $T$ followed by doing type erasure.
  16845. \begin{lstlisting}
  16846. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  16847. |$\Rightarrow$|
  16848. (Cast |$e'$| |$T'$| |$T''$|)
  16849. \end{lstlisting}
  16850. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  16851. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  16852. Finally, each polymorphic function is translated to a regular
  16853. functions in which type erasure has been applied to all the type
  16854. annotations and the body.
  16855. \begin{lstlisting}
  16856. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  16857. |$\Rightarrow$|
  16858. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  16859. \end{lstlisting}
  16860. \begin{exercise}\normalfont
  16861. Implement a compiler for the polymorphic language \LangPoly{} by
  16862. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  16863. programs that use polymorphic functions. Some of them should make
  16864. use of first-class polymorphism.
  16865. \end{exercise}
  16866. \begin{figure}[p]
  16867. \begin{tikzpicture}[baseline=(current bounding box.center)]
  16868. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  16869. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  16870. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  16871. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  16872. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  16873. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  16874. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  16875. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  16876. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  16877. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  16878. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  16879. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  16880. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  16881. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  16882. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  16883. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  16884. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  16885. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  16886. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  16887. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  16888. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  16889. \path[->,bend right=15] (Rpoly) edge [above] node
  16890. {\ttfamily\footnotesize type\_check} (Rpolyp);
  16891. \path[->,bend right=15] (Rpolyp) edge [above] node
  16892. {\ttfamily\footnotesize erase\_types} (Rgradualp);
  16893. \path[->,bend right=15] (Rgradualp) edge [above] node
  16894. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  16895. \path[->,bend right=15] (Rwhilepp) edge [right] node
  16896. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  16897. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  16898. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  16899. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  16900. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  16901. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  16902. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  16903. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  16904. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  16905. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  16906. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16907. \path[->,bend left=15] (F1-1) edge [below] node
  16908. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  16909. \path[->,bend right=15] (F1-2) edge [above] node
  16910. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  16911. \path[->,bend right=15] (F1-3) edge [above] node
  16912. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  16913. \path[->,bend right=15] (F1-4) edge [above] node
  16914. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  16915. \path[->,bend right=15] (F1-5) edge [right] node
  16916. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16917. \path[->,bend left=15] (C3-2) edge [left] node
  16918. {\ttfamily\footnotesize select\_instr.} (x86-2);
  16919. \path[->,bend right=15] (x86-2) edge [left] node
  16920. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16921. \path[->,bend right=15] (x86-2-1) edge [below] node
  16922. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  16923. \path[->,bend right=15] (x86-2-2) edge [left] node
  16924. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  16925. \path[->,bend left=15] (x86-3) edge [above] node
  16926. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  16927. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  16928. \end{tikzpicture}
  16929. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  16930. \label{fig:Rpoly-passes}
  16931. \end{figure}
  16932. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  16933. for the compilation of \LangPoly{}.
  16934. % TODO: challenge problem: specialization of instantiations
  16935. % Further Reading
  16936. \fi
  16937. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16938. \clearpage
  16939. \appendix
  16940. \chapter{Appendix}
  16941. \if\edition\racketEd
  16942. \section{Interpreters}
  16943. \label{appendix:interp}
  16944. \index{subject}{interpreter}
  16945. We provide interpreters for each of the source languages \LangInt{},
  16946. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  16947. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  16948. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  16949. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  16950. and x86 are in the \key{interp.rkt} file.
  16951. \section{Utility Functions}
  16952. \label{appendix:utilities}
  16953. The utility functions described in this section are in the
  16954. \key{utilities.rkt} file of the support code.
  16955. \paragraph{\code{interp-tests}}
  16956. The \key{interp-tests} function runs the compiler passes and the
  16957. interpreters on each of the specified tests to check whether each pass
  16958. is correct. The \key{interp-tests} function has the following
  16959. parameters:
  16960. \begin{description}
  16961. \item[name (a string)] a name to identify the compiler,
  16962. \item[typechecker] a function of exactly one argument that either
  16963. raises an error using the \code{error} function when it encounters a
  16964. type error, or returns \code{\#f} when it encounters a type
  16965. error. If there is no type error, the type checker returns the
  16966. program.
  16967. \item[passes] a list with one entry per pass. An entry is a list with
  16968. four things:
  16969. \begin{enumerate}
  16970. \item a string giving the name of the pass,
  16971. \item the function that implements the pass (a translator from AST
  16972. to AST),
  16973. \item a function that implements the interpreter (a function from
  16974. AST to result value) for the output language,
  16975. \item and a type checker for the output language. Type checkers for
  16976. the $R$ and $C$ languages are provided in the support code. For
  16977. example, the type checkers for \LangVar{} and \LangCVar{} are in
  16978. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  16979. type checker entry is optional. The support code does not provide
  16980. type checkers for the x86 languages.
  16981. \end{enumerate}
  16982. \item[source-interp] an interpreter for the source language. The
  16983. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  16984. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  16985. \item[tests] a list of test numbers that specifies which tests to
  16986. run. (see below)
  16987. \end{description}
  16988. %
  16989. The \key{interp-tests} function assumes that the subdirectory
  16990. \key{tests} has a collection of Racket programs whose names all start
  16991. with the family name, followed by an underscore and then the test
  16992. number, ending with the file extension \key{.rkt}. Also, for each test
  16993. program that calls \code{read} one or more times, there is a file with
  16994. the same name except that the file extension is \key{.in} that
  16995. provides the input for the Racket program. If the test program is
  16996. expected to fail type checking, then there should be an empty file of
  16997. the same name but with extension \key{.tyerr}.
  16998. \paragraph{\code{compiler-tests}}
  16999. runs the compiler passes to generate x86 (a \key{.s} file) and then
  17000. runs the GNU C compiler (gcc) to generate machine code. It runs the
  17001. machine code and checks that the output is $42$. The parameters to the
  17002. \code{compiler-tests} function are similar to those of the
  17003. \code{interp-tests} function, and consist of
  17004. \begin{itemize}
  17005. \item a compiler name (a string),
  17006. \item a type checker,
  17007. \item description of the passes,
  17008. \item name of a test-family, and
  17009. \item a list of test numbers.
  17010. \end{itemize}
  17011. \paragraph{\code{compile-file}}
  17012. takes a description of the compiler passes (see the comment for
  17013. \key{interp-tests}) and returns a function that, given a program file
  17014. name (a string ending in \key{.rkt}), applies all of the passes and
  17015. writes the output to a file whose name is the same as the program file
  17016. name but with \key{.rkt} replaced with \key{.s}.
  17017. \paragraph{\code{read-program}}
  17018. takes a file path and parses that file (it must be a Racket program)
  17019. into an abstract syntax tree.
  17020. \paragraph{\code{parse-program}}
  17021. takes an S-expression representation of an abstract syntax tree and converts it into
  17022. the struct-based representation.
  17023. \paragraph{\code{assert}}
  17024. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  17025. and displays the message \key{msg} if the Boolean \key{bool} is false.
  17026. \paragraph{\code{lookup}}
  17027. % remove discussion of lookup? -Jeremy
  17028. takes a key and an alist, and returns the first value that is
  17029. associated with the given key, if there is one. If not, an error is
  17030. triggered. The alist may contain both immutable pairs (built with
  17031. \key{cons}) and mutable pairs (built with \key{mcons}).
  17032. %The \key{map2} function ...
  17033. \fi %\racketEd
  17034. \section{x86 Instruction Set Quick-Reference}
  17035. \label{sec:x86-quick-reference}
  17036. \index{subject}{x86}
  17037. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  17038. do. We write $A \to B$ to mean that the value of $A$ is written into
  17039. location $B$. Address offsets are given in bytes. The instruction
  17040. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  17041. registers (such as \code{\%rax}), or memory references (such as
  17042. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  17043. reference per instruction. Other operands must be immediates or
  17044. registers.
  17045. \begin{table}[tbp]
  17046. \centering
  17047. \begin{tabular}{l|l}
  17048. \textbf{Instruction} & \textbf{Operation} \\ \hline
  17049. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  17050. \texttt{negq} $A$ & $- A \to A$ \\
  17051. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  17052. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  17053. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  17054. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  17055. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  17056. \texttt{retq} & Pops the return address and jumps to it \\
  17057. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  17058. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  17059. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  17060. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  17061. be an immediate) \\
  17062. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  17063. matches the condition code of the instruction, otherwise go to the
  17064. next instructions. The condition codes are \key{e} for ``equal'',
  17065. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  17066. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  17067. \texttt{jl} $L$ & \\
  17068. \texttt{jle} $L$ & \\
  17069. \texttt{jg} $L$ & \\
  17070. \texttt{jge} $L$ & \\
  17071. \texttt{jmp} $L$ & Jump to label $L$ \\
  17072. \texttt{movq} $A$, $B$ & $A \to B$ \\
  17073. \texttt{movzbq} $A$, $B$ &
  17074. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  17075. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  17076. and the extra bytes of $B$ are set to zero.} \\
  17077. & \\
  17078. & \\
  17079. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  17080. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  17081. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  17082. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  17083. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  17084. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  17085. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  17086. description of the condition codes. $A$ must be a single byte register
  17087. (e.g., \texttt{al} or \texttt{cl}).} \\
  17088. \texttt{setl} $A$ & \\
  17089. \texttt{setle} $A$ & \\
  17090. \texttt{setg} $A$ & \\
  17091. \texttt{setge} $A$ &
  17092. \end{tabular}
  17093. \vspace{5pt}
  17094. \caption{Quick-reference for the x86 instructions used in this book.}
  17095. \label{tab:x86-instr}
  17096. \end{table}
  17097. \if\edition\racketEd
  17098. \cleardoublepage
  17099. \section{Concrete Syntax for Intermediate Languages}
  17100. The concrete syntax of \LangAny{} is defined in
  17101. Figure~\ref{fig:Rany-concrete-syntax}.
  17102. \begin{figure}[tp]
  17103. \centering
  17104. \fbox{
  17105. \begin{minipage}{0.97\textwidth}\small
  17106. \[
  17107. \begin{array}{lcl}
  17108. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  17109. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  17110. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \key{Any} \\
  17111. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17112. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  17113. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  17114. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  17115. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  17116. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  17117. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  17118. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  17119. \MID \LP\key{void?}\;\Exp\RP \\
  17120. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  17121. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  17122. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  17123. \end{array}
  17124. \]
  17125. \end{minipage}
  17126. }
  17127. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  17128. (Figure~\ref{fig:Rlam-syntax}).}
  17129. \label{fig:Rany-concrete-syntax}
  17130. \end{figure}
  17131. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  17132. defined in Figures~\ref{fig:c0-concrete-syntax},
  17133. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  17134. and \ref{fig:c3-concrete-syntax}, respectively.
  17135. \begin{figure}[tbp]
  17136. \fbox{
  17137. \begin{minipage}{0.96\textwidth}
  17138. \small
  17139. \[
  17140. \begin{array}{lcl}
  17141. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  17142. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  17143. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  17144. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  17145. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  17146. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  17147. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  17148. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  17149. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  17150. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  17151. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  17152. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  17153. \end{array}
  17154. \]
  17155. \end{minipage}
  17156. }
  17157. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  17158. \label{fig:c2-concrete-syntax}
  17159. \end{figure}
  17160. \begin{figure}[tp]
  17161. \fbox{
  17162. \begin{minipage}{0.96\textwidth}
  17163. \small
  17164. \[
  17165. \begin{array}{lcl}
  17166. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  17167. \\
  17168. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  17169. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  17170. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  17171. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  17172. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  17173. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  17174. &\MID& \LP\key{fun-ref}~\itm{label}\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  17175. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  17176. \MID \LP\key{collect} \,\itm{int}\RP }\\
  17177. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  17178. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  17179. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  17180. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  17181. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  17182. \LangCFunM{} & ::= & \Def\ldots
  17183. \end{array}
  17184. \]
  17185. \end{minipage}
  17186. }
  17187. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  17188. \label{fig:c3-concrete-syntax}
  17189. \end{figure}
  17190. \fi % racketEd
  17191. \backmatter
  17192. \addtocontents{toc}{\vspace{11pt}}
  17193. %% \addtocontents{toc}{\vspace{11pt}}
  17194. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  17195. \nocite{*}\let\bibname\refname
  17196. \addcontentsline{toc}{fmbm}{\refname}
  17197. \printbibliography
  17198. \printindex{authors}{Author Index}
  17199. \printindex{subject}{Subject Index}
  17200. \end{document}
  17201. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  17202. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  17203. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  17204. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  17205. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  17206. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  17207. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  17208. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  17209. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  17210. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  17211. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  17212. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  17213. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  17214. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  17215. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  17216. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  17217. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  17218. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  17219. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS
  17220. % LocalWords: morekeywords fullflexible