book.tex 674 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169
  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,let},
  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\racketEd
  2301. The main difference compared to the concrete syntax of \LangXInt{}
  2302. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2303. front of every instruction. Instead instructions are grouped into
  2304. \emph{blocks}\index{subject}{block} with a
  2305. label associated with every block, which is why the \key{X86Program}
  2306. struct includes an alist mapping labels to blocks. The reason for this
  2307. organization becomes apparent in Chapter~\ref{ch:Lif} when we
  2308. introduce conditional branching. The \code{Block} structure includes
  2309. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2310. useful in Chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2311. $\itm{info}$ field should contain an empty list.
  2312. \fi}
  2313. %
  2314. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2315. node includes an integer for representing the arity of the function,
  2316. i.e., the number of arguments, which is helpful to know during
  2317. register allocation (Chapter~\ref{ch:register-allocation-Lvar}).
  2318. \begin{figure}[tp]
  2319. \fbox{
  2320. \begin{minipage}{0.98\textwidth}
  2321. \small
  2322. {\if\edition\racketEd
  2323. \[
  2324. \begin{array}{lcl}
  2325. \Reg &::=& \allregisters{} \\
  2326. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2327. \MID \DEREF{\Reg}{\Int} \\
  2328. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2329. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2330. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2331. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2332. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2333. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2334. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2335. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2336. \end{array}
  2337. \]
  2338. \fi}
  2339. {\if\edition\pythonEd
  2340. \[
  2341. \begin{array}{lcl}
  2342. \Reg &::=& \allregisters{} \\
  2343. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2344. \MID \DEREF{\Reg}{\Int} \\
  2345. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2346. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2347. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2348. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2349. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg}\\
  2350. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2351. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2352. \end{array}
  2353. \]
  2354. \fi}
  2355. \end{minipage}
  2356. }
  2357. \caption{The abstract syntax of \LangXInt{} assembly.}
  2358. \label{fig:x86-int-ast}
  2359. \end{figure}
  2360. \section{Planning the trip to x86}
  2361. \label{sec:plan-s0-x86}
  2362. To compile one language to another it helps to focus on the
  2363. differences between the two languages because the compiler will need
  2364. to bridge those differences. What are the differences between \LangVar{}
  2365. and x86 assembly? Here are some of the most important ones:
  2366. \begin{enumerate}
  2367. \item x86 arithmetic instructions typically have two arguments and
  2368. update the second argument in place. In contrast, \LangVar{}
  2369. arithmetic operations take two arguments and produce a new value.
  2370. An x86 instruction may have at most one memory-accessing argument.
  2371. Furthermore, some x86 instructions place special restrictions on
  2372. their arguments.
  2373. \item An argument of an \LangVar{} operator can be a deeply-nested
  2374. expression, whereas x86 instructions restrict their arguments to be
  2375. integer constants, registers, and memory locations.
  2376. {\if\edition\racketEd
  2377. \item The order of execution in x86 is explicit in the syntax: a
  2378. sequence of instructions and jumps to labeled positions, whereas in
  2379. \LangVar{} the order of evaluation is a left-to-right depth-first
  2380. traversal of the abstract syntax tree.
  2381. \fi}
  2382. \item A program in \LangVar{} can have any number of variables
  2383. whereas x86 has 16 registers and the procedure call stack.
  2384. {\if\edition\racketEd
  2385. \item Variables in \LangVar{} can shadow other variables with the
  2386. same name. In x86, registers have unique names and memory locations
  2387. have unique addresses.
  2388. \fi}
  2389. \end{enumerate}
  2390. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2391. down the problem into several steps, dealing with the above
  2392. differences one at a time. Each of these steps is called a \emph{pass}
  2393. of the compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2394. %
  2395. This terminology comes from the way each step passes over, that is,
  2396. traverses the AST of the program.
  2397. %
  2398. Furthermore, we follow the nanopass approach, which means we strive
  2399. for each pass to accomplish one clear objective (not two or three at
  2400. the same time).
  2401. %
  2402. We begin by sketching how we might implement each pass, and give them
  2403. names. We then figure out an ordering of the passes and the
  2404. input/output language for each pass. The very first pass has
  2405. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2406. its output language. In between we can choose whichever language is
  2407. most convenient for expressing the output of each pass, whether that
  2408. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2409. our own design. Finally, to implement each pass we write one
  2410. recursive function per non-terminal in the grammar of the input
  2411. language of the pass. \index{subject}{intermediate language}
  2412. Our compiler for \LangVar{} consists of the following passes.
  2413. %
  2414. \begin{description}
  2415. {\if\edition\racketEd
  2416. \item[\key{uniquify}] deals with the shadowing of variables by
  2417. renaming every variable to a unique name.
  2418. \fi}
  2419. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2420. of a primitive operation or function call is a variable or integer,
  2421. that is, an \emph{atomic} expression. We refer to non-atomic
  2422. expressions as \emph{complex}. This pass introduces temporary
  2423. variables to hold the results of complex
  2424. subexpressions.\index{subject}{atomic
  2425. expression}\index{subject}{complex expression}%
  2426. {\if\edition\racketEd
  2427. \item[\key{explicate\_control}] makes the execution order of the
  2428. program explicit. It converts the abstract syntax tree representation
  2429. into a control-flow graph in which each node contains a sequence of
  2430. statements and the edges between nodes say which nodes contain jumps
  2431. to other nodes.
  2432. \fi}
  2433. \item[\key{select\_instructions}] handles the difference between
  2434. \LangVar{} operations and x86 instructions. This pass converts each
  2435. \LangVar{} operation to a short sequence of instructions that
  2436. accomplishes the same task.
  2437. \item[\key{assign\_homes}] replaces variables with registers or stack
  2438. locations.
  2439. \end{description}
  2440. %
  2441. {\if\edition\racketEd
  2442. %
  2443. Our treatment of \code{remove\_complex\_operands} and
  2444. \code{explicate\_control} as separate passes is an example of the
  2445. nanopass approach\footnote{For analogous decompositions of the
  2446. translation into continuation passing style, see the work of
  2447. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2448. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2449. %
  2450. \fi}
  2451. The next question is: in what order should we apply these passes? This
  2452. question can be challenging because it is difficult to know ahead of
  2453. time which orderings will be better (easier to implement, produce more
  2454. efficient code, etc.) so oftentimes trial-and-error is
  2455. involved. Nevertheless, we can try to plan ahead and make educated
  2456. choices regarding the ordering.
  2457. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2458. \key{uniquify}? The \key{uniquify} pass should come first because
  2459. \key{explicate\_control} changes all the \key{let}-bound variables to
  2460. become local variables whose scope is the entire program, which would
  2461. confuse variables with the same name.}
  2462. %
  2463. \racket{We place \key{remove\_complex\_opera*} before \key{explicate\_control}
  2464. because the later removes the \key{let} form, but it is convenient to
  2465. use \key{let} in the output of \key{remove\_complex\_opera*}.}
  2466. %
  2467. \racket{The ordering of \key{uniquify} with respect to
  2468. \key{remove\_complex\_opera*} does not matter so we arbitrarily choose
  2469. \key{uniquify} to come first.}
  2470. The \key{select\_instructions} and \key{assign\_homes} passes are
  2471. intertwined.
  2472. %
  2473. In Chapter~\ref{ch:Rfun} we learn that, in x86, registers are used for
  2474. passing arguments to functions and it is preferable to assign
  2475. parameters to their corresponding registers. This suggests that it
  2476. would be better to start with the \key{select\_instructions} pass,
  2477. which generates the instructions for argument passing, before
  2478. performing register allocation.
  2479. %
  2480. On the other hand, by selecting instructions first we may run into a
  2481. dead end in \key{assign\_homes}. Recall that only one argument of an
  2482. x86 instruction may be a memory access but \key{assign\_homes} might
  2483. be forced to assign both arguments to memory locations.
  2484. %
  2485. A sophisticated approach is to iteratively repeat the two passes until
  2486. a solution is found. However, to reduce implementation complexity we
  2487. recommend placing \key{select\_instructions} first, followed by the
  2488. \key{assign\_homes}, then a third pass named \key{patch\_instructions}
  2489. that uses a reserved register to fix outstanding problems.
  2490. \begin{figure}[tbp]
  2491. {\if\edition\racketEd
  2492. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2493. \node (Lvar) at (0,2) {\large \LangVar{}};
  2494. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2495. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  2496. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2497. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2498. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2499. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2500. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2501. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2502. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2503. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  2504. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2505. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2506. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2507. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2508. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  2509. \end{tikzpicture}
  2510. \fi}
  2511. {\if\edition\pythonEd
  2512. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2513. \node (Lvar) at (0,2) {\large \LangVar{}};
  2514. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2515. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2516. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2517. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2518. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2519. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2520. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2521. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2522. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2523. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2524. \end{tikzpicture}
  2525. \fi}
  2526. \caption{Diagram of the passes for compiling \LangVar{}. }
  2527. \label{fig:Lvar-passes}
  2528. \end{figure}
  2529. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2530. passes and identifies the input and output language of each pass.
  2531. %
  2532. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2533. language, which extends \LangXInt{} with an unbounded number of
  2534. program-scope variables and removes the restrictions regarding
  2535. instruction arguments.
  2536. %
  2537. The last pass, \key{prelude\_and\_conclusion}, places the program
  2538. instructions inside a \code{main} function with instructions for the
  2539. prelude and conclusion.
  2540. %
  2541. \racket{In the following section we discuss the \LangCVar{}
  2542. intermediate language.}
  2543. %
  2544. The remainder of this chapter provides guidance on the implementation
  2545. of each of the compiler passes in Figure~\ref{fig:Lvar-passes}.
  2546. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2547. %% are programs that are still in the \LangVar{} language, though the
  2548. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2549. %% (Section~\ref{sec:remove-complex-opera-Lvar}).
  2550. %% %
  2551. %% The output of \code{explicate\_control} is in an intermediate language
  2552. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2553. %% syntax, which we introduce in the next section. The
  2554. %% \key{select-instruction} pass translates from \LangCVar{} to
  2555. %% \LangXVar{}. The \key{assign-homes} and
  2556. %% \key{patch-instructions}
  2557. %% passes input and output variants of x86 assembly.
  2558. \newcommand{\CvarGrammarRacket}{
  2559. \begin{array}{lcl}
  2560. \Atm &::=& \Int \MID \Var \\
  2561. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2562. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2563. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2564. \end{array}
  2565. }
  2566. \newcommand{\CvarASTRacket}{
  2567. \begin{array}{lcl}
  2568. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2569. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2570. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2571. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2572. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2573. \end{array}
  2574. }
  2575. {\if\edition\racketEd
  2576. \subsection{The \LangCVar{} Intermediate Language}
  2577. The output of \code{explicate\_control} is similar to the $C$
  2578. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2579. categories for expressions and statements, so we name it \LangCVar{}.
  2580. This style of intermediate language is also known as
  2581. \emph{three-address code}, to emphasize that the typical form of a
  2582. statement is \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2583. addresses~\citep{Aho:2006wb}.
  2584. The concrete syntax for \LangCVar{} is defined in
  2585. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for
  2586. \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2587. %
  2588. The \LangCVar{} language supports the same operators as \LangVar{} but
  2589. the arguments of operators are restricted to atomic
  2590. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2591. assignment statements which can be executed in sequence using the
  2592. \key{Seq} form. A sequence of statements always ends with
  2593. \key{Return}, a guarantee that is baked into the grammar rules for
  2594. \itm{tail}. The naming of this non-terminal comes from the term
  2595. \emph{tail position}\index{subject}{tail position}, which refers to an
  2596. expression that is the last one to execute within a function.
  2597. A \LangCVar{} program consists of an alist mapping labels to
  2598. tails. This is more general than necessary for the present chapter, as
  2599. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2600. us from having to change the syntax in Chapter~\ref{ch:Lif}. For now
  2601. there will be just one label, \key{start}, and the whole program is
  2602. its tail.
  2603. %
  2604. The $\itm{info}$ field of the \key{CProgram} form, after the
  2605. \code{explicate\_control} pass, contains a mapping from the symbol
  2606. \key{locals} to a list of variables, that is, a list of all the
  2607. variables used in the program. At the start of the program, these
  2608. variables are uninitialized; they become initialized on their first
  2609. assignment.
  2610. \begin{figure}[tbp]
  2611. \fbox{
  2612. \begin{minipage}{0.96\textwidth}
  2613. \[
  2614. \begin{array}{l}
  2615. \CvarGrammarRacket \\
  2616. \begin{array}{lcl}
  2617. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2618. \end{array}
  2619. \end{array}
  2620. \]
  2621. \end{minipage}
  2622. }
  2623. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2624. \label{fig:c0-concrete-syntax}
  2625. \end{figure}
  2626. \begin{figure}[tbp]
  2627. \fbox{
  2628. \begin{minipage}{0.96\textwidth}
  2629. \[
  2630. \begin{array}{l}
  2631. \CvarASTRacket \\
  2632. \begin{array}{lcl}
  2633. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2634. \end{array}
  2635. \end{array}
  2636. \]
  2637. \end{minipage}
  2638. }
  2639. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2640. \label{fig:c0-syntax}
  2641. \end{figure}
  2642. The definitional interpreter for \LangCVar{} is in the support code,
  2643. in the file \code{interp-Cvar.rkt}.
  2644. \fi}
  2645. {\if\edition\racketEd
  2646. \section{Uniquify Variables}
  2647. \label{sec:uniquify-Lvar}
  2648. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2649. programs in which every \key{let} binds a unique variable name. For
  2650. example, the \code{uniquify} pass should translate the program on the
  2651. left into the program on the right.
  2652. \begin{transformation}
  2653. \begin{lstlisting}
  2654. (let ([x 32])
  2655. (+ (let ([x 10]) x) x))
  2656. \end{lstlisting}
  2657. \compilesto
  2658. \begin{lstlisting}
  2659. (let ([x.1 32])
  2660. (+ (let ([x.2 10]) x.2) x.1))
  2661. \end{lstlisting}
  2662. \end{transformation}
  2663. The following is another example translation, this time of a program
  2664. with a \key{let} nested inside the initializing expression of another
  2665. \key{let}.
  2666. \begin{transformation}
  2667. \begin{lstlisting}
  2668. (let ([x (let ([x 4])
  2669. (+ x 1))])
  2670. (+ x 2))
  2671. \end{lstlisting}
  2672. \compilesto
  2673. \begin{lstlisting}
  2674. (let ([x.2 (let ([x.1 4])
  2675. (+ x.1 1))])
  2676. (+ x.2 2))
  2677. \end{lstlisting}
  2678. \end{transformation}
  2679. We recommend implementing \code{uniquify} by creating a structurally
  2680. recursive function named \code{uniquify-exp} that mostly just copies
  2681. an expression. However, when encountering a \key{let}, it should
  2682. generate a unique name for the variable and associate the old name
  2683. with the new name in an alist.\footnote{The Racket function
  2684. \code{gensym} is handy for generating unique variable names.} The
  2685. \code{uniquify-exp} function needs to access this alist when it gets
  2686. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2687. for the alist.
  2688. The skeleton of the \code{uniquify-exp} function is shown in
  2689. Figure~\ref{fig:uniquify-Lvar}. The function is curried so that it is
  2690. convenient to partially apply it to an alist and then apply it to
  2691. different expressions, as in the last case for primitive operations in
  2692. Figure~\ref{fig:uniquify-Lvar}. The
  2693. %
  2694. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2695. %
  2696. form of Racket is useful for transforming each element of a list to
  2697. produce a new list.\index{subject}{for/list}
  2698. \begin{figure}[tbp]
  2699. \begin{lstlisting}
  2700. (define (uniquify-exp env)
  2701. (lambda (e)
  2702. (match e
  2703. [(Var x) ___]
  2704. [(Int n) (Int n)]
  2705. [(Let x e body) ___]
  2706. [(Prim op es)
  2707. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2708. (define (uniquify p)
  2709. (match p
  2710. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2711. \end{lstlisting}
  2712. \caption{Skeleton for the \key{uniquify} pass.}
  2713. \label{fig:uniquify-Lvar}
  2714. \end{figure}
  2715. \begin{exercise}
  2716. \normalfont % I don't like the italics for exercises. -Jeremy
  2717. Complete the \code{uniquify} pass by filling in the blanks in
  2718. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2719. variables and for the \key{let} form in the file \code{compiler.rkt}
  2720. in the support code.
  2721. \end{exercise}
  2722. \begin{exercise}
  2723. \normalfont % I don't like the italics for exercises. -Jeremy
  2724. \label{ex:Lvar}
  2725. Create five \LangVar{} programs that exercise the most interesting
  2726. parts of the \key{uniquify} pass, that is, the programs should include
  2727. \key{let} forms, variables, and variables that shadow each other.
  2728. The five programs should be placed in the subdirectory named
  2729. \key{tests} and the file names should start with \code{var\_test\_}
  2730. followed by a unique integer and end with the file extension
  2731. \key{.rkt}.
  2732. %
  2733. The \key{run-tests.rkt} script in the support code checks whether the
  2734. output programs produce the same result as the input programs. The
  2735. script uses the \key{interp-tests} function
  2736. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2737. your \key{uniquify} pass on the example programs. The \code{passes}
  2738. parameter of \key{interp-tests} is a list that should have one entry
  2739. for each pass in your compiler. For now, define \code{passes} to
  2740. contain just one entry for \code{uniquify} as shown below.
  2741. \begin{lstlisting}
  2742. (define passes
  2743. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2744. \end{lstlisting}
  2745. Run the \key{run-tests.rkt} script in the support code to check
  2746. whether the output programs produce the same result as the input
  2747. programs.
  2748. \end{exercise}
  2749. \fi}
  2750. \section{Remove Complex Operands}
  2751. \label{sec:remove-complex-opera-Lvar}
  2752. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2753. into a restricted form in which the arguments of operations are atomic
  2754. expressions. Put another way, this pass removes complex
  2755. operands\index{subject}{complex operand}, such as the expression
  2756. \racket{\code{(- 10)}}\python{\code{-10}}
  2757. in the program below. This is accomplished by introducing a new
  2758. temporary variable, assigning the complex operand to the new
  2759. variable, and then using the new variable in place of the complex
  2760. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2761. right.
  2762. {\if\edition\racketEd
  2763. \begin{transformation}
  2764. % var_test_19.rkt
  2765. \begin{lstlisting}
  2766. (let ([x (+ 42 (- 10))])
  2767. (+ x 10))
  2768. \end{lstlisting}
  2769. \compilesto
  2770. \begin{lstlisting}
  2771. (let ([x (let ([tmp.1 (- 10)])
  2772. (+ 42 tmp.1))])
  2773. (+ x 10))
  2774. \end{lstlisting}
  2775. \end{transformation}
  2776. \fi}
  2777. {\if\edition\pythonEd
  2778. \begin{transformation}
  2779. \begin{lstlisting}
  2780. x = 42 + -10
  2781. print(x + 10)
  2782. \end{lstlisting}
  2783. \compilesto
  2784. \begin{lstlisting}
  2785. tmp_0 = -10
  2786. x = 42 + tmp_0
  2787. tmp_1 = x + 10
  2788. print(tmp_1)
  2789. \end{lstlisting}
  2790. \end{transformation}
  2791. \fi}
  2792. \begin{figure}[tp]
  2793. \centering
  2794. \fbox{
  2795. \begin{minipage}{0.96\textwidth}
  2796. {\if\edition\racketEd
  2797. \[
  2798. \begin{array}{rcl}
  2799. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2800. \Exp &::=& \Atm \MID \READ{} \\
  2801. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2802. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2803. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2804. \end{array}
  2805. \]
  2806. \fi}
  2807. {\if\edition\pythonEd
  2808. \[
  2809. \begin{array}{rcl}
  2810. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2811. \Exp{} &::=& \Atm \MID \READ{} \\
  2812. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2813. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2814. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  2815. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2816. \end{array}
  2817. \]
  2818. \fi}
  2819. \end{minipage}
  2820. }
  2821. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2822. atomic expressions.}
  2823. \label{fig:Lvar-anf-syntax}
  2824. \end{figure}
  2825. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2826. of this pass, the language \LangVarANF{}. The only difference is that
  2827. operator arguments are restricted to be atomic expressions that are
  2828. defined by the \Atm{} non-terminal. In particular, integer constants
  2829. and variables are atomic.
  2830. The atomic expressions are pure (they do not cause side-effects or
  2831. depend on them) whereas complex expressions may have side effects,
  2832. such as \READ{}. A language with this separation between pure versus
  2833. side-effecting expressions is said to be in monadic normal
  2834. form~\citep{Moggi:1991in,Danvy:2003fk} which explains the \textit{mon}
  2835. in \LangVarANF{}. An important invariant of the
  2836. \code{remove\_complex\_operands} pass is that the relative ordering
  2837. among complex expressions is not changed, but the relative ordering
  2838. between atomic expressions and complex expressions can change and
  2839. often does. The reason that these changes are behaviour preserving is
  2840. that the atomic expressions are pure.
  2841. Another well-known form for intermediate languages is the
  2842. \emph{administrative normal form}
  2843. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2844. \index{subject}{administrative normal form} \index{subject}{ANF}
  2845. %
  2846. The \LangVarANF{} language is not quite in ANF because we allow the
  2847. right-hand side of a \code{let} to be a complex expression.
  2848. {\if\edition\racketEd
  2849. We recommend implementing this pass with two mutually recursive
  2850. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2851. \code{rco\_atom} to subexpressions that need to become atomic and to
  2852. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2853. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2854. returns an expression. The \code{rco\_atom} function returns two
  2855. things: an atomic expression and an alist mapping temporary variables to
  2856. complex subexpressions. You can return multiple things from a function
  2857. using Racket's \key{values} form and you can receive multiple things
  2858. from a function call using the \key{define-values} form.
  2859. Also, the
  2860. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2861. form is useful for applying a function to each element of a list, in
  2862. the case where the function returns multiple values.
  2863. \index{subject}{for/lists}
  2864. \fi}
  2865. %
  2866. {\if\edition\pythonEd
  2867. %
  2868. We recommend implementing this pass with an auxiliary method named
  2869. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2870. Boolean that specifies whether the expression needs to become atomic
  2871. or not. The \code{rco\_exp} method should return a pair consisting of
  2872. the new expression and a list of pairs, associating new temporary
  2873. variables with their initializing expressions.
  2874. %
  2875. \fi}
  2876. {\if\edition\racketEd
  2877. Returning to the example program with the expression \code{(+ 42 (-
  2878. 10))}, the subexpression \code{(- 10)} should be processed using the
  2879. \code{rco\_atom} function because it is an argument of the \code{+} and
  2880. therefore needs to become atomic. The output of \code{rco\_atom}
  2881. applied to \code{(- 10)} is as follows.
  2882. \begin{transformation}
  2883. \begin{lstlisting}
  2884. (- 10)
  2885. \end{lstlisting}
  2886. \compilesto
  2887. \begin{lstlisting}
  2888. tmp.1
  2889. ((tmp.1 . (- 10)))
  2890. \end{lstlisting}
  2891. \end{transformation}
  2892. \fi}
  2893. %
  2894. {\if\edition\pythonEd
  2895. %
  2896. Returning to the example program with the expression \code{42 + -10},
  2897. the subexpression \code{-10} should be processed using the
  2898. \code{rco\_exp} function with \code{True} as the second argument
  2899. because \code{-10} is an argument of the \code{+} operator and
  2900. therefore needs to become atomic. The output of \code{rco\_exp}
  2901. applied to \code{-10} is as follows.
  2902. \begin{transformation}
  2903. \begin{lstlisting}
  2904. -10
  2905. \end{lstlisting}
  2906. \compilesto
  2907. \begin{lstlisting}
  2908. tmp_1
  2909. [(tmp_1, -10)]
  2910. \end{lstlisting}
  2911. \end{transformation}
  2912. %
  2913. \fi}
  2914. Take special care of programs such as the following that
  2915. %
  2916. \racket{bind a variable to an atomic expression}
  2917. %
  2918. \python{assign an atomic expression to a variable}.
  2919. %
  2920. You should leave such \racket{variable bindings}\python{assignments}
  2921. unchanged, as shown in the program on the right\\
  2922. %
  2923. {\if\edition\racketEd
  2924. \begin{transformation}
  2925. % var_test_20.rkt
  2926. \begin{lstlisting}
  2927. (let ([a 42])
  2928. (let ([b a])
  2929. b))
  2930. \end{lstlisting}
  2931. \compilesto
  2932. \begin{lstlisting}
  2933. (let ([a 42])
  2934. (let ([b a])
  2935. b))
  2936. \end{lstlisting}
  2937. \end{transformation}
  2938. \fi}
  2939. {\if\edition\pythonEd
  2940. \begin{transformation}
  2941. \begin{lstlisting}
  2942. a = 42
  2943. b = a
  2944. print(b)
  2945. \end{lstlisting}
  2946. \compilesto
  2947. \begin{lstlisting}
  2948. a = 42
  2949. b = a
  2950. print(b)
  2951. \end{lstlisting}
  2952. \end{transformation}
  2953. \fi}
  2954. %
  2955. \noindent A careless implementation might produce the following output with
  2956. unnecessary temporary variables.
  2957. \begin{center}
  2958. \begin{minipage}{0.4\textwidth}
  2959. {\if\edition\racketEd
  2960. \begin{lstlisting}
  2961. (let ([tmp.1 42])
  2962. (let ([a tmp.1])
  2963. (let ([tmp.2 a])
  2964. (let ([b tmp.2])
  2965. b))))
  2966. \end{lstlisting}
  2967. \fi}
  2968. {\if\edition\pythonEd
  2969. \begin{lstlisting}
  2970. tmp_1 = 42
  2971. a = tmp_1
  2972. tmp_2 = a
  2973. b = tmp_2
  2974. print(b)
  2975. \end{lstlisting}
  2976. \fi}
  2977. \end{minipage}
  2978. \end{center}
  2979. \begin{exercise}
  2980. \normalfont
  2981. {\if\edition\racketEd
  2982. Implement the \code{remove\_complex\_operands} function in
  2983. \code{compiler.rkt}.
  2984. %
  2985. Create three new \LangVar{} programs that exercise the interesting
  2986. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  2987. regarding file names described in Exercise~\ref{ex:Lvar}.
  2988. %
  2989. In the \code{run-tests.rkt} script, add the following entry to the
  2990. list of \code{passes} and then run the script to test your compiler.
  2991. \begin{lstlisting}
  2992. (list "remove-complex" remove-complex-opera* interp_Lvar type-check-Lvar)
  2993. \end{lstlisting}
  2994. While debugging your compiler, it is often useful to see the
  2995. intermediate programs that are output from each pass. To print the
  2996. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  2997. \code{interp-tests} in \code{run-tests.rkt}.
  2998. \fi}
  2999. %
  3000. {\if\edition\pythonEd
  3001. Implement the \code{remove\_complex\_operands} pass in
  3002. \code{compiler.py}, creating auxiliary functions for each
  3003. non-terminal in the grammar, i.e., \code{rco\_exp}
  3004. and \code{rco\_stmt}.
  3005. \fi}
  3006. \end{exercise}
  3007. {\if\edition\pythonEd
  3008. \begin{exercise}
  3009. \normalfont % I don't like the italics for exercises. -Jeremy
  3010. \label{ex:Lvar}
  3011. Create five \LangVar{} programs that exercise the most interesting
  3012. parts of the \code{remove\_complex\_operands} pass. The five programs
  3013. should be placed in the subdirectory named \key{tests} and the file
  3014. names should start with \code{var\_test\_} followed by a unique
  3015. integer and end with the file extension \key{.py}.
  3016. %% The \key{run-tests.rkt} script in the support code checks whether the
  3017. %% output programs produce the same result as the input programs. The
  3018. %% script uses the \key{interp-tests} function
  3019. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3020. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3021. %% parameter of \key{interp-tests} is a list that should have one entry
  3022. %% for each pass in your compiler. For now, define \code{passes} to
  3023. %% contain just one entry for \code{uniquify} as shown below.
  3024. %% \begin{lstlisting}
  3025. %% (define passes
  3026. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3027. %% \end{lstlisting}
  3028. Run the \key{run-tests.py} script in the support code to check
  3029. whether the output programs produce the same result as the input
  3030. programs.
  3031. \end{exercise}
  3032. \fi}
  3033. {\if\edition\racketEd
  3034. \section{Explicate Control}
  3035. \label{sec:explicate-control-Lvar}
  3036. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3037. programs that make the order of execution explicit in their
  3038. syntax. For now this amounts to flattening \key{let} constructs into a
  3039. sequence of assignment statements. For example, consider the following
  3040. \LangVar{} program.\\
  3041. % var_test_11.rkt
  3042. \begin{minipage}{0.96\textwidth}
  3043. \begin{lstlisting}
  3044. (let ([y (let ([x 20])
  3045. (+ x (let ([x 22]) x)))])
  3046. y)
  3047. \end{lstlisting}
  3048. \end{minipage}\\
  3049. %
  3050. The output of the previous pass and of \code{explicate\_control} is
  3051. shown below. Recall that the right-hand-side of a \key{let} executes
  3052. before its body, so the order of evaluation for this program is to
  3053. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  3054. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  3055. output of \code{explicate\_control} makes this ordering explicit.
  3056. \begin{transformation}
  3057. \begin{lstlisting}
  3058. (let ([y (let ([x.1 20])
  3059. (let ([x.2 22])
  3060. (+ x.1 x.2)))])
  3061. y)
  3062. \end{lstlisting}
  3063. \compilesto
  3064. \begin{lstlisting}[language=C]
  3065. start:
  3066. x.1 = 20;
  3067. x.2 = 22;
  3068. y = (+ x.1 x.2);
  3069. return y;
  3070. \end{lstlisting}
  3071. \end{transformation}
  3072. \begin{figure}[tbp]
  3073. \begin{lstlisting}
  3074. (define (explicate_tail e)
  3075. (match e
  3076. [(Var x) ___]
  3077. [(Int n) (Return (Int n))]
  3078. [(Let x rhs body) ___]
  3079. [(Prim op es) ___]
  3080. [else (error "explicate_tail unhandled case" e)]))
  3081. (define (explicate_assign e x cont)
  3082. (match e
  3083. [(Var x) ___]
  3084. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3085. [(Let y rhs body) ___]
  3086. [(Prim op es) ___]
  3087. [else (error "explicate_assign unhandled case" e)]))
  3088. (define (explicate_control p)
  3089. (match p
  3090. [(Program info body) ___]))
  3091. \end{lstlisting}
  3092. \caption{Skeleton for the \code{explicate\_control} pass.}
  3093. \label{fig:explicate-control-Lvar}
  3094. \end{figure}
  3095. The organization of this pass depends on the notion of tail position
  3096. that we have alluded to earlier.
  3097. \begin{definition}
  3098. The following rules define when an expression is in \textbf{\emph{tail
  3099. position}}\index{subject}{tail position} for the language \LangVar{}.
  3100. \begin{enumerate}
  3101. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3102. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3103. \end{enumerate}
  3104. \end{definition}
  3105. We recommend implementing \code{explicate\_control} using two mutually
  3106. recursive functions, \code{explicate\_tail} and
  3107. \code{explicate\_assign}, as suggested in the skeleton code in
  3108. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3109. function should be applied to expressions in tail position whereas the
  3110. \code{explicate\_assign} should be applied to expressions that occur on
  3111. the right-hand-side of a \key{let}.
  3112. %
  3113. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3114. input and produces a \Tail{} in \LangCVar{} (see
  3115. Figure~\ref{fig:c0-syntax}).
  3116. %
  3117. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3118. the variable that it is to be assigned to, and a \Tail{} in
  3119. \LangCVar{} for the code that comes after the assignment. The
  3120. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3121. The \code{explicate\_assign} function is in accumulator-passing style:
  3122. the \code{cont} parameter is used for accumulating the output. This
  3123. accumulator-passing style plays an important role in how we generate
  3124. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  3125. \begin{exercise}\normalfont
  3126. %
  3127. Implement the \code{explicate\_control} function in
  3128. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3129. exercise the code in \code{explicate\_control}.
  3130. %
  3131. In the \code{run-tests.rkt} script, add the following entry to the
  3132. list of \code{passes} and then run the script to test your compiler.
  3133. \begin{lstlisting}
  3134. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3135. \end{lstlisting}
  3136. \end{exercise}
  3137. \fi}
  3138. \section{Select Instructions}
  3139. \label{sec:select-Lvar}
  3140. \index{subject}{instruction selection}
  3141. In the \code{select\_instructions} pass we begin the work of
  3142. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3143. language of this pass is a variant of x86 that still uses variables,
  3144. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3145. non-terminal of the \LangXInt{} abstract syntax
  3146. (Figure~\ref{fig:x86-int-ast}).
  3147. \racket{We recommend implementing the
  3148. \code{select\_instructions} with three auxiliary functions, one for
  3149. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3150. $\Tail$.}
  3151. \python{We recommend implementing an auxiliary function
  3152. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  3153. \racket{
  3154. The cases for $\Atm$ are straightforward; variables stay
  3155. the same and integer constants change to immediates:
  3156. $\INT{n}$ changes to $\IMM{n}$.}
  3157. We consider the cases for the $\Stmt$ non-terminal, starting with
  3158. arithmetic operations. For example, consider the addition operation
  3159. below, on the left side. There is an \key{addq} instruction in x86,
  3160. but it performs an in-place update. So we could move $\Arg_1$
  3161. into the left-hand side \itm{var} and then add $\Arg_2$ to
  3162. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  3163. $\Atm_1$ and $\Atm_2$ respectively.
  3164. \begin{transformation}
  3165. {\if\edition\racketEd
  3166. \begin{lstlisting}
  3167. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3168. \end{lstlisting}
  3169. \fi}
  3170. {\if\edition\pythonEd
  3171. \begin{lstlisting}
  3172. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3173. \end{lstlisting}
  3174. \fi}
  3175. \compilesto
  3176. \begin{lstlisting}
  3177. movq |$\Arg_1$|, |$\itm{var}$|
  3178. addq |$\Arg_2$|, |$\itm{var}$|
  3179. \end{lstlisting}
  3180. \end{transformation}
  3181. There are also cases that require special care to avoid generating
  3182. needlessly complicated code. For example, if one of the arguments of
  3183. the addition is the same variable as the left-hand side of the
  3184. assignment, as shown below, then there is no need for the extra move
  3185. instruction. The assignment statement can be translated into a single
  3186. \key{addq} instruction as follows.
  3187. \begin{transformation}
  3188. {\if\edition\racketEd
  3189. \begin{lstlisting}
  3190. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3191. \end{lstlisting}
  3192. \fi}
  3193. {\if\edition\pythonEd
  3194. \begin{lstlisting}
  3195. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3196. \end{lstlisting}
  3197. \fi}
  3198. \compilesto
  3199. \begin{lstlisting}
  3200. addq |$\Arg_1$|, |$\itm{var}$|
  3201. \end{lstlisting}
  3202. \end{transformation}
  3203. The \READOP{} operation does not have a direct counterpart in x86
  3204. assembly, so we provide this functionality with the function
  3205. \code{read\_int} in the file \code{runtime.c}, written in
  3206. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3207. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3208. system}, or simply the \emph{runtime} for short. When compiling your
  3209. generated x86 assembly code, you need to compile \code{runtime.c} to
  3210. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3211. \code{-c}) and link it into the executable. For our purposes of code
  3212. generation, all you need to do is translate an assignment of
  3213. \READOP{} into a call to the \code{read\_int} function followed by a
  3214. move from \code{rax} to the left-hand-side variable. (Recall that the
  3215. return value of a function goes into \code{rax}.)
  3216. \begin{transformation}
  3217. {\if\edition\racketEd
  3218. \begin{lstlisting}
  3219. |$\itm{var}$| = (read);
  3220. \end{lstlisting}
  3221. \fi}
  3222. {\if\edition\pythonEd
  3223. \begin{lstlisting}
  3224. |$\itm{var}$| = input_int();
  3225. \end{lstlisting}
  3226. \fi}
  3227. \compilesto
  3228. \begin{lstlisting}
  3229. callq read_int
  3230. movq %rax, |$\itm{var}$|
  3231. \end{lstlisting}
  3232. \end{transformation}
  3233. {\if\edition\pythonEd
  3234. %
  3235. Similarly, we translate the \code{print} operation, shown below, into
  3236. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3237. In x86, the first six arguments to functions are passed in registers,
  3238. with the first argument passed in register \code{rdi}. So we move the
  3239. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3240. \code{callq} instruction.
  3241. \begin{transformation}
  3242. \begin{lstlisting}
  3243. print(|$\Atm$|)
  3244. \end{lstlisting}
  3245. \compilesto
  3246. \begin{lstlisting}
  3247. movq |$\Arg$|, %rdi
  3248. callq print_int
  3249. \end{lstlisting}
  3250. \end{transformation}
  3251. %
  3252. \fi}
  3253. {\if\edition\racketEd
  3254. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3255. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3256. assignment to the \key{rax} register followed by a jump to the
  3257. conclusion of the program (so the conclusion needs to be labeled).
  3258. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3259. recursively and then append the resulting instructions.
  3260. \fi}
  3261. \begin{exercise}
  3262. \normalfont
  3263. {\if\edition\racketEd
  3264. Implement the \code{select\_instructions} pass in
  3265. \code{compiler.rkt}. Create three new example programs that are
  3266. designed to exercise all of the interesting cases in this pass.
  3267. %
  3268. In the \code{run-tests.rkt} script, add the following entry to the
  3269. list of \code{passes} and then run the script to test your compiler.
  3270. \begin{lstlisting}
  3271. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3272. \end{lstlisting}
  3273. \fi}
  3274. {\if\edition\pythonEd
  3275. Implement the \key{select\_instructions} pass in
  3276. \code{compiler.py}. Create three new example programs that are
  3277. designed to exercise all of the interesting cases in this pass.
  3278. Run the \code{run-tests.py} script to to check
  3279. whether the output programs produce the same result as the input
  3280. programs.
  3281. \fi}
  3282. \end{exercise}
  3283. \section{Assign Homes}
  3284. \label{sec:assign-Lvar}
  3285. The \key{assign\_homes} pass compiles \LangXVar{} programs to
  3286. \LangXVar{} programs that no longer use program variables.
  3287. Thus, the \key{assign-homes} pass is responsible for placing all of
  3288. the program variables in registers or on the stack. For runtime
  3289. efficiency, it is better to place variables in registers, but as there
  3290. are only 16 registers, some programs must necessarily resort to
  3291. placing some variables on the stack. In this chapter we focus on the
  3292. mechanics of placing variables on the stack. We study an algorithm for
  3293. placing variables in registers in
  3294. Chapter~\ref{ch:register-allocation-Lvar}.
  3295. Consider again the following \LangVar{} program from
  3296. Section~\ref{sec:remove-complex-opera-Lvar}.
  3297. % var_test_20.rkt
  3298. {\if\edition\racketEd
  3299. \begin{lstlisting}
  3300. (let ([a 42])
  3301. (let ([b a])
  3302. b))
  3303. \end{lstlisting}
  3304. \fi}
  3305. {\if\edition\pythonEd
  3306. \begin{lstlisting}
  3307. a = 42
  3308. b = a
  3309. print(b)
  3310. \end{lstlisting}
  3311. \fi}
  3312. %
  3313. The output of \code{select\_instructions} is shown below, on the left,
  3314. and the output of \code{assign\_homes} is on the right. In this
  3315. example, we assign variable \code{a} to stack location
  3316. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3317. \begin{transformation}
  3318. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3319. movq $42, a
  3320. movq a, b
  3321. movq b, %rax
  3322. \end{lstlisting}
  3323. \compilesto
  3324. %stack-space: 16
  3325. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3326. movq $42, -8(%rbp)
  3327. movq -8(%rbp), -16(%rbp)
  3328. movq -16(%rbp), %rax
  3329. \end{lstlisting}
  3330. \end{transformation}
  3331. \racket{The \code{locals-types} entry in the $\itm{info}$ of the
  3332. \code{X86Program} node is an alist mapping all the variables in the
  3333. program to their types (for now just \code{Integer}). The
  3334. \code{assign\_homes} pass should replace all uses of those variables
  3335. with stack locations. As an aside, the \code{locals-types} entry is
  3336. computed by \code{type-check-Cvar} in the support code, which
  3337. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3338. which should be propagated to the \code{X86Program} node.}
  3339. %
  3340. \python{The \code{assign\_homes} pass should replace all uses of
  3341. variables with stack locations.}
  3342. %
  3343. In the process of assigning variables to stack locations, it is
  3344. convenient for you to compute and store the size of the frame (in
  3345. bytes) in%
  3346. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space}}
  3347. %
  3348. \python{the field \code{stack\_space} of the \key{X86Program} node},
  3349. which is needed later to generate the conclusion of the \code{main}
  3350. procedure. The x86-64 standard requires the frame size to be a
  3351. multiple of 16 bytes.\index{subject}{frame}
  3352. % TODO: store the number of variables instead? -Jeremy
  3353. \begin{exercise}\normalfont
  3354. Implement the \key{assign\_homes} pass in
  3355. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3356. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3357. grammar. We recommend that the auxiliary functions take an extra
  3358. parameter that maps variable names to homes (stack locations for now).
  3359. %
  3360. {\if\edition\racketEd
  3361. In the \code{run-tests.rkt} script, add the following entry to the
  3362. list of \code{passes} and then run the script to test your compiler.
  3363. \begin{lstlisting}
  3364. (list "assign homes" assign-homes interp_x86-0)
  3365. \end{lstlisting}
  3366. \fi}
  3367. {\if\edition\pythonEd
  3368. Run the \code{run-tests.py} script to to check
  3369. whether the output programs produce the same result as the input
  3370. programs.
  3371. \fi}
  3372. \end{exercise}
  3373. \section{Patch Instructions}
  3374. \label{sec:patch-s0}
  3375. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3376. \LangXInt{} by making sure that each instruction adheres to the
  3377. restriction that at most one argument of an instruction may be a
  3378. memory reference.
  3379. We return to the following example.\\
  3380. \begin{minipage}{0.5\textwidth}
  3381. % var_test_20.rkt
  3382. {\if\edition\racketEd
  3383. \begin{lstlisting}
  3384. (let ([a 42])
  3385. (let ([b a])
  3386. b))
  3387. \end{lstlisting}
  3388. \fi}
  3389. {\if\edition\pythonEd
  3390. \begin{lstlisting}
  3391. a = 42
  3392. b = a
  3393. print(b)
  3394. \end{lstlisting}
  3395. \fi}
  3396. \end{minipage}\\
  3397. The \key{assign\_homes} pass produces the following translation. \\
  3398. \begin{minipage}{0.5\textwidth}
  3399. {\if\edition\racketEd
  3400. \begin{lstlisting}
  3401. movq $42, -8(%rbp)
  3402. movq -8(%rbp), -16(%rbp)
  3403. movq -16(%rbp), %rax
  3404. \end{lstlisting}
  3405. \fi}
  3406. {\if\edition\pythonEd
  3407. \begin{lstlisting}
  3408. movq 42, -8(%rbp)
  3409. movq -8(%rbp), -16(%rbp)
  3410. movq -16(%rbp), %rdi
  3411. callq print_int
  3412. \end{lstlisting}
  3413. \fi}
  3414. \end{minipage}\\
  3415. The second \key{movq} instruction is problematic because both
  3416. arguments are stack locations. We suggest fixing this problem by
  3417. moving from the source location to the register \key{rax} and then
  3418. from \key{rax} to the destination location, as follows.
  3419. \begin{lstlisting}
  3420. movq -8(%rbp), %rax
  3421. movq %rax, -16(%rbp)
  3422. \end{lstlisting}
  3423. \begin{exercise}
  3424. \normalfont Implement the \key{patch\_instructions} pass in
  3425. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3426. Create three new example programs that are
  3427. designed to exercise all of the interesting cases in this pass.
  3428. %
  3429. {\if\edition\racketEd
  3430. In the \code{run-tests.rkt} script, add the following entry to the
  3431. list of \code{passes} and then run the script to test your compiler.
  3432. \begin{lstlisting}
  3433. (list "patch instructions" patch_instructions interp_x86-0)
  3434. \end{lstlisting}
  3435. \fi}
  3436. {\if\edition\pythonEd
  3437. Run the \code{run-tests.py} script to to check
  3438. whether the output programs produce the same result as the input
  3439. programs.
  3440. \fi}
  3441. \end{exercise}
  3442. \section{Generate Prelude and Conclusion}
  3443. \label{sec:print-x86}
  3444. \index{subject}{prelude}\index{subject}{conclusion}
  3445. The last step of the compiler from \LangVar{} to x86 is to generate
  3446. the \code{main} function with a prelude and conclusion wrapped around
  3447. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3448. discussed in Section~\ref{sec:x86}.
  3449. When running on Mac OS X, your compiler should prefix an underscore to
  3450. all labels, e.g., changing \key{main} to \key{\_main}.
  3451. %
  3452. \racket{The Racket call \code{(system-type 'os)} is useful for
  3453. determining which operating system the compiler is running on. It
  3454. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3455. %
  3456. \python{The Python \code{platform} library includes a \code{system()}
  3457. function that returns \code{'Linux'}, \code{'Windows'}, or
  3458. \code{'Darwin'} (for Mac).}
  3459. \begin{exercise}\normalfont
  3460. %
  3461. Implement the \key{prelude\_and\_conclusion} pass in
  3462. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3463. %
  3464. {\if\edition\racketEd
  3465. In the \code{run-tests.rkt} script, add the following entry to the
  3466. list of \code{passes} and then run the script to test your compiler.
  3467. \begin{lstlisting}
  3468. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3469. \end{lstlisting}
  3470. %
  3471. Uncomment the call to the \key{compiler-tests} function
  3472. (Appendix~\ref{appendix:utilities}), which tests your complete
  3473. compiler by executing the generated x86 code. It translates the x86
  3474. AST that you produce into a string by invoking the \code{print-x86}
  3475. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3476. the provided \key{runtime.c} file to \key{runtime.o} using
  3477. \key{gcc}. Run the script to test your compiler.
  3478. %
  3479. \fi}
  3480. {\if\edition\pythonEd
  3481. %
  3482. Run the \code{run-tests.py} script to to check whether the output
  3483. programs produce the same result as the input programs. That script
  3484. translates the x86 AST that you produce into a string by invoking the
  3485. \code{repr} method that is implemented by the x86 AST classes in
  3486. \code{x86\_ast.py}.
  3487. %
  3488. \fi}
  3489. \end{exercise}
  3490. \section{Challenge: Partial Evaluator for \LangVar{}}
  3491. \label{sec:pe-Lvar}
  3492. \index{subject}{partial evaluation}
  3493. This section describes two optional challenge exercises that involve
  3494. adapting and improving the partial evaluator for \LangInt{} that was
  3495. introduced in Section~\ref{sec:partial-evaluation}.
  3496. \begin{exercise}\label{ex:pe-Lvar}
  3497. \normalfont
  3498. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3499. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3500. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3501. %
  3502. \racket{\key{let} binding}\python{assignment}
  3503. %
  3504. to the \LangInt{} language, so you will need to add cases for them in
  3505. the \code{pe\_exp}
  3506. %
  3507. \racket{function}
  3508. %
  3509. \python{and \code{pe\_stmt} functions}.
  3510. %
  3511. Once complete, add the partial evaluation pass to the front of your
  3512. compiler and make sure that your compiler still passes all of the
  3513. tests.
  3514. \end{exercise}
  3515. \begin{exercise}
  3516. \normalfont
  3517. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3518. \code{pe\_add} auxiliary functions with functions that know more about
  3519. arithmetic. For example, your partial evaluator should translate
  3520. {\if\edition\racketEd
  3521. \[
  3522. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3523. \code{(+ 2 (read))}
  3524. \]
  3525. \fi}
  3526. {\if\edition\pythonEd
  3527. \[
  3528. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3529. \code{2 + input\_int()}
  3530. \]
  3531. \fi}
  3532. To accomplish this, the \code{pe\_exp} function should produce output
  3533. in the form of the $\itm{residual}$ non-terminal of the following
  3534. grammar. The idea is that when processing an addition expression, we
  3535. can always produce either 1) an integer constant, 2) an addition
  3536. expression with an integer constant on the left-hand side but not the
  3537. right-hand side, or 3) or an addition expression in which neither
  3538. subexpression is a constant.
  3539. {\if\edition\racketEd
  3540. \[
  3541. \begin{array}{lcl}
  3542. \itm{inert} &::=& \Var
  3543. \MID \LP\key{read}\RP
  3544. \MID \LP\key{-} ~\Var\RP
  3545. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3546. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3547. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3548. \itm{residual} &::=& \Int
  3549. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3550. \MID \itm{inert}
  3551. \end{array}
  3552. \]
  3553. \fi}
  3554. {\if\edition\pythonEd
  3555. \[
  3556. \begin{array}{lcl}
  3557. \itm{inert} &::=& \Var
  3558. \MID \key{input\_int}\LP\RP
  3559. \MID \key{-} \Var
  3560. \MID \key{-} \key{input\_int}\LP\RP
  3561. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3562. \itm{residual} &::=& \Int
  3563. \MID \Int ~ \key{+} ~ \itm{inert}
  3564. \MID \itm{inert}
  3565. \end{array}
  3566. \]
  3567. \fi}
  3568. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3569. inputs are $\itm{residual}$ expressions and they should return
  3570. $\itm{residual}$ expressions. Once the improvements are complete,
  3571. make sure that your compiler still passes all of the tests. After
  3572. all, fast code is useless if it produces incorrect results!
  3573. \end{exercise}
  3574. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3575. \chapter{Register Allocation}
  3576. \label{ch:register-allocation-Lvar}
  3577. \index{subject}{register allocation}
  3578. In Chapter~\ref{ch:Lvar} we learned how to store variables on the
  3579. stack. In this chapter we learn how to improve the performance of the
  3580. generated code by assigning some variables to registers. The CPU can
  3581. access a register in a single cycle, whereas accessing the stack can
  3582. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3583. serves as a running example. The source program is on the left and the
  3584. output of instruction selection is on the right. The program is almost
  3585. in the x86 assembly language but it still uses variables.
  3586. \begin{figure}
  3587. \begin{minipage}{0.45\textwidth}
  3588. Example \LangVar{} program:
  3589. % var_test_28.rkt
  3590. {\if\edition\racketEd
  3591. \begin{lstlisting}
  3592. (let ([v 1])
  3593. (let ([w 42])
  3594. (let ([x (+ v 7)])
  3595. (let ([y x])
  3596. (let ([z (+ x w)])
  3597. (+ z (- y)))))))
  3598. \end{lstlisting}
  3599. \fi}
  3600. {\if\edition\pythonEd
  3601. \begin{lstlisting}
  3602. v = 1
  3603. w = 42
  3604. x = v + 7
  3605. y = x
  3606. z = x + w
  3607. print(z + (- y))
  3608. \end{lstlisting}
  3609. \fi}
  3610. \end{minipage}
  3611. \begin{minipage}{0.45\textwidth}
  3612. After instruction selection:
  3613. {\if\edition\racketEd
  3614. \begin{lstlisting}
  3615. locals-types:
  3616. x : Integer, y : Integer,
  3617. z : Integer, t : Integer,
  3618. v : Integer, w : Integer
  3619. start:
  3620. movq $1, v
  3621. movq $42, w
  3622. movq v, x
  3623. addq $7, x
  3624. movq x, y
  3625. movq x, z
  3626. addq w, z
  3627. movq y, t
  3628. negq t
  3629. movq z, %rax
  3630. addq t, %rax
  3631. jmp conclusion
  3632. \end{lstlisting}
  3633. \fi}
  3634. {\if\edition\pythonEd
  3635. \begin{lstlisting}
  3636. movq $1, v
  3637. movq $42, w
  3638. movq v, x
  3639. addq $7, x
  3640. movq x, y
  3641. movq x, z
  3642. addq w, z
  3643. movq y, tmp_0
  3644. negq tmp_0
  3645. movq z, tmp_1
  3646. addq tmp_0, tmp_1
  3647. movq tmp_1, %rdi
  3648. callq print_int
  3649. \end{lstlisting}
  3650. \fi}
  3651. \end{minipage}
  3652. \caption{A running example for register allocation.}
  3653. \label{fig:reg-eg}
  3654. \end{figure}
  3655. The goal of register allocation is to fit as many variables into
  3656. registers as possible. Some programs have more variables than
  3657. registers so we cannot always map each variable to a different
  3658. register. Fortunately, it is common for different variables to be
  3659. needed during different periods of time during program execution, and
  3660. in such cases several variables can be mapped to the same register.
  3661. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3662. After the variable \code{x} is moved to \code{z} it is no longer
  3663. needed. Variable \code{z}, on the other hand, is used only after this
  3664. point, so \code{x} and \code{z} could share the same register. The
  3665. topic of Section~\ref{sec:liveness-analysis-Lvar} is how to compute
  3666. where a variable is needed. Once we have that information, we compute
  3667. which variables are needed at the same time, i.e., which ones
  3668. \emph{interfere} with each other, and represent this relation as an
  3669. undirected graph whose vertices are variables and edges indicate when
  3670. two variables interfere (Section~\ref{sec:build-interference}). We
  3671. then model register allocation as a graph coloring problem
  3672. (Section~\ref{sec:graph-coloring}).
  3673. If we run out of registers despite these efforts, we place the
  3674. remaining variables on the stack, similar to what we did in
  3675. Chapter~\ref{ch:Lvar}. It is common to use the verb \emph{spill} for
  3676. assigning a variable to a stack location. The decision to spill a
  3677. variable is handled as part of the graph coloring process.
  3678. We make the simplifying assumption that each variable is assigned to
  3679. one location (a register or stack address). A more sophisticated
  3680. approach is to assign a variable to one or more locations in different
  3681. regions of the program. For example, if a variable is used many times
  3682. in short sequence and then only used again after many other
  3683. instructions, it could be more efficient to assign the variable to a
  3684. register during the initial sequence and then move it to the stack for
  3685. the rest of its lifetime. We refer the interested reader to
  3686. \citet{Cooper:2011aa} Chapter 13 for more information about that
  3687. approach.
  3688. % discuss prioritizing variables based on how much they are used.
  3689. \section{Registers and Calling Conventions}
  3690. \label{sec:calling-conventions}
  3691. \index{subject}{calling conventions}
  3692. As we perform register allocation, we need to be aware of the
  3693. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  3694. functions calls are performed in x86.
  3695. %
  3696. Even though \LangVar{} does not include programmer-defined functions,
  3697. our generated code includes a \code{main} function that is called by
  3698. the operating system and our generated code contains calls to the
  3699. \code{read\_int} function.
  3700. Function calls require coordination between two pieces of code that
  3701. may be written by different programmers or generated by different
  3702. compilers. Here we follow the System V calling conventions that are
  3703. used by the GNU C compiler on Linux and
  3704. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3705. %
  3706. The calling conventions include rules about how functions share the
  3707. use of registers. In particular, the caller is responsible for freeing
  3708. up some registers prior to the function call for use by the callee.
  3709. These are called the \emph{caller-saved registers}
  3710. \index{subject}{caller-saved registers}
  3711. and they are
  3712. \begin{lstlisting}
  3713. rax rcx rdx rsi rdi r8 r9 r10 r11
  3714. \end{lstlisting}
  3715. On the other hand, the callee is responsible for preserving the values
  3716. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3717. which are
  3718. \begin{lstlisting}
  3719. rsp rbp rbx r12 r13 r14 r15
  3720. \end{lstlisting}
  3721. We can think about this caller/callee convention from two points of
  3722. view, the caller view and the callee view:
  3723. \begin{itemize}
  3724. \item The caller should assume that all the caller-saved registers get
  3725. overwritten with arbitrary values by the callee. On the other hand,
  3726. the caller can safely assume that all the callee-saved registers
  3727. contain the same values after the call that they did before the
  3728. call.
  3729. \item The callee can freely use any of the caller-saved registers.
  3730. However, if the callee wants to use a callee-saved register, the
  3731. callee must arrange to put the original value back in the register
  3732. prior to returning to the caller. This can be accomplished by saving
  3733. the value to the stack in the prelude of the function and restoring
  3734. the value in the conclusion of the function.
  3735. \end{itemize}
  3736. In x86, registers are also used for passing arguments to a function
  3737. and for the return value. In particular, the first six arguments to a
  3738. function are passed in the following six registers, in this order.
  3739. \begin{lstlisting}
  3740. rdi rsi rdx rcx r8 r9
  3741. \end{lstlisting}
  3742. If there are more than six arguments, then the convention is to use
  3743. space on the frame of the caller for the rest of the
  3744. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  3745. need more than six arguments.
  3746. %
  3747. \racket{For now, the only function we care about is \code{read\_int}
  3748. and it takes zero arguments.}
  3749. %
  3750. \python{For now, the only functions we care about are \code{read\_int}
  3751. and \code{print\_int}, which take zero and one argument, respectively.}
  3752. %
  3753. The register \code{rax} is used for the return value of a function.
  3754. The next question is how these calling conventions impact register
  3755. allocation. Consider the \LangVar{} program in
  3756. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3757. example from the caller point of view and then from the callee point
  3758. of view.
  3759. The program makes two calls to \READOP{}. Also, the variable \code{x}
  3760. is in use during the second call to \READOP{}, so we need to make sure
  3761. that the value in \code{x} does not get accidentally wiped out by the
  3762. call to \READOP{}. One obvious approach is to save all the values in
  3763. caller-saved registers to the stack prior to each function call, and
  3764. restore them after each call. That way, if the register allocator
  3765. chooses to assign \code{x} to a caller-saved register, its value will
  3766. be preserved across the call to \READOP{}. However, saving and
  3767. restoring to the stack is relatively slow. If \code{x} is not used
  3768. many times, it may be better to assign \code{x} to a stack location in
  3769. the first place. Or better yet, if we can arrange for \code{x} to be
  3770. placed in a callee-saved register, then it won't need to be saved and
  3771. restored during function calls.
  3772. The approach that we recommend for variables that are in use during a
  3773. function call is to either assign them to callee-saved registers or to
  3774. spill them to the stack. On the other hand, for variables that are not
  3775. in use during a function call, we try the following alternatives in
  3776. order 1) look for an available caller-saved register (to leave room
  3777. for other variables in the callee-saved register), 2) look for a
  3778. callee-saved register, and 3) spill the variable to the stack.
  3779. It is straightforward to implement this approach in a graph coloring
  3780. register allocator. First, we know which variables are in use during
  3781. every function call because we compute that information for every
  3782. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3783. we build the interference graph
  3784. (Section~\ref{sec:build-interference}), we can place an edge between
  3785. each of these call-live variables and the caller-saved registers in
  3786. the interference graph. This will prevent the graph coloring algorithm
  3787. from assigning them to caller-saved registers.
  3788. Returning to the example in
  3789. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3790. generated x86 code on the right-hand side. Notice that variable
  3791. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3792. is already in a safe place during the second call to
  3793. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3794. \code{rcx}, a caller-saved register, because \code{y} is not in the
  3795. live-after set of a \code{callq} instruction.
  3796. Next we analyze the example from the callee point of view, focusing on
  3797. the prelude and conclusion of the \code{main} function. As usual the
  3798. prelude begins with saving the \code{rbp} register to the stack and
  3799. setting the \code{rbp} to the current stack pointer. We now know why
  3800. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3801. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3802. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3803. (\code{x}). The other callee-saved registers are not saved in the
  3804. prelude because they are not used. The prelude subtracts 8 bytes from
  3805. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3806. conclusion, we see that \code{rbx} is restored from the stack with a
  3807. \code{popq} instruction.
  3808. \index{subject}{prelude}\index{subject}{conclusion}
  3809. \begin{figure}[tp]
  3810. \begin{minipage}{0.45\textwidth}
  3811. Example \LangVar{} program:
  3812. %var_test_14.rkt
  3813. {\if\edition\racketEd
  3814. \begin{lstlisting}
  3815. (let ([x (read)])
  3816. (let ([y (read)])
  3817. (+ (+ x y) 42)))
  3818. \end{lstlisting}
  3819. \fi}
  3820. {\if\edition\pythonEd
  3821. \begin{lstlisting}
  3822. x = input_int()
  3823. y = input_int()
  3824. print((x + y) + 42)
  3825. \end{lstlisting}
  3826. \fi}
  3827. \end{minipage}
  3828. \begin{minipage}{0.45\textwidth}
  3829. Generated x86 assembly:
  3830. {\if\edition\racketEd
  3831. \begin{lstlisting}
  3832. start:
  3833. callq read_int
  3834. movq %rax, %rbx
  3835. callq read_int
  3836. movq %rax, %rcx
  3837. addq %rcx, %rbx
  3838. movq %rbx, %rax
  3839. addq $42, %rax
  3840. jmp _conclusion
  3841. .globl main
  3842. main:
  3843. pushq %rbp
  3844. movq %rsp, %rbp
  3845. pushq %rbx
  3846. subq $8, %rsp
  3847. jmp start
  3848. conclusion:
  3849. addq $8, %rsp
  3850. popq %rbx
  3851. popq %rbp
  3852. retq
  3853. \end{lstlisting}
  3854. \fi}
  3855. {\if\edition\pythonEd
  3856. \begin{lstlisting}
  3857. .globl main
  3858. main:
  3859. pushq %rbp
  3860. movq %rsp, %rbp
  3861. pushq %rbx
  3862. subq $8, %rsp
  3863. callq read_int
  3864. movq %rax, %rbx
  3865. callq read_int
  3866. movq %rax, %rcx
  3867. movq %rbx, %rdx
  3868. addq %rcx, %rdx
  3869. movq %rdx, %rcx
  3870. addq $42, %rcx
  3871. movq %rcx, %rdi
  3872. callq print_int
  3873. addq $8, %rsp
  3874. popq %rbx
  3875. popq %rbp
  3876. retq
  3877. \end{lstlisting}
  3878. \fi}
  3879. \end{minipage}
  3880. \caption{An example with function calls.}
  3881. \label{fig:example-calling-conventions}
  3882. \end{figure}
  3883. %\clearpage
  3884. \section{Liveness Analysis}
  3885. \label{sec:liveness-analysis-Lvar}
  3886. \index{subject}{liveness analysis}
  3887. The \code{uncover\_live} \racket{pass}\python{function}
  3888. performs \emph{liveness analysis}, that
  3889. is, it discovers which variables are in-use in different regions of a
  3890. program.
  3891. %
  3892. A variable or register is \emph{live} at a program point if its
  3893. current value is used at some later point in the program. We refer to
  3894. variables, stack locations, and registers collectively as
  3895. \emph{locations}.
  3896. %
  3897. Consider the following code fragment in which there are two writes to
  3898. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3899. \begin{center}
  3900. \begin{minipage}{0.96\textwidth}
  3901. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3902. movq $5, a
  3903. movq $30, b
  3904. movq a, c
  3905. movq $10, b
  3906. addq b, c
  3907. \end{lstlisting}
  3908. \end{minipage}
  3909. \end{center}
  3910. The answer is no because \code{a} is live from line 1 to 3 and
  3911. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3912. line 2 is never used because it is overwritten (line 4) before the
  3913. next read (line 5).
  3914. The live locations can be computed by traversing the instruction
  3915. sequence back to front (i.e., backwards in execution order). Let
  3916. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3917. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3918. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3919. locations before instruction $I_k$.
  3920. \racket{We recommend representing these
  3921. sets with the Racket \code{set} data structure described in
  3922. Figure~\ref{fig:set}.}
  3923. \python{We recommend representing these sets with the Python
  3924. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  3925. data structure.}
  3926. {\if\edition\racketEd
  3927. \begin{figure}[tp]
  3928. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  3929. \small
  3930. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3931. A \emph{set} is an unordered collection of elements without duplicates.
  3932. Here are some of the operations defined on sets.
  3933. \index{subject}{set}
  3934. \begin{description}
  3935. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  3936. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  3937. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  3938. difference of the two sets.
  3939. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  3940. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  3941. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  3942. \end{description}
  3943. \end{tcolorbox}
  3944. %\end{wrapfigure}
  3945. \caption{The \code{set} data structure.}
  3946. \label{fig:set}
  3947. \end{figure}
  3948. \fi}
  3949. The live locations after an instruction are always the same as the
  3950. live locations before the next instruction.
  3951. \index{subject}{live-after} \index{subject}{live-before}
  3952. \begin{equation} \label{eq:live-after-before-next}
  3953. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3954. \end{equation}
  3955. To start things off, there are no live locations after the last
  3956. instruction, so
  3957. \begin{equation}\label{eq:live-last-empty}
  3958. L_{\mathsf{after}}(n) = \emptyset
  3959. \end{equation}
  3960. We then apply the following rule repeatedly, traversing the
  3961. instruction sequence back to front.
  3962. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  3963. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  3964. \end{equation}
  3965. where $W(k)$ are the locations written to by instruction $I_k$ and
  3966. $R(k)$ are the locations read by instruction $I_k$.
  3967. {\if\edition\racketEd
  3968. There is a special case for \code{jmp} instructions. The locations
  3969. that are live before a \code{jmp} should be the locations in
  3970. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  3971. maintaining an alist named \code{label->live} that maps each label to
  3972. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  3973. now the only \code{jmp} in a \LangXVar{} program is the one at the
  3974. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  3975. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  3976. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  3977. \fi}
  3978. Let us walk through the above example, applying these formulas
  3979. starting with the instruction on line 5. We collect the answers in
  3980. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  3981. \code{addq b, c} instruction is $\emptyset$ because it is the last
  3982. instruction (formula~\ref{eq:live-last-empty}). The
  3983. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  3984. because it reads from variables \code{b} and \code{c}
  3985. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  3986. \[
  3987. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  3988. \]
  3989. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  3990. the live-before set from line 5 to be the live-after set for this
  3991. instruction (formula~\ref{eq:live-after-before-next}).
  3992. \[
  3993. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  3994. \]
  3995. This move instruction writes to \code{b} and does not read from any
  3996. variables, so we have the following live-before set
  3997. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  3998. \[
  3999. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4000. \]
  4001. The live-before for instruction \code{movq a, c}
  4002. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4003. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  4004. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4005. variable that is not live and does not read from a variable.
  4006. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4007. because it writes to variable \code{a}.
  4008. \begin{figure}[tbp]
  4009. \begin{minipage}{0.45\textwidth}
  4010. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4011. movq $5, a
  4012. movq $30, b
  4013. movq a, c
  4014. movq $10, b
  4015. addq b, c
  4016. \end{lstlisting}
  4017. \end{minipage}
  4018. \vrule\hspace{10pt}
  4019. \begin{minipage}{0.45\textwidth}
  4020. \begin{align*}
  4021. L_{\mathsf{before}}(1)= \emptyset,
  4022. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4023. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4024. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4025. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4026. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4027. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4028. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4029. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4030. L_{\mathsf{after}}(5)= \emptyset
  4031. \end{align*}
  4032. \end{minipage}
  4033. \caption{Example output of liveness analysis on a short example.}
  4034. \label{fig:liveness-example-0}
  4035. \end{figure}
  4036. \begin{exercise}\normalfont
  4037. Perform liveness analysis on the running example in
  4038. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4039. sets for each instruction. Compare your answers to the solution
  4040. shown in Figure~\ref{fig:live-eg}.
  4041. \end{exercise}
  4042. \begin{figure}[tp]
  4043. \hspace{20pt}
  4044. \begin{minipage}{0.45\textwidth}
  4045. {\if\edition\racketEd
  4046. \begin{lstlisting}
  4047. |$\{\ttm{rsp}\}$|
  4048. movq $1, v
  4049. |$\{\ttm{v},\ttm{rsp}\}$|
  4050. movq $42, w
  4051. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4052. movq v, x
  4053. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4054. addq $7, x
  4055. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4056. movq x, y
  4057. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4058. movq x, z
  4059. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4060. addq w, z
  4061. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4062. movq y, t
  4063. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4064. negq t
  4065. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4066. movq z, %rax
  4067. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4068. addq t, %rax
  4069. |$\{\ttm{rax},\ttm{rsp}\}$|
  4070. jmp conclusion
  4071. \end{lstlisting}
  4072. \fi}
  4073. {\if\edition\pythonEd
  4074. \begin{lstlisting}
  4075. movq $1, v
  4076. |$\{\ttm{v}\}$|
  4077. movq $42, w
  4078. |$\{\ttm{w}, \ttm{v}\}$|
  4079. movq v, x
  4080. |$\{\ttm{w}, \ttm{x}\}$|
  4081. addq $7, x
  4082. |$\{\ttm{w}, \ttm{x}\}$|
  4083. movq x, y
  4084. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4085. movq x, z
  4086. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4087. addq w, z
  4088. |$\{\ttm{y}, \ttm{z}\}$|
  4089. movq y, tmp_0
  4090. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4091. negq tmp_0
  4092. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4093. movq z, tmp_1
  4094. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4095. addq tmp_0, tmp_1
  4096. |$\{\ttm{tmp\_1}\}$|
  4097. movq tmp_1, %rdi
  4098. |$\{\ttm{rdi}\}$|
  4099. callq print_int
  4100. |$\{\}$|
  4101. \end{lstlisting}
  4102. \fi}
  4103. \end{minipage}
  4104. \caption{The running example annotated with live-after sets.}
  4105. \label{fig:live-eg}
  4106. \end{figure}
  4107. \begin{exercise}\normalfont
  4108. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4109. %
  4110. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4111. field of the \code{Block} structure.}
  4112. %
  4113. \python{Return a dictionary that maps each instruction to its
  4114. live-after set.}
  4115. %
  4116. \racket{We recommend creating an auxiliary function that takes a list
  4117. of instructions and an initial live-after set (typically empty) and
  4118. returns the list of live-after sets.}
  4119. %
  4120. We recommend creating auxiliary functions to 1) compute the set
  4121. of locations that appear in an \Arg{}, 2) compute the locations read
  4122. by an instruction (the $R$ function), and 3) the locations written by
  4123. an instruction (the $W$ function). The \code{callq} instruction should
  4124. include all of the caller-saved registers in its write-set $W$ because
  4125. the calling convention says that those registers may be written to
  4126. during the function call. Likewise, the \code{callq} instruction
  4127. should include the appropriate argument-passing registers in its
  4128. read-set $R$, depending on the arity of the function being
  4129. called. (This is why the abstract syntax for \code{callq} includes the
  4130. arity.)
  4131. \end{exercise}
  4132. %\clearpage
  4133. \section{Build the Interference Graph}
  4134. \label{sec:build-interference}
  4135. {\if\edition\racketEd
  4136. \begin{figure}[tp]
  4137. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4138. \small
  4139. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4140. A \emph{graph} is a collection of vertices and edges where each
  4141. edge connects two vertices. A graph is \emph{directed} if each
  4142. edge points from a source to a target. Otherwise the graph is
  4143. \emph{undirected}.
  4144. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4145. \begin{description}
  4146. %% We currently don't use directed graphs. We instead use
  4147. %% directed multi-graphs. -Jeremy
  4148. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4149. directed graph from a list of edges. Each edge is a list
  4150. containing the source and target vertex.
  4151. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4152. undirected graph from a list of edges. Each edge is represented by
  4153. a list containing two vertices.
  4154. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4155. inserts a vertex into the graph.
  4156. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4157. inserts an edge between the two vertices.
  4158. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4159. returns a sequence of vertices adjacent to the vertex.
  4160. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4161. returns a sequence of all vertices in the graph.
  4162. \end{description}
  4163. \end{tcolorbox}
  4164. %\end{wrapfigure}
  4165. \caption{The Racket \code{graph} package.}
  4166. \label{fig:graph}
  4167. \end{figure}
  4168. \fi}
  4169. Based on the liveness analysis, we know where each location is live.
  4170. However, during register allocation, we need to answer questions of
  4171. the specific form: are locations $u$ and $v$ live at the same time?
  4172. (And therefore cannot be assigned to the same register.) To make this
  4173. question more efficient to answer, we create an explicit data
  4174. structure, an \emph{interference graph}\index{subject}{interference
  4175. graph}. An interference graph is an undirected graph that has an
  4176. edge between two locations if they are live at the same time, that is,
  4177. if they interfere with each other.
  4178. %
  4179. \racket{We recommend using the Racket \code{graph} package
  4180. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4181. %
  4182. \python{We provide implementations of directed and undirected graph
  4183. data structures in the file \code{graph.py} of the support code.}
  4184. A straightforward way to compute the interference graph is to look at
  4185. the set of live locations between each instruction and add an edge to
  4186. the graph for every pair of variables in the same set. This approach
  4187. is less than ideal for two reasons. First, it can be expensive because
  4188. it takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  4189. locations. Second, in the special case where two locations hold the
  4190. same value (because one was assigned to the other), they can be live
  4191. at the same time without interfering with each other.
  4192. A better way to compute the interference graph is to focus on
  4193. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4194. must not overwrite something in a live location. So for each
  4195. instruction, we create an edge between the locations being written to
  4196. and the live locations. (Except that one should not create self
  4197. edges.) Note that for the \key{callq} instruction, we consider all of
  4198. the caller-saved registers as being written to, so an edge is added
  4199. between every live variable and every caller-saved register. Also, for
  4200. \key{movq} there is the above-mentioned special case to deal with. If
  4201. a live variable $v$ is the same as the source of the \key{movq}, then
  4202. there is no need to add an edge between $v$ and the destination,
  4203. because they both hold the same value.
  4204. %
  4205. So we have the following two rules.
  4206. \begin{enumerate}
  4207. \item If instruction $I_k$ is a move instruction of the form
  4208. \key{movq} $s$\key{,} $d$, then for every $v \in
  4209. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4210. $(d,v)$.
  4211. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4212. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4213. $(d,v)$.
  4214. \end{enumerate}
  4215. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4216. the above rules to each instruction. We highlight a few of the
  4217. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4218. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4219. so \code{v} interferes with \code{rsp}.}
  4220. %
  4221. \python{The first instruction is \lstinline{movq $1, v} and the
  4222. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4223. no interference because $\ttm{v}$ is the destination of the move.}
  4224. %
  4225. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4226. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4227. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4228. %
  4229. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4230. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4231. $\ttm{x}$ interferes with \ttm{w}.}
  4232. %
  4233. \racket{The next instruction is \lstinline{movq x, y} and the
  4234. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4235. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4236. \ttm{x} because \ttm{x} is the source of the move and therefore
  4237. \ttm{x} and \ttm{y} hold the same value.}
  4238. %
  4239. \python{The next instruction is \lstinline{movq x, y} and the
  4240. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4241. applies, so \ttm{y} interferes with \ttm{w} but not
  4242. \ttm{x} because \ttm{x} is the source of the move and therefore
  4243. \ttm{x} and \ttm{y} hold the same value.}
  4244. %
  4245. Figure~\ref{fig:interference-results} lists the interference results
  4246. for all of the instructions and the resulting interference graph is
  4247. shown in Figure~\ref{fig:interfere}.
  4248. \begin{figure}[tbp]
  4249. \begin{quote}
  4250. {\if\edition\racketEd
  4251. \begin{tabular}{ll}
  4252. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4253. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4254. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4255. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4256. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4257. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4258. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4259. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4260. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4261. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4262. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4263. \lstinline!jmp conclusion!& no interference.
  4264. \end{tabular}
  4265. \fi}
  4266. {\if\edition\pythonEd
  4267. \begin{tabular}{ll}
  4268. \lstinline!movq $1, v!& no interference\\
  4269. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4270. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4271. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4272. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4273. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4274. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4275. \lstinline!movq y, tmp_0!& \ttm{t} interferes with \ttm{z} \\
  4276. \lstinline!negq tmp_0!& \ttm{t} interferes with \ttm{z} \\
  4277. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4278. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4279. \lstinline!movq tmp_1, %rdi! & no interference \\
  4280. \lstinline!callq print_int!& no interference.
  4281. \end{tabular}
  4282. \fi}
  4283. \end{quote}
  4284. \caption{Interference results for the running example.}
  4285. \label{fig:interference-results}
  4286. \end{figure}
  4287. \begin{figure}[tbp]
  4288. \large
  4289. {\if\edition\racketEd
  4290. \[
  4291. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4292. \node (rax) at (0,0) {$\ttm{rax}$};
  4293. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4294. \node (t1) at (0,2) {$\ttm{t}$};
  4295. \node (z) at (3,2) {$\ttm{z}$};
  4296. \node (x) at (6,2) {$\ttm{x}$};
  4297. \node (y) at (3,0) {$\ttm{y}$};
  4298. \node (w) at (6,0) {$\ttm{w}$};
  4299. \node (v) at (9,0) {$\ttm{v}$};
  4300. \draw (t1) to (rax);
  4301. \draw (t1) to (z);
  4302. \draw (z) to (y);
  4303. \draw (z) to (w);
  4304. \draw (x) to (w);
  4305. \draw (y) to (w);
  4306. \draw (v) to (w);
  4307. \draw (v) to (rsp);
  4308. \draw (w) to (rsp);
  4309. \draw (x) to (rsp);
  4310. \draw (y) to (rsp);
  4311. \path[-.,bend left=15] (z) edge node {} (rsp);
  4312. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4313. \draw (rax) to (rsp);
  4314. \end{tikzpicture}
  4315. \]
  4316. \fi}
  4317. {\if\edition\pythonEd
  4318. \[
  4319. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4320. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4321. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4322. \node (z) at (3,2) {$\ttm{z}$};
  4323. \node (x) at (6,2) {$\ttm{x}$};
  4324. \node (y) at (3,0) {$\ttm{y}$};
  4325. \node (w) at (6,0) {$\ttm{w}$};
  4326. \node (v) at (9,0) {$\ttm{v}$};
  4327. \draw (t0) to (t1);
  4328. \draw (t0) to (z);
  4329. \draw (z) to (y);
  4330. \draw (z) to (w);
  4331. \draw (x) to (w);
  4332. \draw (y) to (w);
  4333. \draw (v) to (w);
  4334. \end{tikzpicture}
  4335. \]
  4336. \fi}
  4337. \caption{The interference graph of the example program.}
  4338. \label{fig:interfere}
  4339. \end{figure}
  4340. %% Our next concern is to choose a data structure for representing the
  4341. %% interference graph. There are many choices for how to represent a
  4342. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4343. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4344. %% data structure is to study the algorithm that uses the data structure,
  4345. %% determine what operations need to be performed, and then choose the
  4346. %% data structure that provide the most efficient implementations of
  4347. %% those operations. Often times the choice of data structure can have an
  4348. %% effect on the time complexity of the algorithm, as it does here. If
  4349. %% you skim the next section, you will see that the register allocation
  4350. %% algorithm needs to ask the graph for all of its vertices and, given a
  4351. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4352. %% correct choice of graph representation is that of an adjacency
  4353. %% list. There are helper functions in \code{utilities.rkt} for
  4354. %% representing graphs using the adjacency list representation:
  4355. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4356. %% (Appendix~\ref{appendix:utilities}).
  4357. %% %
  4358. %% \margincomment{\footnotesize To do: change to use the
  4359. %% Racket graph library. \\ --Jeremy}
  4360. %% %
  4361. %% In particular, those functions use a hash table to map each vertex to
  4362. %% the set of adjacent vertices, and the sets are represented using
  4363. %% Racket's \key{set}, which is also a hash table.
  4364. \begin{exercise}\normalfont
  4365. \racket{Implement the compiler pass named \code{build\_interference} according
  4366. to the algorithm suggested above. We recommend using the Racket
  4367. \code{graph} package to create and inspect the interference graph.
  4368. The output graph of this pass should be stored in the $\itm{info}$ field of
  4369. the program, under the key \code{conflicts}.}
  4370. %
  4371. \python{Implement a function named \code{build\_interference}
  4372. according to the algorithm suggested above that
  4373. returns the interference graph.}
  4374. \end{exercise}
  4375. \section{Graph Coloring via Sudoku}
  4376. \label{sec:graph-coloring}
  4377. \index{subject}{graph coloring}
  4378. \index{subject}{Sudoku}
  4379. \index{subject}{color}
  4380. We come to the main event, mapping variables to registers and stack
  4381. locations. Variables that interfere with each other must be mapped to
  4382. different locations. In terms of the interference graph, this means
  4383. that adjacent vertices must be mapped to different locations. If we
  4384. think of locations as colors, the register allocation problem becomes
  4385. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4386. The reader may be more familiar with the graph coloring problem than he
  4387. or she realizes; the popular game of Sudoku is an instance of the
  4388. graph coloring problem. The following describes how to build a graph
  4389. out of an initial Sudoku board.
  4390. \begin{itemize}
  4391. \item There is one vertex in the graph for each Sudoku square.
  4392. \item There is an edge between two vertices if the corresponding squares
  4393. are in the same row, in the same column, or if the squares are in
  4394. the same $3\times 3$ region.
  4395. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4396. \item Based on the initial assignment of numbers to squares in the
  4397. Sudoku board, assign the corresponding colors to the corresponding
  4398. vertices in the graph.
  4399. \end{itemize}
  4400. If you can color the remaining vertices in the graph with the nine
  4401. colors, then you have also solved the corresponding game of Sudoku.
  4402. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4403. the corresponding graph with colored vertices. We map the Sudoku
  4404. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4405. sampling of the vertices (the colored ones) because showing edges for
  4406. all of the vertices would make the graph unreadable.
  4407. \begin{figure}[tbp]
  4408. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4409. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4410. \caption{A Sudoku game board and the corresponding colored graph.}
  4411. \label{fig:sudoku-graph}
  4412. \end{figure}
  4413. Some techniques for playing Sudoku correspond to heuristics used in
  4414. graph coloring algorithms. For example, one of the basic techniques
  4415. for Sudoku is called Pencil Marks. The idea is to use a process of
  4416. elimination to determine what numbers are no longer available for a
  4417. square and write down those numbers in the square (writing very
  4418. small). For example, if the number $1$ is assigned to a square, then
  4419. write the pencil mark $1$ in all the squares in the same row, column,
  4420. and region to indicate that $1$ is no longer an option for those other
  4421. squares.
  4422. %
  4423. The Pencil Marks technique corresponds to the notion of
  4424. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4425. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4426. are no longer available. In graph terminology, we have the following
  4427. definition:
  4428. \begin{equation*}
  4429. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4430. \text{ and } \mathrm{color}(v) = c \}
  4431. \end{equation*}
  4432. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4433. edge with $u$.
  4434. The Pencil Marks technique leads to a simple strategy for filling in
  4435. numbers: if there is a square with only one possible number left, then
  4436. choose that number! But what if there are no squares with only one
  4437. possibility left? One brute-force approach is to try them all: choose
  4438. the first one and if that ultimately leads to a solution, great. If
  4439. not, backtrack and choose the next possibility. One good thing about
  4440. Pencil Marks is that it reduces the degree of branching in the search
  4441. tree. Nevertheless, backtracking can be terribly time consuming. One
  4442. way to reduce the amount of backtracking is to use the
  4443. most-constrained-first heuristic (aka. minimum remaining
  4444. values)~\citep{Russell2003}. That is, when choosing a square, always
  4445. choose one with the fewest possibilities left (the vertex with the
  4446. highest saturation). The idea is that choosing highly constrained
  4447. squares earlier rather than later is better because later on there may
  4448. not be any possibilities left in the highly saturated squares.
  4449. However, register allocation is easier than Sudoku because the
  4450. register allocator can fall back to assigning variables to stack
  4451. locations when the registers run out. Thus, it makes sense to replace
  4452. backtracking with greedy search: make the best choice at the time and
  4453. keep going. We still wish to minimize the number of colors needed, so
  4454. we use the most-constrained-first heuristic in the greedy search.
  4455. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4456. algorithm for register allocation based on saturation and the
  4457. most-constrained-first heuristic. It is roughly equivalent to the
  4458. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4459. %,Gebremedhin:1999fk,Omari:2006uq
  4460. Just as in Sudoku, the algorithm represents colors with integers. The
  4461. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4462. for register allocation. The integers $k$ and larger correspond to
  4463. stack locations. The registers that are not used for register
  4464. allocation, such as \code{rax}, are assigned to negative integers. In
  4465. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4466. %% One might wonder why we include registers at all in the liveness
  4467. %% analysis and interference graph. For example, we never allocate a
  4468. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4469. %% leave them out. As we see in Chapter~\ref{ch:Lvec}, when we begin
  4470. %% to use register for passing arguments to functions, it will be
  4471. %% necessary for those registers to appear in the interference graph
  4472. %% because those registers will also be assigned to variables, and we
  4473. %% don't want those two uses to encroach on each other. Regarding
  4474. %% registers such as \code{rax} and \code{rsp} that are not used for
  4475. %% variables, we could omit them from the interference graph but that
  4476. %% would require adding special cases to our algorithm, which would
  4477. %% complicate the logic for little gain.
  4478. \begin{figure}[btp]
  4479. \centering
  4480. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4481. Algorithm: DSATUR
  4482. Input: a graph |$G$|
  4483. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4484. |$W \gets \mathrm{vertices}(G)$|
  4485. while |$W \neq \emptyset$| do
  4486. pick a vertex |$u$| from |$W$| with the highest saturation,
  4487. breaking ties randomly
  4488. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4489. |$\mathrm{color}[u] \gets c$|
  4490. |$W \gets W - \{u\}$|
  4491. \end{lstlisting}
  4492. \caption{The saturation-based greedy graph coloring algorithm.}
  4493. \label{fig:satur-algo}
  4494. \end{figure}
  4495. {\if\edition\racketEd
  4496. With the DSATUR algorithm in hand, let us return to the running
  4497. example and consider how to color the interference graph in
  4498. Figure~\ref{fig:interfere}.
  4499. %
  4500. We start by assigning the register nodes to their own color. For
  4501. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4502. assigned $-2$. The variables are not yet colored, so they are
  4503. annotated with a dash. We then update the saturation for vertices that
  4504. are adjacent to a register, obtaining the following annotated
  4505. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4506. it interferes with both \code{rax} and \code{rsp}.
  4507. \[
  4508. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4509. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4510. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4511. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4512. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4513. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4514. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4515. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4516. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4517. \draw (t1) to (rax);
  4518. \draw (t1) to (z);
  4519. \draw (z) to (y);
  4520. \draw (z) to (w);
  4521. \draw (x) to (w);
  4522. \draw (y) to (w);
  4523. \draw (v) to (w);
  4524. \draw (v) to (rsp);
  4525. \draw (w) to (rsp);
  4526. \draw (x) to (rsp);
  4527. \draw (y) to (rsp);
  4528. \path[-.,bend left=15] (z) edge node {} (rsp);
  4529. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4530. \draw (rax) to (rsp);
  4531. \end{tikzpicture}
  4532. \]
  4533. The algorithm says to select a maximally saturated vertex. So we pick
  4534. $\ttm{t}$ and color it with the first available integer, which is
  4535. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4536. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4537. \[
  4538. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4539. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4540. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4541. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4542. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4543. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4544. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4545. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4546. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4547. \draw (t1) to (rax);
  4548. \draw (t1) to (z);
  4549. \draw (z) to (y);
  4550. \draw (z) to (w);
  4551. \draw (x) to (w);
  4552. \draw (y) to (w);
  4553. \draw (v) to (w);
  4554. \draw (v) to (rsp);
  4555. \draw (w) to (rsp);
  4556. \draw (x) to (rsp);
  4557. \draw (y) to (rsp);
  4558. \path[-.,bend left=15] (z) edge node {} (rsp);
  4559. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4560. \draw (rax) to (rsp);
  4561. \end{tikzpicture}
  4562. \]
  4563. We repeat the process, selecting a maximally saturated vertex,
  4564. choosing is \code{z}, and color it with the first available number, which
  4565. is $1$. We add $1$ to the saturation for the neighboring vertices
  4566. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4567. \[
  4568. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4569. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4570. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4571. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4572. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4573. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4574. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4575. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4576. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4577. \draw (t1) to (rax);
  4578. \draw (t1) to (z);
  4579. \draw (z) to (y);
  4580. \draw (z) to (w);
  4581. \draw (x) to (w);
  4582. \draw (y) to (w);
  4583. \draw (v) to (w);
  4584. \draw (v) to (rsp);
  4585. \draw (w) to (rsp);
  4586. \draw (x) to (rsp);
  4587. \draw (y) to (rsp);
  4588. \path[-.,bend left=15] (z) edge node {} (rsp);
  4589. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4590. \draw (rax) to (rsp);
  4591. \end{tikzpicture}
  4592. \]
  4593. The most saturated vertices are now \code{w} and \code{y}. We color
  4594. \code{w} with the first available color, which is $0$.
  4595. \[
  4596. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4597. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4598. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4599. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4600. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4601. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4602. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4603. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4604. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4605. \draw (t1) to (rax);
  4606. \draw (t1) to (z);
  4607. \draw (z) to (y);
  4608. \draw (z) to (w);
  4609. \draw (x) to (w);
  4610. \draw (y) to (w);
  4611. \draw (v) to (w);
  4612. \draw (v) to (rsp);
  4613. \draw (w) to (rsp);
  4614. \draw (x) to (rsp);
  4615. \draw (y) to (rsp);
  4616. \path[-.,bend left=15] (z) edge node {} (rsp);
  4617. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4618. \draw (rax) to (rsp);
  4619. \end{tikzpicture}
  4620. \]
  4621. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4622. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4623. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4624. and \code{z}, whose colors are $0$ and $1$ respectively.
  4625. \[
  4626. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4627. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4628. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4629. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4630. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4631. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4632. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4633. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4634. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4635. \draw (t1) to (rax);
  4636. \draw (t1) to (z);
  4637. \draw (z) to (y);
  4638. \draw (z) to (w);
  4639. \draw (x) to (w);
  4640. \draw (y) to (w);
  4641. \draw (v) to (w);
  4642. \draw (v) to (rsp);
  4643. \draw (w) to (rsp);
  4644. \draw (x) to (rsp);
  4645. \draw (y) to (rsp);
  4646. \path[-.,bend left=15] (z) edge node {} (rsp);
  4647. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4648. \draw (rax) to (rsp);
  4649. \end{tikzpicture}
  4650. \]
  4651. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4652. \[
  4653. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4654. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4655. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4656. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4657. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4658. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4659. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4660. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4661. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4662. \draw (t1) to (rax);
  4663. \draw (t1) to (z);
  4664. \draw (z) to (y);
  4665. \draw (z) to (w);
  4666. \draw (x) to (w);
  4667. \draw (y) to (w);
  4668. \draw (v) to (w);
  4669. \draw (v) to (rsp);
  4670. \draw (w) to (rsp);
  4671. \draw (x) to (rsp);
  4672. \draw (y) to (rsp);
  4673. \path[-.,bend left=15] (z) edge node {} (rsp);
  4674. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4675. \draw (rax) to (rsp);
  4676. \end{tikzpicture}
  4677. \]
  4678. In the last step of the algorithm, we color \code{x} with $1$.
  4679. \[
  4680. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4681. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4682. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4683. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4684. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4685. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4686. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4687. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4688. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4689. \draw (t1) to (rax);
  4690. \draw (t1) to (z);
  4691. \draw (z) to (y);
  4692. \draw (z) to (w);
  4693. \draw (x) to (w);
  4694. \draw (y) to (w);
  4695. \draw (v) to (w);
  4696. \draw (v) to (rsp);
  4697. \draw (w) to (rsp);
  4698. \draw (x) to (rsp);
  4699. \draw (y) to (rsp);
  4700. \path[-.,bend left=15] (z) edge node {} (rsp);
  4701. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4702. \draw (rax) to (rsp);
  4703. \end{tikzpicture}
  4704. \]
  4705. So we obtain the following coloring:
  4706. \[
  4707. \{
  4708. \ttm{rax} \mapsto -1,
  4709. \ttm{rsp} \mapsto -2,
  4710. \ttm{t} \mapsto 0,
  4711. \ttm{z} \mapsto 1,
  4712. \ttm{x} \mapsto 1,
  4713. \ttm{y} \mapsto 2,
  4714. \ttm{w} \mapsto 0,
  4715. \ttm{v} \mapsto 1
  4716. \}
  4717. \]
  4718. \fi}
  4719. %
  4720. {\if\edition\pythonEd
  4721. %
  4722. With the DSATUR algorithm in hand, let us return to the running
  4723. example and consider how to color the interference graph in
  4724. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4725. to indicate that it has not yet been assigned a color. The saturation
  4726. sets are also shown for each node; all of them start as the empty set.
  4727. (We do not include the register nodes in the graph below because there
  4728. were no interference edges involving registers in this program, but in
  4729. general there can be.)
  4730. %
  4731. \[
  4732. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4733. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4734. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4735. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4736. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4737. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4738. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4739. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4740. \draw (t0) to (t1);
  4741. \draw (t0) to (z);
  4742. \draw (z) to (y);
  4743. \draw (z) to (w);
  4744. \draw (x) to (w);
  4745. \draw (y) to (w);
  4746. \draw (v) to (w);
  4747. \end{tikzpicture}
  4748. \]
  4749. The algorithm says to select a maximally saturated vertex, but they
  4750. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4751. then color it with the first available integer, which is $0$. We mark
  4752. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4753. they interfere with $\ttm{tmp\_0}$.
  4754. \[
  4755. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4756. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4757. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4758. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4759. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4760. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4761. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4762. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4763. \draw (t0) to (t1);
  4764. \draw (t0) to (z);
  4765. \draw (z) to (y);
  4766. \draw (z) to (w);
  4767. \draw (x) to (w);
  4768. \draw (y) to (w);
  4769. \draw (v) to (w);
  4770. \end{tikzpicture}
  4771. \]
  4772. We repeat the process. The most saturated vertices are \code{z} and
  4773. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4774. available number, which is $1$. We add $1$ to the saturation for the
  4775. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4776. \[
  4777. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4778. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4779. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4780. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4781. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4782. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4783. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4784. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4785. \draw (t0) to (t1);
  4786. \draw (t0) to (z);
  4787. \draw (z) to (y);
  4788. \draw (z) to (w);
  4789. \draw (x) to (w);
  4790. \draw (y) to (w);
  4791. \draw (v) to (w);
  4792. \end{tikzpicture}
  4793. \]
  4794. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4795. \code{y}. We color \code{w} with the first available color, which
  4796. is $0$.
  4797. \[
  4798. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4799. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4800. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4801. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4802. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4803. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4804. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4805. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4806. \draw (t0) to (t1);
  4807. \draw (t0) to (z);
  4808. \draw (z) to (y);
  4809. \draw (z) to (w);
  4810. \draw (x) to (w);
  4811. \draw (y) to (w);
  4812. \draw (v) to (w);
  4813. \end{tikzpicture}
  4814. \]
  4815. Now \code{y} is the most saturated, so we color it with $2$.
  4816. \[
  4817. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4818. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4819. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4820. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4821. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4822. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4823. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4824. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4825. \draw (t0) to (t1);
  4826. \draw (t0) to (z);
  4827. \draw (z) to (y);
  4828. \draw (z) to (w);
  4829. \draw (x) to (w);
  4830. \draw (y) to (w);
  4831. \draw (v) to (w);
  4832. \end{tikzpicture}
  4833. \]
  4834. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  4835. We choose to color \code{v} with $1$.
  4836. \[
  4837. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4838. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4839. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4840. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4841. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4842. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4843. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4844. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4845. \draw (t0) to (t1);
  4846. \draw (t0) to (z);
  4847. \draw (z) to (y);
  4848. \draw (z) to (w);
  4849. \draw (x) to (w);
  4850. \draw (y) to (w);
  4851. \draw (v) to (w);
  4852. \end{tikzpicture}
  4853. \]
  4854. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4855. \[
  4856. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4857. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4858. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4859. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4860. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4861. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4862. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4863. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4864. \draw (t0) to (t1);
  4865. \draw (t0) to (z);
  4866. \draw (z) to (y);
  4867. \draw (z) to (w);
  4868. \draw (x) to (w);
  4869. \draw (y) to (w);
  4870. \draw (v) to (w);
  4871. \end{tikzpicture}
  4872. \]
  4873. So we obtain the following coloring:
  4874. \[
  4875. \{ \ttm{tmp\_0} \mapsto 0,
  4876. \ttm{tmp\_1} \mapsto 1,
  4877. \ttm{z} \mapsto 1,
  4878. \ttm{x} \mapsto 1,
  4879. \ttm{y} \mapsto 2,
  4880. \ttm{w} \mapsto 0,
  4881. \ttm{v} \mapsto 1 \}
  4882. \]
  4883. \fi}
  4884. We recommend creating an auxiliary function named \code{color\_graph}
  4885. that takes an interference graph and a list of all the variables in
  4886. the program. This function should return a mapping of variables to
  4887. their colors (represented as natural numbers). By creating this helper
  4888. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  4889. when we add support for functions.
  4890. To prioritize the processing of highly saturated nodes inside the
  4891. \code{color\_graph} function, we recommend using the priority queue
  4892. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  4893. addition, you will need to maintain a mapping from variables to their
  4894. ``handles'' in the priority queue so that you can notify the priority
  4895. queue when their saturation changes.}
  4896. {\if\edition\racketEd
  4897. \begin{figure}[tp]
  4898. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4899. \small
  4900. \begin{tcolorbox}[title=Priority Queue]
  4901. A \emph{priority queue} is a collection of items in which the
  4902. removal of items is governed by priority. In a ``min'' queue,
  4903. lower priority items are removed first. An implementation is in
  4904. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4905. queue} \index{subject}{minimum priority queue}
  4906. \begin{description}
  4907. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4908. priority queue that uses the $\itm{cmp}$ predicate to determine
  4909. whether its first argument has lower or equal priority to its
  4910. second argument.
  4911. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4912. items in the queue.
  4913. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4914. the item into the queue and returns a handle for the item in the
  4915. queue.
  4916. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4917. the lowest priority.
  4918. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4919. notifies the queue that the priority has decreased for the item
  4920. associated with the given handle.
  4921. \end{description}
  4922. \end{tcolorbox}
  4923. %\end{wrapfigure}
  4924. \caption{The priority queue data structure.}
  4925. \label{fig:priority-queue}
  4926. \end{figure}
  4927. \fi}
  4928. With the coloring complete, we finalize the assignment of variables to
  4929. registers and stack locations. We map the first $k$ colors to the $k$
  4930. registers and the rest of the colors to stack locations. Suppose for
  4931. the moment that we have just one register to use for register
  4932. allocation, \key{rcx}. Then we have the following map from colors to
  4933. locations.
  4934. \[
  4935. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4936. \]
  4937. Composing this mapping with the coloring, we arrive at the following
  4938. assignment of variables to locations.
  4939. {\if\edition\racketEd
  4940. \begin{gather*}
  4941. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4942. \ttm{w} \mapsto \key{\%rcx}, \,
  4943. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4944. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4945. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4946. \ttm{t} \mapsto \key{\%rcx} \}
  4947. \end{gather*}
  4948. \fi}
  4949. {\if\edition\pythonEd
  4950. \begin{gather*}
  4951. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4952. \ttm{w} \mapsto \key{\%rcx}, \,
  4953. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4954. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4955. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4956. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  4957. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  4958. \end{gather*}
  4959. \fi}
  4960. Adapt the code from the \code{assign\_homes} pass
  4961. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  4962. assigned location. Applying the above assignment to our running
  4963. example, on the left, yields the program on the right.
  4964. % why frame size of 32? -JGS
  4965. \begin{center}
  4966. {\if\edition\racketEd
  4967. \begin{minipage}{0.3\textwidth}
  4968. \begin{lstlisting}
  4969. movq $1, v
  4970. movq $42, w
  4971. movq v, x
  4972. addq $7, x
  4973. movq x, y
  4974. movq x, z
  4975. addq w, z
  4976. movq y, t
  4977. negq t
  4978. movq z, %rax
  4979. addq t, %rax
  4980. jmp conclusion
  4981. \end{lstlisting}
  4982. \end{minipage}
  4983. $\Rightarrow\qquad$
  4984. \begin{minipage}{0.45\textwidth}
  4985. \begin{lstlisting}
  4986. movq $1, -8(%rbp)
  4987. movq $42, %rcx
  4988. movq -8(%rbp), -8(%rbp)
  4989. addq $7, -8(%rbp)
  4990. movq -8(%rbp), -16(%rbp)
  4991. movq -8(%rbp), -8(%rbp)
  4992. addq %rcx, -8(%rbp)
  4993. movq -16(%rbp), %rcx
  4994. negq %rcx
  4995. movq -8(%rbp), %rax
  4996. addq %rcx, %rax
  4997. jmp conclusion
  4998. \end{lstlisting}
  4999. \end{minipage}
  5000. \fi}
  5001. {\if\edition\pythonEd
  5002. \begin{minipage}{0.3\textwidth}
  5003. \begin{lstlisting}
  5004. movq $1, v
  5005. movq $42, w
  5006. movq v, x
  5007. addq $7, x
  5008. movq x, y
  5009. movq x, z
  5010. addq w, z
  5011. movq y, tmp_0
  5012. negq tmp_0
  5013. movq z, tmp_1
  5014. addq tmp_0, tmp_1
  5015. movq tmp_1, %rdi
  5016. callq print_int
  5017. \end{lstlisting}
  5018. \end{minipage}
  5019. $\Rightarrow\qquad$
  5020. \begin{minipage}{0.45\textwidth}
  5021. \begin{lstlisting}
  5022. movq $1, -8(%rbp)
  5023. movq $42, %rcx
  5024. movq -8(%rbp), -8(%rbp)
  5025. addq $7, -8(%rbp)
  5026. movq -8(%rbp), -16(%rbp)
  5027. movq -8(%rbp), -8(%rbp)
  5028. addq %rcx, -8(%rbp)
  5029. movq -16(%rbp), %rcx
  5030. negq %rcx
  5031. movq -8(%rbp), -8(%rbp)
  5032. addq %rcx, -8(%rbp)
  5033. movq -8(%rbp), %rdi
  5034. callq print_int
  5035. \end{lstlisting}
  5036. \end{minipage}
  5037. \fi}
  5038. \end{center}
  5039. \begin{exercise}\normalfont
  5040. %
  5041. Implement the compiler pass \code{allocate\_registers}.
  5042. %
  5043. Create five programs that exercise all aspects of the register
  5044. allocation algorithm, including spilling variables to the stack.
  5045. %
  5046. \racket{Replace \code{assign\_homes} in the list of \code{passes} in the
  5047. \code{run-tests.rkt} script with the three new passes:
  5048. \code{uncover\_live}, \code{build\_interference}, and
  5049. \code{allocate\_registers}.
  5050. %
  5051. Temporarily remove the \code{print\_x86} pass from the list of passes
  5052. and the call to \code{compiler-tests}.
  5053. Run the script to test the register allocator.
  5054. }
  5055. %
  5056. \python{Run the \code{run-tests.py} script to to check whether the
  5057. output programs produce the same result as the input programs.}
  5058. \end{exercise}
  5059. \section{Patch Instructions}
  5060. \label{sec:patch-instructions}
  5061. The remaining step in the compilation to x86 is to ensure that the
  5062. instructions have at most one argument that is a memory access.
  5063. %
  5064. In the running example, the instruction \code{movq -8(\%rbp),
  5065. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  5066. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5067. then move \code{rax} into \code{-16(\%rbp)}.
  5068. %
  5069. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5070. problematic, but they can simply be deleted. In general, we recommend
  5071. deleting all the trivial moves whose source and destination are the
  5072. same location.
  5073. %
  5074. The following is the output of \code{patch\_instructions} on the
  5075. running example.
  5076. \begin{center}
  5077. {\if\edition\racketEd
  5078. \begin{minipage}{0.4\textwidth}
  5079. \begin{lstlisting}
  5080. movq $1, -8(%rbp)
  5081. movq $42, %rcx
  5082. movq -8(%rbp), -8(%rbp)
  5083. addq $7, -8(%rbp)
  5084. movq -8(%rbp), -16(%rbp)
  5085. movq -8(%rbp), -8(%rbp)
  5086. addq %rcx, -8(%rbp)
  5087. movq -16(%rbp), %rcx
  5088. negq %rcx
  5089. movq -8(%rbp), %rax
  5090. addq %rcx, %rax
  5091. jmp conclusion
  5092. \end{lstlisting}
  5093. \end{minipage}
  5094. $\Rightarrow\qquad$
  5095. \begin{minipage}{0.45\textwidth}
  5096. \begin{lstlisting}
  5097. movq $1, -8(%rbp)
  5098. movq $42, %rcx
  5099. addq $7, -8(%rbp)
  5100. movq -8(%rbp), %rax
  5101. movq %rax, -16(%rbp)
  5102. addq %rcx, -8(%rbp)
  5103. movq -16(%rbp), %rcx
  5104. negq %rcx
  5105. movq -8(%rbp), %rax
  5106. addq %rcx, %rax
  5107. jmp conclusion
  5108. \end{lstlisting}
  5109. \end{minipage}
  5110. \fi}
  5111. {\if\edition\pythonEd
  5112. \begin{minipage}{0.4\textwidth}
  5113. \begin{lstlisting}
  5114. movq $1, -8(%rbp)
  5115. movq $42, %rcx
  5116. movq -8(%rbp), -8(%rbp)
  5117. addq $7, -8(%rbp)
  5118. movq -8(%rbp), -16(%rbp)
  5119. movq -8(%rbp), -8(%rbp)
  5120. addq %rcx, -8(%rbp)
  5121. movq -16(%rbp), %rcx
  5122. negq %rcx
  5123. movq -8(%rbp), -8(%rbp)
  5124. addq %rcx, -8(%rbp)
  5125. movq -8(%rbp), %rdi
  5126. callq print_int
  5127. \end{lstlisting}
  5128. \end{minipage}
  5129. $\Rightarrow\qquad$
  5130. \begin{minipage}{0.45\textwidth}
  5131. \begin{lstlisting}
  5132. movq $1, -8(%rbp)
  5133. movq $42, %rcx
  5134. addq $7, -8(%rbp)
  5135. movq -8(%rbp), %rax
  5136. movq %rax, -16(%rbp)
  5137. addq %rcx, -8(%rbp)
  5138. movq -16(%rbp), %rcx
  5139. negq %rcx
  5140. addq %rcx, -8(%rbp)
  5141. movq -8(%rbp), %rdi
  5142. callq print_int
  5143. \end{lstlisting}
  5144. \end{minipage}
  5145. \fi}
  5146. \end{center}
  5147. \begin{exercise}\normalfont
  5148. %
  5149. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5150. %
  5151. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5152. %in the \code{run-tests.rkt} script.
  5153. %
  5154. Run the script to test the \code{patch\_instructions} pass.
  5155. \end{exercise}
  5156. \section{Prelude and Conclusion}
  5157. \label{sec:print-x86-reg-alloc}
  5158. \index{subject}{calling conventions}
  5159. \index{subject}{prelude}\index{subject}{conclusion}
  5160. Recall that this pass generates the prelude and conclusion
  5161. instructions to satisfy the x86 calling conventions
  5162. (Section~\ref{sec:calling-conventions}). With the addition of the
  5163. register allocator, the callee-saved registers used by the register
  5164. allocator must be saved in the prelude and restored in the conclusion.
  5165. In the \code{allocate\_registers} pass,
  5166. %
  5167. \racket{add an entry to the \itm{info}
  5168. of \code{X86Program} named \code{used\_callee}}
  5169. %
  5170. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5171. %
  5172. that stores the set of callee-saved registers that were assigned to
  5173. variables. The \code{prelude\_and\_conclusion} pass can then access
  5174. this information to decide which callee-saved registers need to be
  5175. saved and restored.
  5176. %
  5177. When calculating the size of the frame to adjust the \code{rsp} in the
  5178. prelude, make sure to take into account the space used for saving the
  5179. callee-saved registers. Also, don't forget that the frame needs to be
  5180. a multiple of 16 bytes!
  5181. \racket{An overview of all of the passes involved in register
  5182. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5183. {\if\edition\racketEd
  5184. \begin{figure}[tbp]
  5185. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5186. \node (Lvar) at (0,2) {\large \LangVar{}};
  5187. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5188. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  5189. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5190. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5191. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5192. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5193. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5194. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5195. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5196. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5197. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5198. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5199. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5200. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5201. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5202. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5203. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5204. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  5205. \end{tikzpicture}
  5206. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5207. \label{fig:reg-alloc-passes}
  5208. \end{figure}
  5209. \fi}
  5210. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5211. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5212. use of registers and the stack, we limit the register allocator for
  5213. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5214. the prelude\index{subject}{prelude} of the \code{main} function, we
  5215. push \code{rbx} onto the stack because it is a callee-saved register
  5216. and it was assigned to variable by the register allocator. We
  5217. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5218. reserve space for the one spilled variable. After that subtraction,
  5219. the \code{rsp} is aligned to 16 bytes.
  5220. Moving on to the program proper, we see how the registers were
  5221. allocated.
  5222. %
  5223. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5224. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5225. %
  5226. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5227. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5228. were assigned to \code{rbx}.}
  5229. %
  5230. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5231. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5232. callee-save register \code{rbx} onto the stack. The spilled variables
  5233. must be placed lower on the stack than the saved callee-save
  5234. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5235. \code{-16(\%rbp)}.
  5236. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5237. done in the prelude. We move the stack pointer up by \code{8} bytes
  5238. (the room for spilled variables), then we pop the old values of
  5239. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5240. \code{retq} to return control to the operating system.
  5241. \begin{figure}[tbp]
  5242. % var_test_28.rkt
  5243. % (use-minimal-set-of-registers! #t)
  5244. % and only rbx rcx
  5245. % tmp 0 rbx
  5246. % z 1 rcx
  5247. % y 0 rbx
  5248. % w 2 16(%rbp)
  5249. % v 0 rbx
  5250. % x 0 rbx
  5251. {\if\edition\racketEd
  5252. \begin{lstlisting}
  5253. start:
  5254. movq $1, %rbx
  5255. movq $42, -16(%rbp)
  5256. addq $7, %rbx
  5257. movq %rbx, %rcx
  5258. addq -16(%rbp), %rcx
  5259. negq %rbx
  5260. movq %rcx, %rax
  5261. addq %rbx, %rax
  5262. jmp conclusion
  5263. .globl main
  5264. main:
  5265. pushq %rbp
  5266. movq %rsp, %rbp
  5267. pushq %rbx
  5268. subq $8, %rsp
  5269. jmp start
  5270. conclusion:
  5271. addq $8, %rsp
  5272. popq %rbx
  5273. popq %rbp
  5274. retq
  5275. \end{lstlisting}
  5276. \fi}
  5277. {\if\edition\pythonEd
  5278. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5279. \begin{lstlisting}
  5280. .globl main
  5281. main:
  5282. pushq %rbp
  5283. movq %rsp, %rbp
  5284. pushq %rbx
  5285. subq $8, %rsp
  5286. movq $1, %rcx
  5287. movq $42, %rbx
  5288. addq $7, %rcx
  5289. movq %rcx, -16(%rbp)
  5290. addq %rbx, -16(%rbp)
  5291. negq %rcx
  5292. movq -16(%rbp), %rbx
  5293. addq %rcx, %rbx
  5294. movq %rbx, %rdi
  5295. callq print_int
  5296. addq $8, %rsp
  5297. popq %rbx
  5298. popq %rbp
  5299. retq
  5300. \end{lstlisting}
  5301. \fi}
  5302. \caption{The x86 output from the running example
  5303. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5304. and \code{rcx}.}
  5305. \label{fig:running-example-x86}
  5306. \end{figure}
  5307. \begin{exercise}\normalfont
  5308. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5309. %
  5310. \racket{
  5311. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5312. list of passes and the call to \code{compiler-tests}.}
  5313. %
  5314. Run the script to test the complete compiler for \LangVar{} that
  5315. performs register allocation.
  5316. \end{exercise}
  5317. \section{Challenge: Move Biasing}
  5318. \label{sec:move-biasing}
  5319. \index{subject}{move biasing}
  5320. This section describes an enhancement to the register allocator,
  5321. called move biasing, for students who are looking for an extra
  5322. challenge.
  5323. {\if\edition\racketEd
  5324. To motivate the need for move biasing we return to the running example
  5325. but this time use all of the general purpose registers. So we have
  5326. the following mapping of color numbers to registers.
  5327. \[
  5328. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  5329. \]
  5330. Using the same assignment of variables to color numbers that was
  5331. produced by the register allocator described in the last section, we
  5332. get the following program.
  5333. \begin{center}
  5334. \begin{minipage}{0.3\textwidth}
  5335. \begin{lstlisting}
  5336. movq $1, v
  5337. movq $42, w
  5338. movq v, x
  5339. addq $7, x
  5340. movq x, y
  5341. movq x, z
  5342. addq w, z
  5343. movq y, t
  5344. negq t
  5345. movq z, %rax
  5346. addq t, %rax
  5347. jmp conclusion
  5348. \end{lstlisting}
  5349. \end{minipage}
  5350. $\Rightarrow\qquad$
  5351. \begin{minipage}{0.45\textwidth}
  5352. \begin{lstlisting}
  5353. movq $1, %rdx
  5354. movq $42, %rcx
  5355. movq %rdx, %rdx
  5356. addq $7, %rdx
  5357. movq %rdx, %rsi
  5358. movq %rdx, %rdx
  5359. addq %rcx, %rdx
  5360. movq %rsi, %rcx
  5361. negq %rcx
  5362. movq %rdx, %rax
  5363. addq %rcx, %rax
  5364. jmp conclusion
  5365. \end{lstlisting}
  5366. \end{minipage}
  5367. \end{center}
  5368. In the above output code there are two \key{movq} instructions that
  5369. can be removed because their source and target are the same. However,
  5370. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5371. register, we could instead remove three \key{movq} instructions. We
  5372. can accomplish this by taking into account which variables appear in
  5373. \key{movq} instructions with which other variables.
  5374. \fi}
  5375. {\if\edition\pythonEd
  5376. %
  5377. To motivate the need for move biasing we return to the running example
  5378. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5379. remove three trivial move instructions from the running
  5380. example. However, we could remove another trivial move if we were able
  5381. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5382. We say that two variables $p$ and $q$ are \emph{move
  5383. related}\index{subject}{move related} if they participate together in
  5384. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5385. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5386. when there are multiple variables with the same saturation, prefer
  5387. variables that can be assigned to a color that is the same as the
  5388. color of a move related variable. Furthermore, when the register
  5389. allocator chooses a color for a variable, it should prefer a color
  5390. that has already been used for a move-related variable (assuming that
  5391. they do not interfere). Of course, this preference should not override
  5392. the preference for registers over stack locations. So this preference
  5393. should be used as a tie breaker when choosing between registers or
  5394. when choosing between stack locations.
  5395. We recommend representing the move relationships in a graph, similar
  5396. to how we represented interference. The following is the \emph{move
  5397. graph} for our running example.
  5398. {\if\edition\racketEd
  5399. \[
  5400. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5401. \node (rax) at (0,0) {$\ttm{rax}$};
  5402. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5403. \node (t) at (0,2) {$\ttm{t}$};
  5404. \node (z) at (3,2) {$\ttm{z}$};
  5405. \node (x) at (6,2) {$\ttm{x}$};
  5406. \node (y) at (3,0) {$\ttm{y}$};
  5407. \node (w) at (6,0) {$\ttm{w}$};
  5408. \node (v) at (9,0) {$\ttm{v}$};
  5409. \draw (v) to (x);
  5410. \draw (x) to (y);
  5411. \draw (x) to (z);
  5412. \draw (y) to (t);
  5413. \end{tikzpicture}
  5414. \]
  5415. \fi}
  5416. %
  5417. {\if\edition\pythonEd
  5418. \[
  5419. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5420. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5421. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5422. \node (z) at (3,2) {$\ttm{z}$};
  5423. \node (x) at (6,2) {$\ttm{x}$};
  5424. \node (y) at (3,0) {$\ttm{y}$};
  5425. \node (w) at (6,0) {$\ttm{w}$};
  5426. \node (v) at (9,0) {$\ttm{v}$};
  5427. \draw (y) to (t0);
  5428. \draw (z) to (x);
  5429. \draw (z) to (t1);
  5430. \draw (x) to (y);
  5431. \draw (x) to (v);
  5432. \end{tikzpicture}
  5433. \]
  5434. \fi}
  5435. {\if\edition\racketEd
  5436. Now we replay the graph coloring, pausing to see the coloring of
  5437. \code{y}. Recall the following configuration. The most saturated vertices
  5438. were \code{w} and \code{y}.
  5439. \[
  5440. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5441. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5442. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5443. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5444. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5445. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5446. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5447. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5448. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5449. \draw (t1) to (rax);
  5450. \draw (t1) to (z);
  5451. \draw (z) to (y);
  5452. \draw (z) to (w);
  5453. \draw (x) to (w);
  5454. \draw (y) to (w);
  5455. \draw (v) to (w);
  5456. \draw (v) to (rsp);
  5457. \draw (w) to (rsp);
  5458. \draw (x) to (rsp);
  5459. \draw (y) to (rsp);
  5460. \path[-.,bend left=15] (z) edge node {} (rsp);
  5461. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5462. \draw (rax) to (rsp);
  5463. \end{tikzpicture}
  5464. \]
  5465. %
  5466. Last time we chose to color \code{w} with $0$. But this time we see
  5467. that \code{w} is not move related to any vertex, but \code{y} is move
  5468. related to \code{t}. So we choose to color \code{y} the same color as
  5469. \code{t}, $0$.
  5470. \[
  5471. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5472. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5473. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5474. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5475. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5476. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5477. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5478. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5479. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5480. \draw (t1) to (rax);
  5481. \draw (t1) to (z);
  5482. \draw (z) to (y);
  5483. \draw (z) to (w);
  5484. \draw (x) to (w);
  5485. \draw (y) to (w);
  5486. \draw (v) to (w);
  5487. \draw (v) to (rsp);
  5488. \draw (w) to (rsp);
  5489. \draw (x) to (rsp);
  5490. \draw (y) to (rsp);
  5491. \path[-.,bend left=15] (z) edge node {} (rsp);
  5492. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5493. \draw (rax) to (rsp);
  5494. \end{tikzpicture}
  5495. \]
  5496. Now \code{w} is the most saturated, so we color it $2$.
  5497. \[
  5498. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5499. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5500. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5501. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5502. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5503. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5504. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5505. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5506. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5507. \draw (t1) to (rax);
  5508. \draw (t1) to (z);
  5509. \draw (z) to (y);
  5510. \draw (z) to (w);
  5511. \draw (x) to (w);
  5512. \draw (y) to (w);
  5513. \draw (v) to (w);
  5514. \draw (v) to (rsp);
  5515. \draw (w) to (rsp);
  5516. \draw (x) to (rsp);
  5517. \draw (y) to (rsp);
  5518. \path[-.,bend left=15] (z) edge node {} (rsp);
  5519. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5520. \draw (rax) to (rsp);
  5521. \end{tikzpicture}
  5522. \]
  5523. At this point, vertices \code{x} and \code{v} are most saturated, but
  5524. \code{x} is move related to \code{y} and \code{z}, so we color
  5525. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5526. \[
  5527. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5528. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5529. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5530. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5531. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5532. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5533. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5534. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5535. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5536. \draw (t1) to (rax);
  5537. \draw (t) to (z);
  5538. \draw (z) to (y);
  5539. \draw (z) to (w);
  5540. \draw (x) to (w);
  5541. \draw (y) to (w);
  5542. \draw (v) to (w);
  5543. \draw (v) to (rsp);
  5544. \draw (w) to (rsp);
  5545. \draw (x) to (rsp);
  5546. \draw (y) to (rsp);
  5547. \path[-.,bend left=15] (z) edge node {} (rsp);
  5548. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5549. \draw (rax) to (rsp);
  5550. \end{tikzpicture}
  5551. \]
  5552. \fi}
  5553. %
  5554. {\if\edition\pythonEd
  5555. Now we replay the graph coloring, pausing before the coloring of
  5556. \code{w}. Recall the following configuration. The most saturated vertices
  5557. were \code{tmp\_1}, \code{w}, and \code{y}.
  5558. \[
  5559. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5560. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5561. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5562. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5563. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5564. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5565. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5566. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5567. \draw (t0) to (t1);
  5568. \draw (t0) to (z);
  5569. \draw (z) to (y);
  5570. \draw (z) to (w);
  5571. \draw (x) to (w);
  5572. \draw (y) to (w);
  5573. \draw (v) to (w);
  5574. \end{tikzpicture}
  5575. \]
  5576. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5577. or \code{y}, but note that \code{w} is not move related to any
  5578. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5579. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5580. \code{y} and color it $0$, we can delete another move instruction.
  5581. \[
  5582. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5583. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5584. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5585. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5586. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5587. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5588. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5589. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5590. \draw (t0) to (t1);
  5591. \draw (t0) to (z);
  5592. \draw (z) to (y);
  5593. \draw (z) to (w);
  5594. \draw (x) to (w);
  5595. \draw (y) to (w);
  5596. \draw (v) to (w);
  5597. \end{tikzpicture}
  5598. \]
  5599. Now \code{w} is the most saturated, so we color it $2$.
  5600. \[
  5601. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5602. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5603. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5604. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5605. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5606. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5607. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5608. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5609. \draw (t0) to (t1);
  5610. \draw (t0) to (z);
  5611. \draw (z) to (y);
  5612. \draw (z) to (w);
  5613. \draw (x) to (w);
  5614. \draw (y) to (w);
  5615. \draw (v) to (w);
  5616. \end{tikzpicture}
  5617. \]
  5618. To finish the coloring, \code{x} and \code{v} get $0$ and
  5619. \code{tmp\_1} gets $1$.
  5620. \[
  5621. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5622. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5623. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5624. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5625. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5626. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5627. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5628. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5629. \draw (t0) to (t1);
  5630. \draw (t0) to (z);
  5631. \draw (z) to (y);
  5632. \draw (z) to (w);
  5633. \draw (x) to (w);
  5634. \draw (y) to (w);
  5635. \draw (v) to (w);
  5636. \end{tikzpicture}
  5637. \]
  5638. \fi}
  5639. So we have the following assignment of variables to registers.
  5640. {\if\edition\racketEd
  5641. \begin{gather*}
  5642. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5643. \ttm{w} \mapsto \key{\%rsi}, \,
  5644. \ttm{x} \mapsto \key{\%rcx}, \,
  5645. \ttm{y} \mapsto \key{\%rcx}, \,
  5646. \ttm{z} \mapsto \key{\%rdx}, \,
  5647. \ttm{t} \mapsto \key{\%rcx} \}
  5648. \end{gather*}
  5649. \fi}
  5650. {\if\edition\pythonEd
  5651. \begin{gather*}
  5652. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5653. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5654. \ttm{x} \mapsto \key{\%rcx}, \,
  5655. \ttm{y} \mapsto \key{\%rcx}, \\
  5656. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5657. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5658. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5659. \end{gather*}
  5660. \fi}
  5661. We apply this register assignment to the running example, on the left,
  5662. to obtain the code in the middle. The \code{patch\_instructions} then
  5663. deletes the trivial moves to obtain the code on the right.
  5664. {\if\edition\racketEd
  5665. \begin{minipage}{0.25\textwidth}
  5666. \begin{lstlisting}
  5667. movq $1, v
  5668. movq $42, w
  5669. movq v, x
  5670. addq $7, x
  5671. movq x, y
  5672. movq x, z
  5673. addq w, z
  5674. movq y, t
  5675. negq t
  5676. movq z, %rax
  5677. addq t, %rax
  5678. jmp conclusion
  5679. \end{lstlisting}
  5680. \end{minipage}
  5681. $\Rightarrow\qquad$
  5682. \begin{minipage}{0.25\textwidth}
  5683. \begin{lstlisting}
  5684. movq $1, %rcx
  5685. movq $42, %rsi
  5686. movq %rcx, %rcx
  5687. addq $7, %rcx
  5688. movq %rcx, %rcx
  5689. movq %rcx, %rdx
  5690. addq %rsi, %rdx
  5691. movq %rcx, %rcx
  5692. negq %rcx
  5693. movq %rdx, %rax
  5694. addq %rcx, %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. addq $7, %rcx
  5704. movq %rcx, %rdx
  5705. addq %rsi, %rdx
  5706. negq %rcx
  5707. movq %rdx, %rax
  5708. addq %rcx, %rax
  5709. jmp conclusion
  5710. \end{lstlisting}
  5711. \end{minipage}
  5712. \fi}
  5713. {\if\edition\pythonEd
  5714. \begin{minipage}{0.20\textwidth}
  5715. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5716. movq $1, v
  5717. movq $42, w
  5718. movq v, x
  5719. addq $7, x
  5720. movq x, y
  5721. movq x, z
  5722. addq w, z
  5723. movq y, tmp_0
  5724. negq tmp_0
  5725. movq z, tmp_1
  5726. addq tmp_0, tmp_1
  5727. movq tmp_1, %rdi
  5728. callq _print_int
  5729. \end{lstlisting}
  5730. \end{minipage}
  5731. ${\Rightarrow\qquad}$
  5732. \begin{minipage}{0.30\textwidth}
  5733. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5734. movq $1, %rcx
  5735. movq $42, -16(%rbp)
  5736. movq %rcx, %rcx
  5737. addq $7, %rcx
  5738. movq %rcx, %rcx
  5739. movq %rcx, -8(%rbp)
  5740. addq -16(%rbp), -8(%rbp)
  5741. movq %rcx, %rcx
  5742. negq %rcx
  5743. movq -8(%rbp), -8(%rbp)
  5744. addq %rcx, -8(%rbp)
  5745. movq -8(%rbp), %rdi
  5746. callq _print_int
  5747. \end{lstlisting}
  5748. \end{minipage}
  5749. ${\Rightarrow\qquad}$
  5750. \begin{minipage}{0.20\textwidth}
  5751. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5752. movq $1, %rcx
  5753. movq $42, -16(%rbp)
  5754. addq $7, %rcx
  5755. movq %rcx, -8(%rbp)
  5756. movq -16(%rbp), %rax
  5757. addq %rax, -8(%rbp)
  5758. negq %rcx
  5759. addq %rcx, -8(%rbp)
  5760. movq -8(%rbp), %rdi
  5761. callq print_int
  5762. \end{lstlisting}
  5763. \end{minipage}
  5764. \fi}
  5765. \begin{exercise}\normalfont
  5766. Change your implementation of \code{allocate\_registers} to take move
  5767. biasing into account. Create two new tests that include at least one
  5768. opportunity for move biasing and visually inspect the output x86
  5769. programs to make sure that your move biasing is working properly. Make
  5770. sure that your compiler still passes all of the tests.
  5771. \end{exercise}
  5772. %To do: another neat challenge would be to do
  5773. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5774. %% \subsection{Output of the Running Example}
  5775. %% \label{sec:reg-alloc-output}
  5776. % challenge: prioritize variables based on execution frequencies
  5777. % and the number of uses of a variable
  5778. % challenge: enhance the coloring algorithm using Chaitin's
  5779. % approach of prioritizing high-degree variables
  5780. % by removing low-degree variables (coloring them later)
  5781. % from the interference graph
  5782. \section{Further Reading}
  5783. \label{sec:register-allocation-further-reading}
  5784. Early register allocation algorithms were developed for Fortran
  5785. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5786. of graph coloring began in the late 1970s and early 1980s with the
  5787. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5788. algorithm is based on the following observation of
  5789. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5790. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5791. $v$ removed is also $k$ colorable. To see why, suppose that the
  5792. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5793. different colors, but since there are less than $k$ neighbors, there
  5794. will be one or more colors left over to use for coloring $v$ in $G$.
  5795. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5796. less than $k$ from the graph and recursively colors the rest of the
  5797. graph. Upon returning from the recursion, it colors $v$ with one of
  5798. the available colors and returns. \citet{Chaitin:1982vn} augments
  5799. this algorithm to handle spilling as follows. If there are no vertices
  5800. of degree lower than $k$ then pick a vertex at random, spill it,
  5801. remove it from the graph, and proceed recursively to color the rest of
  5802. the graph.
  5803. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5804. move-related and that don't interfere with each other, a process
  5805. called \emph{coalescing}. While coalescing decreases the number of
  5806. moves, it can make the graph more difficult to
  5807. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5808. which two variables are merged only if they have fewer than $k$
  5809. neighbors of high degree. \citet{George:1996aa} observe that
  5810. conservative coalescing is sometimes too conservative and make it more
  5811. aggressive by iterating the coalescing with the removal of low-degree
  5812. vertices.
  5813. %
  5814. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5815. also propose \emph{biased coloring} in which a variable is assigned to
  5816. the same color as another move-related variable if possible, as
  5817. discussed in Section~\ref{sec:move-biasing}.
  5818. %
  5819. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5820. performs coalescing, graph coloring, and spill code insertion until
  5821. all variables have been assigned a location.
  5822. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5823. spills variables that don't have to be: a high-degree variable can be
  5824. colorable if many of its neighbors are assigned the same color.
  5825. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5826. high-degree vertex is not immediately spilled. Instead the decision is
  5827. deferred until after the recursive call, at which point it is apparent
  5828. whether there is actually an available color or not. We observe that
  5829. this algorithm is equivalent to the smallest-last ordering
  5830. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5831. be registers and the rest to be stack locations.
  5832. %% biased coloring
  5833. Earlier editions of the compiler course at Indiana University
  5834. \citep{Dybvig:2010aa} were based on the algorithm of
  5835. \citet{Briggs:1994kx}.
  5836. The smallest-last ordering algorithm is one of many \emph{greedy}
  5837. coloring algorithms. A greedy coloring algorithm visits all the
  5838. vertices in a particular order and assigns each one the first
  5839. available color. An \emph{offline} greedy algorithm chooses the
  5840. ordering up-front, prior to assigning colors. The algorithm of
  5841. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5842. ordering does not depend on the colors assigned. Other orderings are
  5843. possible. For example, \citet{Chow:1984ys} order variables according
  5844. to an estimate of runtime cost.
  5845. An \emph{online} greedy coloring algorithm uses information about the
  5846. current assignment of colors to influence the order in which the
  5847. remaining vertices are colored. The saturation-based algorithm
  5848. described in this chapter is one such algorithm. We choose to use
  5849. saturation-based coloring because it is fun to introduce graph
  5850. coloring via Sudoku!
  5851. A register allocator may choose to map each variable to just one
  5852. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5853. variable to one or more locations. The later can be achieved by
  5854. \emph{live range splitting}, where a variable is replaced by several
  5855. variables that each handle part of its live
  5856. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5857. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5858. %% replacement algorithm, bottom-up local
  5859. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5860. %% Cooper: top-down (priority bassed), bottom-up
  5861. %% top-down
  5862. %% order variables by priority (estimated cost)
  5863. %% caveat: split variables into two groups:
  5864. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5865. %% color the constrained ones first
  5866. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5867. %% cite J. Cocke for an algorithm that colors variables
  5868. %% in a high-degree first ordering
  5869. %Register Allocation via Usage Counts, Freiburghouse CACM
  5870. \citet{Palsberg:2007si} observe that many of the interference graphs
  5871. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5872. that is, every cycle with four or more edges has an edge which is not
  5873. part of the cycle but which connects two vertices on the cycle. Such
  5874. graphs can be optimally colored by the greedy algorithm with a vertex
  5875. ordering determined by maximum cardinality search.
  5876. In situations where compile time is of utmost importance, such as in
  5877. just-in-time compilers, graph coloring algorithms can be too expensive
  5878. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  5879. appropriate.
  5880. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5881. \chapter{Booleans and Conditionals}
  5882. \label{ch:Lif}
  5883. \index{subject}{Boolean}
  5884. \index{subject}{control flow}
  5885. \index{subject}{conditional expression}
  5886. The \LangInt{} and \LangVar{} languages only have a single kind of
  5887. value, the integers. In this chapter we add a second kind of value,
  5888. the Booleans, to create the \LangIf{} language. The Boolean values
  5889. \emph{true} and \emph{false} are written \TRUE{} and \FALSE{}
  5890. respectively in \racket{Racket}\python{Python}. The \LangIf{}
  5891. language includes several operations that involve Booleans (\key{and},
  5892. \key{not}, \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the
  5893. \key{if} expression \python{and statement}. With the addition of
  5894. \key{if}, programs can have non-trivial control flow which
  5895. %
  5896. \racket{impacts \code{explicate\_control} and liveness analysis}
  5897. %
  5898. \python{impacts liveness analysis and motivates a new pass named
  5899. \code{explicate\_control}}.
  5900. %
  5901. Also, because we now have two kinds of values, we need to handle
  5902. programs that apply an operation to the wrong kind of value, such as
  5903. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5904. There are two language design options for such situations. One option
  5905. is to signal an error and the other is to provide a wider
  5906. interpretation of the operation. \racket{The Racket
  5907. language}\python{Python} uses a mixture of these two options,
  5908. depending on the operation and the kind of value. For example, the
  5909. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  5910. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  5911. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  5912. %
  5913. \racket{On the other hand, \code{(car 1)} results in a run-time error
  5914. in Racket because \code{car} expects a pair.}
  5915. %
  5916. \python{On the other hand, \code{1[0]} results in a run-time error
  5917. in Python because an ``\code{int} object is not subscriptable''.}
  5918. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  5919. design choices as \racket{Racket}\python{Python}, except much of the
  5920. error detection happens at compile time instead of run
  5921. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  5922. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  5923. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  5924. Racket}\python{MyPy} reports a compile-time error
  5925. %
  5926. \racket{because Racket expects the type of the argument to be of the form
  5927. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  5928. %
  5929. \python{stating that a ``value of type \code{int} is not indexable''.}
  5930. The \LangIf{} language performs type checking during compilation like
  5931. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Rdyn} we study the
  5932. alternative choice, that is, a dynamically typed language like
  5933. \racket{Racket}\python{Python}.
  5934. The \LangIf{} language is a subset of \racket{Typed Racket}\python{MyPy};
  5935. for some operations we are more restrictive, for example, rejecting
  5936. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5937. This chapter is organized as follows. We begin by defining the syntax
  5938. and interpreter for the \LangIf{} language
  5939. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  5940. checking and define a type checker for \LangIf{}
  5941. (Section~\ref{sec:type-check-Lif}).
  5942. %
  5943. \racket{To compile \LangIf{} we need to enlarge the intermediate
  5944. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  5945. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  5946. %
  5947. The remaining sections of this chapter discuss how the addition of
  5948. Booleans and conditional control flow to the language requires changes
  5949. to the existing compiler passes and the addition of new ones. In
  5950. particular, we introduce the \code{shrink} pass to translates some
  5951. operators into others, thereby reducing the number of operators that
  5952. need to be handled in later passes.
  5953. %
  5954. The main event of this chapter is the \code{explicate\_control} pass
  5955. that is responsible for translating \code{if}'s into conditional
  5956. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  5957. %
  5958. Regarding register allocation, there is the interesting question of
  5959. how to handle conditional \code{goto}'s during liveness analysis.
  5960. \section{The \LangIf{} Language}
  5961. \label{sec:lang-if}
  5962. The concrete syntax of the \LangIf{} language is defined in
  5963. Figure~\ref{fig:Lif-concrete-syntax} and the abstract syntax is defined
  5964. in Figure~\ref{fig:Lif-syntax}. The \LangIf{} language includes all of
  5965. \LangVar{}\racket{(shown in gray)}, the Boolean literals \TRUE{} and
  5966. \FALSE{}, and the \code{if} expression \python{and statement}. We expand the
  5967. operators to include
  5968. \begin{enumerate}
  5969. \item subtraction on integers,
  5970. \item the logical operators \key{and}, \key{or}, and \key{not},
  5971. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  5972. for comparing integers or Booleans for equality, and
  5973. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  5974. comparing integers.
  5975. \end{enumerate}
  5976. \racket{We reorganize the abstract syntax for the primitive
  5977. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  5978. rule for all of them. This means that the grammar no longer checks
  5979. whether the arity of an operators matches the number of
  5980. arguments. That responsibility is moved to the type checker for
  5981. \LangIf{}, which we introduce in Section~\ref{sec:type-check-Lif}.}
  5982. \newcommand{\LifGrammarRacket}{
  5983. \begin{array}{lcl}
  5984. \Type &::=& \key{Boolean} \\
  5985. \itm{bool} &::=& \TRUE \MID \FALSE \\
  5986. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5987. \Exp &::=& \CSUB{\Exp}{\Exp} \MID \itm{bool}
  5988. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  5989. \MID (\key{not}\;\Exp) \\
  5990. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  5991. \end{array}
  5992. }
  5993. \newcommand{\LifASTRacket}{
  5994. \begin{array}{lcl}
  5995. \Type &::=& \key{Boolean} \\
  5996. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  5997. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  5998. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  5999. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6000. \end{array}
  6001. }
  6002. \newcommand{\LintOpAST}{
  6003. \begin{array}{rcl}
  6004. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6005. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6006. \end{array}
  6007. }
  6008. \newcommand{\LifGrammarPython}{
  6009. \begin{array}{rcl}
  6010. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6011. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6012. \MID \key{not}~\Exp \\
  6013. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6014. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6015. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6016. \end{array}
  6017. }
  6018. \newcommand{\LifASTPython}{
  6019. \begin{array}{lcl}
  6020. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6021. \itm{unaryop} &::=& \code{Not()} \\
  6022. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6023. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6024. \Exp &::=& \BOOL{\itm{bool}}
  6025. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6026. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6027. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6028. \end{array}
  6029. }
  6030. \begin{figure}[tp]
  6031. \centering
  6032. \fbox{
  6033. \begin{minipage}{0.96\textwidth}
  6034. {\if\edition\racketEd
  6035. \[
  6036. \begin{array}{l}
  6037. \gray{\LintGrammarRacket{}} \\ \hline
  6038. \gray{\LvarGrammarRacket{}} \\ \hline
  6039. \LifGrammarRacket{} \\
  6040. \begin{array}{lcl}
  6041. \LangIfM{} &::=& \Exp
  6042. \end{array}
  6043. \end{array}
  6044. \]
  6045. \fi}
  6046. {\if\edition\pythonEd
  6047. \[
  6048. \begin{array}{l}
  6049. \gray{\LintGrammarPython} \\ \hline
  6050. \gray{\LvarGrammarPython} \\ \hline
  6051. \LifGrammarPython \\
  6052. \begin{array}{rcl}
  6053. \LangIfM{} &::=& \Stmt^{*}
  6054. \end{array}
  6055. \end{array}
  6056. \]
  6057. \fi}
  6058. \end{minipage}
  6059. }
  6060. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6061. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6062. \label{fig:Lif-concrete-syntax}
  6063. \end{figure}
  6064. \begin{figure}[tp]
  6065. \centering
  6066. \fbox{
  6067. \begin{minipage}{0.96\textwidth}
  6068. {\if\edition\racketEd
  6069. \[
  6070. \begin{array}{l}
  6071. \gray{\LintOpAST} \\ \hline
  6072. \gray{\LvarASTRacket{}} \\ \hline
  6073. \LifASTRacket{} \\
  6074. \begin{array}{lcl}
  6075. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6076. \end{array}
  6077. \end{array}
  6078. \]
  6079. \fi}
  6080. {\if\edition\pythonEd
  6081. \[
  6082. \begin{array}{l}
  6083. \gray{\LintASTPython} \\ \hline
  6084. \gray{\LvarASTPython} \\ \hline
  6085. \LifASTPython \\
  6086. \begin{array}{lcl}
  6087. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6088. \end{array}
  6089. \end{array}
  6090. \]
  6091. \fi}
  6092. \end{minipage}
  6093. }
  6094. \caption{The abstract syntax of \LangIf{}.}
  6095. \label{fig:Lif-syntax}
  6096. \end{figure}
  6097. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  6098. which inherits from the interpreter for \LangVar{}
  6099. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6100. evaluate to the corresponding Boolean values. The conditional
  6101. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  6102. and then either evaluates $e_2$ or $e_3$ depending on whether
  6103. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  6104. \code{and}, \code{or}, and \code{not} behave according to propositional logic,
  6105. but note that the \code{and} and \code{or} operations are
  6106. short-circuiting.
  6107. %
  6108. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6109. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6110. %
  6111. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6112. evaluated if $e_1$ evaluates to \TRUE{}.
  6113. \racket{With the increase in the number of primitive operations, the
  6114. interpreter would become repetitive without some care. We refactor
  6115. the case for \code{Prim}, moving the code that differs with each
  6116. operation into the \code{interp\_op} method shown in in
  6117. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6118. \code{or} operations separately because of their short-circuiting
  6119. behavior.}
  6120. \begin{figure}[tbp]
  6121. {\if\edition\racketEd
  6122. \begin{lstlisting}
  6123. (define interp_Lif_class
  6124. (class interp_Lvar_class
  6125. (super-new)
  6126. (define/public (interp_op op) ...)
  6127. (define/override ((interp_exp env) e)
  6128. (define recur (interp_exp env))
  6129. (match e
  6130. [(Bool b) b]
  6131. [(If cnd thn els)
  6132. (match (recur cnd)
  6133. [#t (recur thn)]
  6134. [#f (recur els)])]
  6135. [(Prim 'and (list e1 e2))
  6136. (match (recur e1)
  6137. [#t (match (recur e2) [#t #t] [#f #f])]
  6138. [#f #f])]
  6139. [(Prim 'or (list e1 e2))
  6140. (define v1 (recur e1))
  6141. (match v1
  6142. [#t #t]
  6143. [#f (match (recur e2) [#t #t] [#f #f])])]
  6144. [(Prim op args)
  6145. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6146. [else ((super interp_exp env) e)]))
  6147. ))
  6148. (define (interp_Lif p)
  6149. (send (new interp_Lif_class) interp_program p))
  6150. \end{lstlisting}
  6151. \fi}
  6152. {\if\edition\pythonEd
  6153. \begin{lstlisting}
  6154. class InterpLif(InterpLvar):
  6155. def interp_exp(self, e, env):
  6156. match e:
  6157. case IfExp(test, body, orelse):
  6158. if self.interp_exp(test, env):
  6159. return self.interp_exp(body, env)
  6160. else:
  6161. return self.interp_exp(orelse, env)
  6162. case BinOp(left, Sub(), right):
  6163. return self.interp_exp(left, env) - self.interp_exp(right, env)
  6164. case UnaryOp(Not(), v):
  6165. return not self.interp_exp(v, env)
  6166. case BoolOp(And(), values):
  6167. if self.interp_exp(values[0], env):
  6168. return self.interp_exp(values[1], env)
  6169. else:
  6170. return False
  6171. case BoolOp(Or(), values):
  6172. if self.interp_exp(values[0], env):
  6173. return True
  6174. else:
  6175. return self.interp_exp(values[1], env)
  6176. case Compare(left, [cmp], [right]):
  6177. l = self.interp_exp(left, env)
  6178. r = self.interp_exp(right, env)
  6179. return self.interp_cmp(cmp)(l, r)
  6180. case _:
  6181. return super().interp_exp(e, env)
  6182. def interp_stmts(self, ss, env):
  6183. if len(ss) == 0:
  6184. return
  6185. match ss[0]:
  6186. case If(test, body, orelse):
  6187. if self.interp_exp(test, env):
  6188. return self.interp_stmts(body + ss[1:], env)
  6189. else:
  6190. return self.interp_stmts(orelse + ss[1:], env)
  6191. case _:
  6192. return super().interp_stmts(ss, env)
  6193. ...
  6194. \end{lstlisting}
  6195. \fi}
  6196. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6197. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6198. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6199. \label{fig:interp-Lif}
  6200. \end{figure}
  6201. {\if\edition\racketEd
  6202. \begin{figure}[tbp]
  6203. \begin{lstlisting}
  6204. (define/public (interp_op op)
  6205. (match op
  6206. ['+ fx+]
  6207. ['- fx-]
  6208. ['read read-fixnum]
  6209. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6210. ['eq? (lambda (v1 v2)
  6211. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6212. (and (boolean? v1) (boolean? v2))
  6213. (and (vector? v1) (vector? v2)))
  6214. (eq? v1 v2)]))]
  6215. ['< (lambda (v1 v2)
  6216. (cond [(and (fixnum? v1) (fixnum? v2))
  6217. (< v1 v2)]))]
  6218. ['<= (lambda (v1 v2)
  6219. (cond [(and (fixnum? v1) (fixnum? v2))
  6220. (<= v1 v2)]))]
  6221. ['> (lambda (v1 v2)
  6222. (cond [(and (fixnum? v1) (fixnum? v2))
  6223. (> v1 v2)]))]
  6224. ['>= (lambda (v1 v2)
  6225. (cond [(and (fixnum? v1) (fixnum? v2))
  6226. (>= v1 v2)]))]
  6227. [else (error 'interp_op "unknown operator")]))
  6228. \end{lstlisting}
  6229. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6230. \label{fig:interp-op-Lif}
  6231. \end{figure}
  6232. \fi}
  6233. {\if\edition\pythonEd
  6234. \begin{figure}
  6235. \begin{lstlisting}
  6236. class InterpLif(InterpLvar):
  6237. ...
  6238. def interp_cmp(self, cmp):
  6239. match cmp:
  6240. case Lt():
  6241. return lambda x, y: x < y
  6242. case LtE():
  6243. return lambda x, y: x <= y
  6244. case Gt():
  6245. return lambda x, y: x > y
  6246. case GtE():
  6247. return lambda x, y: x >= y
  6248. case Eq():
  6249. return lambda x, y: x == y
  6250. case NotEq():
  6251. return lambda x, y: x != y
  6252. \end{lstlisting}
  6253. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6254. \label{fig:interp-cmp-Lif}
  6255. \end{figure}
  6256. \fi}
  6257. \section{Type Checking \LangIf{} Programs}
  6258. \label{sec:type-check-Lif}
  6259. \index{subject}{type checking}
  6260. \index{subject}{semantic analysis}
  6261. It is helpful to think about type checking in two complementary
  6262. ways. A type checker predicts the type of value that will be produced
  6263. by each expression in the program. For \LangIf{}, we have just two types,
  6264. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6265. {\if\edition\racketEd
  6266. \begin{lstlisting}
  6267. (+ 10 (- (+ 12 20)))
  6268. \end{lstlisting}
  6269. \fi}
  6270. {\if\edition\pythonEd
  6271. \begin{lstlisting}
  6272. 10 + -(12 + 20)
  6273. \end{lstlisting}
  6274. \fi}
  6275. \noindent produces a value of type \INTTY{} while
  6276. {\if\edition\racketEd
  6277. \begin{lstlisting}
  6278. (and (not #f) #t)
  6279. \end{lstlisting}
  6280. \fi}
  6281. {\if\edition\pythonEd
  6282. \begin{lstlisting}
  6283. (not False) and True
  6284. \end{lstlisting}
  6285. \fi}
  6286. \noindent produces a value of type \BOOLTY{}.
  6287. A second way to think about type checking is that it enforces a set of
  6288. rules about which operators can be applied to which kinds of
  6289. values. For example, our type checker for \LangIf{} signals an error
  6290. for the below expression {\if\edition\racketEd
  6291. \begin{lstlisting}
  6292. (not (+ 10 (- (+ 12 20))))
  6293. \end{lstlisting}
  6294. \fi}
  6295. {\if\edition\pythonEd
  6296. \begin{lstlisting}
  6297. not (10 + -(12 + 20))
  6298. \end{lstlisting}
  6299. \fi}
  6300. The subexpression
  6301. \racket{\code{(+ 10 (- (+ 12 20)))}}\python{\code{(10 + -(12 + 20))}}
  6302. has type \INTTY{} but the type checker enforces the rule that the argument of
  6303. \code{not} must be an expression of type \BOOLTY{}.
  6304. We implement type checking using classes and methods because they
  6305. provide the open recursion needed to reuse code as we extend the type
  6306. checker in later chapters, analogous to the use of classes and methods
  6307. for the interpreters (Section~\ref{sec:extensible-interp}).
  6308. We separate the type checker for the \LangVar{} subset into its own
  6309. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6310. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6311. from the type checker for \LangVar{}. These type checkers are in the
  6312. files
  6313. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6314. and
  6315. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6316. of the support code.
  6317. %
  6318. Each type checker is a structurally recursive function over the AST.
  6319. Given an input expression \code{e}, the type checker either signals an
  6320. error or returns \racket{an expression and} its type (\INTTY{} or
  6321. \BOOLTY{}).
  6322. %
  6323. \racket{It returns an expression because there are situations in which
  6324. we want to change or update the expression.}
  6325. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6326. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6327. \INTTY{}. To handle variables, the type checker uses the environment
  6328. \code{env} to map variables to types.
  6329. %
  6330. \racket{Consider the case for \key{let}. We type check the
  6331. initializing expression to obtain its type \key{T} and then
  6332. associate type \code{T} with the variable \code{x} in the
  6333. environment used to type check the body of the \key{let}. Thus,
  6334. when the type checker encounters a use of variable \code{x}, it can
  6335. find its type in the environment.}
  6336. %
  6337. \python{Consider the case for assignment. We type check the
  6338. initializing expression to obtain its type \key{t}. If the variable
  6339. \code{lhs.id} is already in the environment because there was a
  6340. prior assignment, we check that this initializer has the same type
  6341. as the prior one. If this is the first assignment to the variable,
  6342. we associate type \code{t} with the variable \code{lhs.id} in the
  6343. environment. Thus, when the type checker encounters a use of
  6344. variable \code{x}, it can find its type in the environment.}
  6345. %
  6346. \racket{Regarding primitive operators, we recursively analyze the
  6347. arguments and then invoke \code{type\_check\_op} to check whether
  6348. the argument types are allowed.}
  6349. %
  6350. \python{Regarding addition and negation, we recursively analyze the
  6351. arguments, check that they have type \INT{}, and return \INT{}.}
  6352. \racket{Several auxiliary methods are used in the type checker. The
  6353. method \code{operator-types} defines a dictionary that maps the
  6354. operator names to their parameter and return types. The
  6355. \code{type-equal?} method determines whether two types are equal,
  6356. which for now simply dispatches to \code{equal?} (deep
  6357. equality). The \code{check-type-equal?} method triggers an error if
  6358. the two types are not equal. The \code{type-check-op} method looks
  6359. up the operator in the \code{operator-types} dictionary and then
  6360. checks whether the argument types are equal to the parameter types.
  6361. The result is the return type of the operator.}
  6362. %
  6363. \python{The auxiliary method \code{check\_type\_equal} method triggers
  6364. an error if the two types are not equal.}
  6365. \begin{figure}[tbp]
  6366. {\if\edition\racketEd
  6367. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6368. (define type-check-Lvar_class
  6369. (class object%
  6370. (super-new)
  6371. (define/public (operator-types)
  6372. '((+ . ((Integer Integer) . Integer))
  6373. (- . ((Integer) . Integer))
  6374. (read . (() . Integer))))
  6375. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6376. (define/public (check-type-equal? t1 t2 e)
  6377. (unless (type-equal? t1 t2)
  6378. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6379. (define/public (type-check-op op arg-types e)
  6380. (match (dict-ref (operator-types) op)
  6381. [`(,param-types . ,return-type)
  6382. (for ([at arg-types] [pt param-types])
  6383. (check-type-equal? at pt e))
  6384. return-type]
  6385. [else (error 'type-check-op "unrecognized ~a" op)]))
  6386. (define/public (type-check-exp env)
  6387. (lambda (e)
  6388. (match e
  6389. [(Int n) (values (Int n) 'Integer)]
  6390. [(Var x) (values (Var x) (dict-ref env x))]
  6391. [(Let x e body)
  6392. (define-values (e^ Te) ((type-check-exp env) e))
  6393. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6394. (values (Let x e^ b) Tb)]
  6395. [(Prim op es)
  6396. (define-values (new-es ts)
  6397. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6398. (values (Prim op new-es) (type-check-op op ts e))]
  6399. [else (error 'type-check-exp "couldn't match" e)])))
  6400. (define/public (type-check-program e)
  6401. (match e
  6402. [(Program info body)
  6403. (define-values (body^ Tb) ((type-check-exp '()) body))
  6404. (check-type-equal? Tb 'Integer body)
  6405. (Program info body^)]
  6406. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6407. ))
  6408. (define (type-check-Lvar p)
  6409. (send (new type-check-Lvar_class) type-check-program p))
  6410. \end{lstlisting}
  6411. \fi}
  6412. {\if\edition\pythonEd
  6413. \begin{lstlisting}
  6414. class TypeCheckLvar:
  6415. def check_type_equal(self, t1, t2, e):
  6416. if t1 != t2:
  6417. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6418. raise Exception(msg)
  6419. def type_check_exp(self, e, env):
  6420. match e:
  6421. case BinOp(left, Add(), right):
  6422. l = self.type_check_exp(left, env)
  6423. check_type_equal(l, int, left)
  6424. r = self.type_check_exp(right, env)
  6425. check_type_equal(r, int, right)
  6426. return int
  6427. case UnaryOp(USub(), v):
  6428. t = self.type_check_exp(v, env)
  6429. check_type_equal(t, int, v)
  6430. return int
  6431. case Name(id):
  6432. return env[id]
  6433. case Constant(value) if isinstance(value, int):
  6434. return int
  6435. case Call(Name('input_int'), []):
  6436. return int
  6437. def type_check_stmts(self, ss, env):
  6438. if len(ss) == 0:
  6439. return
  6440. match ss[0]:
  6441. case Assign([lhs], value):
  6442. t = self.type_check_exp(value, env)
  6443. if lhs.id in env:
  6444. check_type_equal(env[lhs.id], t, value)
  6445. else:
  6446. env[lhs.id] = t
  6447. return self.type_check_stmts(ss[1:], env)
  6448. case Expr(Call(Name('print'), [arg])):
  6449. t = self.type_check_exp(arg, env)
  6450. check_type_equal(t, int, arg)
  6451. return self.type_check_stmts(ss[1:], env)
  6452. case Expr(value):
  6453. self.type_check_exp(value, env)
  6454. return self.type_check_stmts(ss[1:], env)
  6455. def type_check_P(self, p):
  6456. match p:
  6457. case Module(body):
  6458. self.type_check_stmts(body, {})
  6459. \end{lstlisting}
  6460. \fi}
  6461. \caption{Type checker for the \LangVar{} language.}
  6462. \label{fig:type-check-Lvar}
  6463. \end{figure}
  6464. \begin{figure}[tbp]
  6465. {\if\edition\racketEd
  6466. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6467. (define type-check-Lif_class
  6468. (class type-check-Lvar_class
  6469. (super-new)
  6470. (inherit check-type-equal?)
  6471. (define/override (operator-types)
  6472. (append '((- . ((Integer Integer) . Integer))
  6473. (and . ((Boolean Boolean) . Boolean))
  6474. (or . ((Boolean Boolean) . Boolean))
  6475. (< . ((Integer Integer) . Boolean))
  6476. (<= . ((Integer Integer) . Boolean))
  6477. (> . ((Integer Integer) . Boolean))
  6478. (>= . ((Integer Integer) . Boolean))
  6479. (not . ((Boolean) . Boolean))
  6480. )
  6481. (super operator-types)))
  6482. (define/override (type-check-exp env)
  6483. (lambda (e)
  6484. (match e
  6485. [(Bool b) (values (Bool b) 'Boolean)]
  6486. [(Prim 'eq? (list e1 e2))
  6487. (define-values (e1^ T1) ((type-check-exp env) e1))
  6488. (define-values (e2^ T2) ((type-check-exp env) e2))
  6489. (check-type-equal? T1 T2 e)
  6490. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6491. [(If cnd thn els)
  6492. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6493. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6494. (define-values (els^ Te) ((type-check-exp env) els))
  6495. (check-type-equal? Tc 'Boolean e)
  6496. (check-type-equal? Tt Te e)
  6497. (values (If cnd^ thn^ els^) Te)]
  6498. [else ((super type-check-exp env) e)])))
  6499. ))
  6500. (define (type-check-Lif p)
  6501. (send (new type-check-Lif_class) type-check-program p))
  6502. \end{lstlisting}
  6503. \fi}
  6504. {\if\edition\pythonEd
  6505. \begin{lstlisting}
  6506. class TypeCheckLif(TypeCheckLvar):
  6507. def type_check_exp(self, e, env):
  6508. match e:
  6509. case Constant(value) if isinstance(value, bool):
  6510. return bool
  6511. case BinOp(left, Sub(), right):
  6512. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6513. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6514. return int
  6515. case UnaryOp(Not(), v):
  6516. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6517. return bool
  6518. case BoolOp(op, values):
  6519. left = values[0] ; right = values[1]
  6520. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6521. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6522. return bool
  6523. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6524. or isinstance(cmp, NotEq):
  6525. l = self.type_check_exp(left, env)
  6526. r = self.type_check_exp(right, env)
  6527. check_type_equal(l, r, e)
  6528. return bool
  6529. case Compare(left, [cmp], [right]):
  6530. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6531. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6532. return bool
  6533. case IfExp(test, body, orelse):
  6534. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6535. b = self.type_check_exp(body, env)
  6536. o = self.type_check_exp(orelse, env)
  6537. check_type_equal(b, o, e)
  6538. return b
  6539. case _:
  6540. return super().type_check_exp(e, env)
  6541. def type_check_stmts(self, ss, env):
  6542. if len(ss) == 0:
  6543. return
  6544. match ss[0]:
  6545. case If(test, body, orelse):
  6546. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6547. b = self.type_check_stmts(body, env)
  6548. o = self.type_check_stmts(orelse, env)
  6549. check_type_equal(b, o, ss[0])
  6550. return self.type_check_stmts(ss[1:], env)
  6551. case _:
  6552. return super().type_check_stmts(ss, env)
  6553. \end{lstlisting}
  6554. \fi}
  6555. \caption{Type checker for the \LangIf{} language.}
  6556. \label{fig:type-check-Lif}
  6557. \end{figure}
  6558. We shift our focus to Figure~\ref{fig:type-check-Lif}, the type
  6559. checker for \LangIf{}.
  6560. %
  6561. The type of a Boolean constant is \BOOLTY{}.
  6562. %
  6563. \racket{The \code{operator-types} function adds dictionary entries for
  6564. the other new operators.}
  6565. %
  6566. \python{Subtraction requires its arguments to be of type \INTTY{} and produces
  6567. an \INTTY{}. Negation requires its argument to be a \BOOLTY{} and
  6568. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6569. %
  6570. The equality operators requires the two arguments to have the same
  6571. type.
  6572. %
  6573. \python{The other comparisons (less-than, etc.) require their
  6574. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6575. %
  6576. The condition of an \code{if} must
  6577. be of \BOOLTY{} type and the two branches must have the same type.
  6578. \begin{exercise}\normalfont
  6579. Create 10 new test programs in \LangIf{}. Half of the programs should
  6580. have a type error. For those programs, create an empty file with the
  6581. same base name but with file extension \code{.tyerr}. For example, if
  6582. the test
  6583. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6584. is expected to error, then create
  6585. an empty file named \code{cond\_test\_14.tyerr}.
  6586. %
  6587. \racket{This indicates to \code{interp-tests} and
  6588. \code{compiler-tests} that a type error is expected. }
  6589. %
  6590. The other half of the test programs should not have type errors.
  6591. %
  6592. \racket{In the \code{run-tests.rkt} script, change the second argument
  6593. of \code{interp-tests} and \code{compiler-tests} to
  6594. \code{type-check-Lif}, which causes the type checker to run prior to
  6595. the compiler passes. Temporarily change the \code{passes} to an
  6596. empty list and run the script, thereby checking that the new test
  6597. programs either type check or not as intended.}
  6598. %
  6599. Run the test script to check that these test programs type check as
  6600. expected.
  6601. \end{exercise}
  6602. \clearpage
  6603. \section{The \LangCIf{} Intermediate Language}
  6604. \label{sec:Cif}
  6605. {\if\edition\racketEd
  6606. %
  6607. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6608. \LangCIf{} intermediate language and Figure~\ref{fig:c1-syntax}
  6609. defines its abstract syntax. Compared to \LangCVar{}, the \LangCIf{}
  6610. language adds logical and comparison operators to the \Exp{}
  6611. non-terminal and the literals \TRUE{} and \FALSE{} to the \Arg{}
  6612. non-terminal.
  6613. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  6614. statements to the \Tail{} non-terminal. The condition of an \code{if}
  6615. statement is a comparison operation and the branches are \code{goto}
  6616. statements, making it straightforward to compile \code{if} statements
  6617. to x86.
  6618. %
  6619. \fi}
  6620. %
  6621. {\if\edition\pythonEd
  6622. %
  6623. The output of \key{explicate\_control} is a language similar to the
  6624. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6625. \code{goto} statements, so we name it \LangCIf{}. The
  6626. concrete syntax for \LangCIf{} is defined in
  6627. Figure~\ref{fig:c1-concrete-syntax}
  6628. and the abstract syntax is defined in Figure~\ref{fig:c1-syntax}.
  6629. %
  6630. The \LangCIf{} language supports the same operators as \LangIf{} but
  6631. the arguments of operators are restricted to atomic expressions. The
  6632. \LangCIf{} language does not include \code{if} expressions but it does
  6633. include a restricted form of \code{if} statment. The condition must be
  6634. a comparison and the two branches may only contain \code{goto}
  6635. statements. These restrictions make it easier to translate \code{if}
  6636. statements to x86.
  6637. %
  6638. \fi}
  6639. %
  6640. The \key{CProgram} construct contains
  6641. %
  6642. \racket{an alist}\python{a dictionary}
  6643. %
  6644. mapping labels to $\Tail$ expressions, which can be return statements,
  6645. an assignment statement followed by a $\Tail$ expression, a
  6646. \code{goto}, or a conditional \code{goto}.
  6647. \newcommand{\CifGrammarRacket}{
  6648. \begin{array}{lcl}
  6649. \Atm &::=& \itm{bool} \\
  6650. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6651. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6652. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  6653. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  6654. \end{array}
  6655. }
  6656. \newcommand{\CifASTRacket}{
  6657. \begin{array}{lcl}
  6658. \Atm &::=& \BOOL{\itm{bool}} \\
  6659. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6660. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6661. \Tail &::= & \GOTO{\itm{label}} \\
  6662. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  6663. \end{array}
  6664. }
  6665. \newcommand{\CifGrammarPython}{
  6666. \begin{array}{lcl}
  6667. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  6668. \Exp &::= & \Atm \MID \CREAD{}
  6669. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  6670. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  6671. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  6672. \Stmt &::=& \CPRINT{\Exp} \MID \Exp \\
  6673. &\MID& \CASSIGN{\Var}{\Exp}
  6674. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  6675. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  6676. \end{array}
  6677. }
  6678. \newcommand{\CifASTPython}{
  6679. \begin{array}{lcl}
  6680. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6681. \Exp &::= & \Atm \MID \READ{} \\
  6682. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6683. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6684. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  6685. \Stmt &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  6686. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6687. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6688. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  6689. \end{array}
  6690. }
  6691. \begin{figure}[tbp]
  6692. \fbox{
  6693. \begin{minipage}{0.96\textwidth}
  6694. \small
  6695. {\if\edition\racketEd
  6696. \[
  6697. \begin{array}{l}
  6698. \gray{\CvarGrammarRacket} \\ \hline
  6699. \CifGrammarRacket \\
  6700. \begin{array}{lcl}
  6701. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  6702. \end{array}
  6703. \end{array}
  6704. \]
  6705. \fi}
  6706. {\if\edition\pythonEd
  6707. \[
  6708. \begin{array}{l}
  6709. \CifGrammarPython \\
  6710. \begin{array}{lcl}
  6711. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  6712. \end{array}
  6713. \end{array}
  6714. \]
  6715. \fi}
  6716. \end{minipage}
  6717. }
  6718. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  6719. \label{fig:c1-concrete-syntax}
  6720. \end{figure}
  6721. \begin{figure}[tp]
  6722. \fbox{
  6723. \begin{minipage}{0.96\textwidth}
  6724. \small
  6725. {\if\edition\racketEd
  6726. \[
  6727. \begin{array}{l}
  6728. \gray{\CvarASTRacket} \\ \hline
  6729. \CifASTRacket \\
  6730. \begin{array}{lcl}
  6731. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  6732. \end{array}
  6733. \end{array}
  6734. \]
  6735. \fi}
  6736. {\if\edition\pythonEd
  6737. \[
  6738. \begin{array}{l}
  6739. \CifASTPython \\
  6740. \begin{array}{lcl}
  6741. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  6742. \end{array}
  6743. \end{array}
  6744. \]
  6745. \fi}
  6746. \end{minipage}
  6747. }
  6748. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6749. (Figure~\ref{fig:c0-syntax})}.}
  6750. \label{fig:c1-syntax}
  6751. \end{figure}
  6752. \section{The \LangXIf{} Language}
  6753. \label{sec:x86-if}
  6754. \index{subject}{x86} To implement the new logical operations, the comparison
  6755. operations, and the \key{if} expression, we need to delve further into
  6756. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  6757. define the concrete and abstract syntax for the \LangXIf{} subset
  6758. of x86, which includes instructions for logical operations,
  6759. comparisons, and \racket{conditional} jumps.
  6760. One challenge is that x86 does not provide an instruction that
  6761. directly implements logical negation (\code{not} in \LangIf{} and
  6762. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6763. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6764. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6765. bit of its arguments, and writes the results into its second argument.
  6766. Recall the truth table for exclusive-or:
  6767. \begin{center}
  6768. \begin{tabular}{l|cc}
  6769. & 0 & 1 \\ \hline
  6770. 0 & 0 & 1 \\
  6771. 1 & 1 & 0
  6772. \end{tabular}
  6773. \end{center}
  6774. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6775. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6776. for the bit $1$, the result is the opposite of the second bit. Thus,
  6777. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6778. the first argument as follows, where $\Arg$ is the translation of
  6779. $\Atm$.
  6780. \[
  6781. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  6782. \qquad\Rightarrow\qquad
  6783. \begin{array}{l}
  6784. \key{movq}~ \Arg\key{,} \Var\\
  6785. \key{xorq}~ \key{\$1,} \Var
  6786. \end{array}
  6787. \]
  6788. \begin{figure}[tp]
  6789. \fbox{
  6790. \begin{minipage}{0.96\textwidth}
  6791. \[
  6792. \begin{array}{lcl}
  6793. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6794. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6795. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  6796. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6797. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  6798. \key{subq} \; \Arg\key{,} \Arg \MID
  6799. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  6800. && \gray{ \key{callq} \; \itm{label} \MID
  6801. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \racket{\key{jmp}\,\itm{label} \MID} } \python{\key{jmp}\,\itm{label} \MID} \\
  6802. && \racket{\gray{ \itm{label}\key{:}\; \Instr }}\python{\itm{label}\key{:}\; \Instr}
  6803. \MID \key{xorq}~\Arg\key{,}~\Arg
  6804. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  6805. && \key{set}cc~\Arg
  6806. \MID \key{movzbq}~\Arg\key{,}~\Arg
  6807. \MID \key{j}cc~\itm{label}
  6808. \\
  6809. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  6810. & & \gray{ \key{main:} \; \Instr\ldots }
  6811. \end{array}
  6812. \]
  6813. \end{minipage}
  6814. }
  6815. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6816. \label{fig:x86-1-concrete}
  6817. \end{figure}
  6818. \begin{figure}[tp]
  6819. \fbox{
  6820. \begin{minipage}{0.98\textwidth}
  6821. \small
  6822. {\if\edition\racketEd
  6823. \[
  6824. \begin{array}{lcl}
  6825. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6826. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6827. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6828. \MID \BYTEREG{\itm{bytereg}} \\
  6829. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6830. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6831. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6832. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  6833. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6834. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6835. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6836. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6837. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6838. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6839. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6840. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}} \\
  6841. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  6842. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  6843. \end{array}
  6844. \]
  6845. \fi}
  6846. %
  6847. {\if\edition\pythonEd
  6848. \[
  6849. \begin{array}{lcl}
  6850. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6851. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6852. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6853. \MID \BYTEREG{\itm{bytereg}} \\
  6854. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6855. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6856. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6857. &\MID& \gray{ \BININSTR{\code{movq}}{\Arg}{\Arg}
  6858. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6859. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6860. \MID \PUSHQ{\Arg}} \\
  6861. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  6862. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6863. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6864. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6865. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6866. &\MID& \JMPIF{\key{'}\itm{cc}\key{'}}{\itm{label}} \\
  6867. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Instr^{*} \key{,} \ldots \RC }
  6868. \end{array}
  6869. \]
  6870. \fi}
  6871. \end{minipage}
  6872. }
  6873. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  6874. \label{fig:x86-1}
  6875. \end{figure}
  6876. Next we consider the x86 instructions that are relevant for compiling
  6877. the comparison operations. The \key{cmpq} instruction compares its two
  6878. arguments to determine whether one argument is less than, equal, or
  6879. greater than the other argument. The \key{cmpq} instruction is unusual
  6880. regarding the order of its arguments and where the result is
  6881. placed. The argument order is backwards: if you want to test whether
  6882. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  6883. \key{cmpq} is placed in the special EFLAGS register. This register
  6884. cannot be accessed directly but it can be queried by a number of
  6885. instructions, including the \key{set} instruction. The instruction
  6886. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  6887. depending on whether the comparison comes out according to the
  6888. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  6889. for less-or-equal, \key{g} for greater, \key{ge} for
  6890. greater-or-equal). The \key{set} instruction has a quirk in
  6891. that its destination argument must be single byte register, such as
  6892. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  6893. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  6894. instruction can be used to move from a single byte register to a
  6895. normal 64-bit register. The abstract syntax for the \code{set}
  6896. instruction differs from the concrete syntax in that it separates the
  6897. instruction name from the condition code.
  6898. \python{The x86 instructions for jumping are relevant to the
  6899. compilation of \key{if} expressions.}
  6900. %
  6901. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  6902. counter to the address of the instruction after the specified
  6903. label.}
  6904. %
  6905. \racket{The x86 instruction for conditional jump is relevant to the
  6906. compilation of \key{if} expressions.}
  6907. %
  6908. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  6909. counter to point to the instruction after \itm{label} depending on
  6910. whether the result in the EFLAGS register matches the condition code
  6911. \itm{cc}, otherwise the jump instruction falls through to the next
  6912. instruction. Like the abstract syntax for \code{set}, the abstract
  6913. syntax for conditional jump separates the instruction name from the
  6914. condition code. For example, \JMPIF{\key{'le'}}{\key{foo}} corresponds
  6915. to \code{jle foo}. Because the conditional jump instruction relies on
  6916. the EFLAGS register, it is common for it to be immediately preceded by
  6917. a \key{cmpq} instruction to set the EFLAGS register.
  6918. \section{Shrink the \LangIf{} Language}
  6919. \label{sec:shrink-Lif}
  6920. The \LangIf{} language includes several features that are easily
  6921. expressible with other features. For example, \code{and} and \code{or}
  6922. are expressible using \code{if} as follows.
  6923. \begin{align*}
  6924. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  6925. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  6926. \end{align*}
  6927. By performing these translations in the front-end of the compiler, the
  6928. later passes of the compiler do not need to deal with these features,
  6929. making the passes shorter.
  6930. %% For example, subtraction is
  6931. %% expressible using addition and negation.
  6932. %% \[
  6933. %% \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  6934. %% \]
  6935. %% Several of the comparison operations are expressible using less-than
  6936. %% and logical negation.
  6937. %% \[
  6938. %% \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  6939. %% \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  6940. %% \]
  6941. %% The \key{let} is needed in the above translation to ensure that
  6942. %% expression $e_1$ is evaluated before $e_2$.
  6943. On the other hand, sometimes translations reduce the efficiency of the
  6944. generated code by increasing the number of instructions. For example,
  6945. expressing subtraction in terms of negation
  6946. \[
  6947. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  6948. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  6949. \]
  6950. produces code with two x86 instructions (\code{negq} and \code{addq})
  6951. instead of just one (\code{subq}).
  6952. %% However,
  6953. %% these differences typically do not affect the number of accesses to
  6954. %% memory, which is the primary factor that determines execution time on
  6955. %% modern computer architectures.
  6956. \begin{exercise}\normalfont
  6957. %
  6958. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  6959. the language by translating them to \code{if} expressions in \LangIf{}.
  6960. %
  6961. Create four test programs that involve these operators.
  6962. %
  6963. {\if\edition\racketEd
  6964. In the \code{run-tests.rkt} script, add the following entry for
  6965. \code{shrink} to the list of passes (it should be the only pass at
  6966. this point).
  6967. \begin{lstlisting}
  6968. (list "shrink" shrink interp_Lif type-check-Lif)
  6969. \end{lstlisting}
  6970. This instructs \code{interp-tests} to run the intepreter
  6971. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  6972. output of \code{shrink}.
  6973. \fi}
  6974. %
  6975. Run the script to test your compiler on all the test programs.
  6976. \end{exercise}
  6977. {\if\edition\racketEd
  6978. \section{Uniquify Variables}
  6979. \label{sec:uniquify-Lif}
  6980. Add cases to \code{uniquify-exp} to handle Boolean constants and
  6981. \code{if} expressions.
  6982. \begin{exercise}\normalfont
  6983. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  6984. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  6985. \begin{lstlisting}
  6986. (list "uniquify" uniquify interp_Lif type_check_Lif)
  6987. \end{lstlisting}
  6988. Run the script to test your compiler.
  6989. \end{exercise}
  6990. \fi}
  6991. \section{Remove Complex Operands}
  6992. \label{sec:remove-complex-opera-Lif}
  6993. The output language of \code{remove\_complex\_operands} is
  6994. \LangIfANF{} (Figure~\ref{fig:Lif-anf-syntax}), the administrative
  6995. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  6996. but the \code{if} expression is not. All three sub-expressions of an
  6997. \code{if} are allowed to be complex expressions but the operands of
  6998. \code{not} and the comparisons must be atomic.
  6999. %
  7000. \python{We add a new language form, the \code{Let} expression, to aid
  7001. in the translation of \code{if} expressions. When we recursively
  7002. process the two branches of the \code{if}, we generate temporary
  7003. variables and their initializing expressions. However, these
  7004. expressions may contain side effects and should only be executed
  7005. when the condition of the \code{if} is true (for the ``then''
  7006. branch) or false (for the ``else'' branch). The \code{Let} provides
  7007. a way to initialize the temporary variables within the two branches
  7008. of the \code{if} expression. In general, the $\LET{x}{e_1}{e_2}$
  7009. form assigns the result of $e_1$ to the variable $x$, an then
  7010. evaluates $e_2$, which may reference $x$.}
  7011. Add cases for Boolean constants, \python{comparisons,} and \code{if}
  7012. expressions to the \code{rco\_exp} and \code{rco\_atom} functions
  7013. according to whether the output needs to be \Exp{} or \Atm{} as
  7014. specified in the grammar for \LangIfANF{}. Regarding \code{if}, it is
  7015. particularly important to \textbf{not} replace its condition with a
  7016. temporary variable because that would interfere with the generation of
  7017. high-quality output in the \code{explicate\_control} pass.
  7018. \newcommand{\LifASTMonadPython}{
  7019. \begin{array}{rcl}
  7020. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7021. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7022. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7023. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7024. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  7025. \Exp &::=& \Atm \MID \READ{} \\
  7026. &\MID& \BINOP{\itm{binaryop}}{\Atm}{\Atm} \MID \UNIOP{\key{unaryop}}{\Atm} \\
  7027. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7028. &\MID& \LET{\Var}{\Exp}{\Exp}\\
  7029. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7030. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}\\
  7031. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7032. \end{array}
  7033. }
  7034. \begin{figure}[tp]
  7035. \centering
  7036. \fbox{
  7037. \begin{minipage}{0.96\textwidth}
  7038. {\if\edition\racketEd
  7039. \[
  7040. \begin{array}{rcl}
  7041. Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  7042. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  7043. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  7044. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7045. &\MID& \UNIOP{\key{not}}{\Atm} \\
  7046. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7047. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7048. \end{array}
  7049. \]
  7050. \fi}
  7051. {\if\edition\pythonEd
  7052. \[
  7053. \begin{array}{l}
  7054. \LifASTMonadPython \\
  7055. \begin{array}{rcl}
  7056. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7057. \end{array}
  7058. \end{array}
  7059. \]
  7060. \fi}
  7061. \end{minipage}
  7062. }
  7063. \caption{\LangIfANF{} is \LangIf{} in monadic normal form.}
  7064. \label{fig:Lif-anf-syntax}
  7065. \end{figure}
  7066. \begin{exercise}\normalfont
  7067. %
  7068. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7069. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7070. %
  7071. Create three new \LangIf{} programs that exercise the interesting
  7072. code in this pass.
  7073. %
  7074. {\if\edition\racketEd
  7075. In the \code{run-tests.rkt} script, add the following entry to the
  7076. list of \code{passes} and then run the script to test your compiler.
  7077. \begin{lstlisting}
  7078. (list "remove-complex" remove-complex-opera* interp-Lif type-check-Lif)
  7079. \end{lstlisting}
  7080. \fi}
  7081. \end{exercise}
  7082. \section{Explicate Control}
  7083. \label{sec:explicate-control-Lif}
  7084. \racket{Recall that the purpose of \code{explicate\_control} is to
  7085. make the order of evaluation explicit in the syntax of the program.
  7086. With the addition of \key{if} this get more interesting.}
  7087. %
  7088. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7089. %
  7090. The main challenge to overcome is that the condition of an \key{if}
  7091. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  7092. condition must be a comparison.
  7093. As a motivating example, consider the following program that has an
  7094. \key{if} expression nested in the condition of another \key{if}.%
  7095. \python{\footnote{Programmers rarely write nested \code{if}
  7096. expressions, but it is not uncommon for the condition of an
  7097. \code{if} statement to be a call of a function that also contains an
  7098. \code{if} statement. When such a function is inlined, the result is
  7099. a nested \code{if} that requires the techniques discussed in this
  7100. section.}}
  7101. % cond_test_41.rkt, if_lt_eq.py
  7102. \begin{center}
  7103. \begin{minipage}{0.96\textwidth}
  7104. {\if\edition\racketEd
  7105. \begin{lstlisting}
  7106. (let ([x (read)])
  7107. (let ([y (read)])
  7108. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7109. (+ y 2)
  7110. (+ y 10))))
  7111. \end{lstlisting}
  7112. \fi}
  7113. {\if\edition\pythonEd
  7114. \begin{lstlisting}
  7115. x = input_int()
  7116. y = input_int()
  7117. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7118. \end{lstlisting}
  7119. \fi}
  7120. \end{minipage}
  7121. \end{center}
  7122. %
  7123. The naive way to compile \key{if} and the comparison operations would
  7124. be to handle each of them in isolation, regardless of their context.
  7125. Each comparison would be translated into a \key{cmpq} instruction
  7126. followed by a couple instructions to move the result from the EFLAGS
  7127. register into a general purpose register or stack location. Each
  7128. \key{if} would be translated into a \key{cmpq} instruction followed by
  7129. a conditional jump. The generated code for the inner \key{if} in the
  7130. above example would be as follows.
  7131. \begin{center}
  7132. \begin{minipage}{0.96\textwidth}
  7133. \begin{lstlisting}
  7134. cmpq $1, x
  7135. setl %al
  7136. movzbq %al, tmp
  7137. cmpq $1, tmp
  7138. je then_branch_1
  7139. jmp else_branch_1
  7140. \end{lstlisting}
  7141. \end{minipage}
  7142. \end{center}
  7143. However, if we take context into account we can do better and reduce
  7144. the use of \key{cmpq} instructions for accessing the EFLAG register.
  7145. Our goal will be to compile \key{if} expressions so that the relevant
  7146. comparison instruction appears directly before the conditional jump.
  7147. For example, we want to generate the following code for the inner
  7148. \code{if}.
  7149. \begin{center}
  7150. \begin{minipage}{0.96\textwidth}
  7151. \begin{lstlisting}
  7152. cmpq $1, x
  7153. jl then_branch_1
  7154. jmp else_branch_1
  7155. \end{lstlisting}
  7156. \end{minipage}
  7157. \end{center}
  7158. One way to achieve this is to reorganize the code at the level of
  7159. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7160. the following code.
  7161. \begin{center}
  7162. \begin{minipage}{0.96\textwidth}
  7163. {\if\edition\racketEd
  7164. \begin{lstlisting}
  7165. (let ([x (read)])
  7166. (let ([y (read)])
  7167. (if (< x 1)
  7168. (if (eq? x 0)
  7169. (+ y 2)
  7170. (+ y 10))
  7171. (if (eq? x 2)
  7172. (+ y 2)
  7173. (+ y 10)))))
  7174. \end{lstlisting}
  7175. \fi}
  7176. {\if\edition\pythonEd
  7177. \begin{lstlisting}
  7178. x = input_int()
  7179. y = intput_int()
  7180. print(((y + 2) if x == 0 else (y + 10)) \
  7181. if (x < 1) \
  7182. else ((y + 2) if (x == 2) else (y + 10)))
  7183. \end{lstlisting}
  7184. \fi}
  7185. \end{minipage}
  7186. \end{center}
  7187. Unfortunately, this approach duplicates the two branches from the
  7188. outer \code{if} and a compiler must never duplicate code! After all,
  7189. the two branches could have been very large expressions.
  7190. We need a way to perform the above transformation but without
  7191. duplicating code. That is, we need a way for different parts of a
  7192. program to refer to the same piece of code.
  7193. %
  7194. Put another way, we need to move away from abstract syntax
  7195. \emph{trees} and instead use \emph{graphs}.
  7196. %
  7197. At the level of x86 assembly this is straightforward because we can
  7198. label the code for each branch and insert jumps in all the places that
  7199. need to execute the branch.
  7200. %
  7201. Likewise, our language \LangCIf{} provides the ability to label a
  7202. sequence of code and to jump to a label via \code{goto}.
  7203. %
  7204. %% In particular, we use a standard program representation called a
  7205. %% \emph{control flow graph} (CFG), due to Frances Elizabeth
  7206. %% \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex
  7207. %% is a labeled sequence of code, called a \emph{basic block}, and each
  7208. %% edge represents a jump to another block.
  7209. %
  7210. %% The nice thing about the output of \code{explicate\_control} is that
  7211. %% there are no unnecessary comparisons and every comparison is part of a
  7212. %% conditional jump.
  7213. %% The down-side of this output is that it includes
  7214. %% trivial blocks, such as the blocks labeled \code{block92} through
  7215. %% \code{block95}, that only jump to another block. We discuss a solution
  7216. %% to this problem in Section~\ref{sec:opt-jumps}.
  7217. {\if\edition\racketEd
  7218. %
  7219. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  7220. \code{explicate\_control} for \LangVar{} using two mutually recursive
  7221. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7222. former function translates expressions in tail position whereas the
  7223. later function translates expressions on the right-hand-side of a
  7224. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  7225. have a new kind of position to deal with: the predicate position of
  7226. the \key{if}. We need another function, \code{explicate\_pred}, that
  7227. decides how to compile an \key{if} by analyzing its predicate. So
  7228. \code{explicate\_pred} takes an \LangIf{} expression and two \LangCIf{}
  7229. tails for the then-branch and else-branch and outputs a tail. In the
  7230. following paragraphs we discuss specific cases in the
  7231. \code{explicate\_tail}, \code{explicate\_assign}, and
  7232. \code{explicate\_pred} functions.
  7233. %
  7234. \fi}
  7235. %
  7236. {\if\edition\pythonEd
  7237. %
  7238. We recommend implementing \code{explicate\_control} using the
  7239. following four auxiliary functions.
  7240. \begin{description}
  7241. \item[\code{explicate\_effect}] generates code for expressions as
  7242. statements, so their result is ignored and only their side effects
  7243. matter.
  7244. \item[\code{explicate\_assign}] generates code for expressions
  7245. on the right-hand side of an assignment.
  7246. \item[\code{explicate\_pred}] generates code for an \code{if}
  7247. expression or statement by analyzing the condition expression.
  7248. \item[\code{explicate\_stmt}] generates code for statements.
  7249. \end{description}
  7250. These four functions should build the dictionary of basic blocks. The
  7251. following auxiliary function can be used to create a new basic block
  7252. from a list of statements. It returns a \code{goto} statement that
  7253. jumps to the new basic block.
  7254. \begin{center}
  7255. \begin{minipage}{\textwidth}
  7256. \begin{lstlisting}
  7257. def create_block(stmts, basic_blocks):
  7258. label = label_name(generate_name('block'))
  7259. basic_blocks[label] = stmts
  7260. return Goto(label)
  7261. \end{lstlisting}
  7262. \end{minipage}
  7263. \end{center}
  7264. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7265. \code{explicate\_control} pass.
  7266. The \code{explicate\_effect} function has three parameters: 1) the
  7267. expression to be compiled, 2) the already-compiled code for this
  7268. expression's \emph{continuation}, that is, the list of statements that
  7269. should execute after this expression, and 3) the dictionary of
  7270. generated basic blocks. The \code{explicate\_effect} function returns
  7271. a list of \LangCIf{} statements and it may add to the dictionary of
  7272. basic blocks.
  7273. %
  7274. Let's consider a few of the cases for the expression to be compiled.
  7275. If the expression to be compiled is a constant, then it can be
  7276. discarded because it has no side effects. If it's a \CREAD{}, then it
  7277. has a side-effect and should be preserved. So the exprssion should be
  7278. translated into a statement using the \code{Expr} AST class. If the
  7279. expression to be compiled is an \code{if} expression, we translate the
  7280. two branches using \code{explicate\_effect} and then translate the
  7281. condition expression using \code{explicate\_pred}, which generates
  7282. code for the entire \code{if}.
  7283. The \code{explicate\_assign} function has four parameters: 1) the
  7284. right-hand-side of the assignment, 2) the left-hand-side of the
  7285. assignment (the variable), 3) the continuation, and 4) the dictionary
  7286. of basic blocks. The \code{explicate\_assign} function returns a list
  7287. of \LangCIf{} statements and it may add to the dictionary of basic
  7288. blocks.
  7289. When the right-hand-side is an \code{if} expression, there is some
  7290. work to do. In particular, the two branches should be translated using
  7291. \code{explicate\_assign} and the condition expression should be
  7292. translated using \code{explicate\_pred}. Otherwise we can simply
  7293. generate an assignment statement, with the given left and right-hand
  7294. sides, concatenated with its continuation.
  7295. \begin{figure}[tbp]
  7296. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7297. def explicate_effect(e, cont, basic_blocks):
  7298. match e:
  7299. case IfExp(test, body, orelse):
  7300. ...
  7301. case Call(func, args):
  7302. ...
  7303. case Let(var, rhs, body):
  7304. ...
  7305. case _:
  7306. ...
  7307. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7308. match rhs:
  7309. case IfExp(test, body, orelse):
  7310. ...
  7311. case Let(var, rhs, body):
  7312. ...
  7313. case _:
  7314. return [Assign([lhs], rhs)] + cont
  7315. def explicate_pred(cnd, thn, els, basic_blocks):
  7316. match cnd:
  7317. case Compare(left, [op], [right]):
  7318. goto_thn = create_block(thn, basic_blocks)
  7319. goto_els = create_block(els, basic_blocks)
  7320. return [If(cnd, [goto_thn], [goto_els])]
  7321. case Constant(True):
  7322. return thn;
  7323. case Constant(False):
  7324. return els;
  7325. case UnaryOp(Not(), operand):
  7326. ...
  7327. case IfExp(test, body, orelse):
  7328. ...
  7329. case Let(var, rhs, body):
  7330. ...
  7331. case _:
  7332. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7333. [create_block(els, basic_blocks)],
  7334. [create_block(thn, basic_blocks)])]
  7335. def explicate_stmt(s, cont, basic_blocks):
  7336. match s:
  7337. case Assign([lhs], rhs):
  7338. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7339. case Expr(value):
  7340. return explicate_effect(value, cont, basic_blocks)
  7341. case If(test, body, orelse):
  7342. ...
  7343. def explicate_control(p):
  7344. match p:
  7345. case Module(body):
  7346. new_body = [Return(Constant(0))]
  7347. basic_blocks = {}
  7348. for s in reversed(body):
  7349. new_body = explicate_stmt(s, new_body, basic_blocks)
  7350. basic_blocks[label_name('start')] = new_body
  7351. return CProgram(basic_blocks)
  7352. \end{lstlisting}
  7353. \caption{Skeleton for the \code{explicate\_control} pass.}
  7354. \label{fig:explicate-control-Lif}
  7355. \end{figure}
  7356. \fi}
  7357. {\if\edition\racketEd
  7358. %
  7359. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7360. additional cases for Boolean constants and \key{if}. The cases for
  7361. \code{if} should recursively compile the two branches using either
  7362. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7363. cases should then invoke \code{explicate\_pred} on the condition
  7364. expression, passing in the generated code for the two branches. For
  7365. example, consider the following program with an \code{if} in tail
  7366. position.
  7367. \begin{lstlisting}
  7368. (let ([x (read)])
  7369. (if (eq? x 0) 42 777))
  7370. \end{lstlisting}
  7371. The two branches are recursively compiled to \code{return 42;} and
  7372. \code{return 777;}. We then delegate to \code{explicate\_pred},
  7373. passing the condition \code{(eq? x 0)} and the two return statements, which is
  7374. used as the result for \code{explicate\_tail}.
  7375. Next let us consider a program with an \code{if} on the right-hand
  7376. side of a \code{let}.
  7377. \begin{lstlisting}
  7378. (let ([y (read)])
  7379. (let ([x (if (eq? y 0) 40 777)])
  7380. (+ x 2)))
  7381. \end{lstlisting}
  7382. Note that the body of the inner \code{let} will have already been
  7383. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7384. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7385. to recursively process both branches of the \code{if}, so we generate
  7386. the following block using an auxiliary function named \code{create\_block}.
  7387. \begin{lstlisting}
  7388. block_6:
  7389. return (+ x 2)
  7390. \end{lstlisting}
  7391. and use \code{goto block\_6;} as the \code{cont} argument for
  7392. compiling the branches. So the two branches compile to
  7393. \begin{lstlisting}
  7394. x = 40;
  7395. goto block_6;
  7396. \end{lstlisting}
  7397. and
  7398. \begin{lstlisting}
  7399. x = 777;
  7400. goto block_6;
  7401. \end{lstlisting}
  7402. We then delegate to \code{explicate\_pred}, passing the condition \code{(eq? y
  7403. 0)} and the above code for the branches.
  7404. \fi}
  7405. {\if\edition\racketEd
  7406. \begin{figure}[tbp]
  7407. \begin{lstlisting}
  7408. (define (explicate_pred cnd thn els)
  7409. (match cnd
  7410. [(Var x) ___]
  7411. [(Let x rhs body) ___]
  7412. [(Prim 'not (list e)) ___]
  7413. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7414. (IfStmt (Prim op es) (create_block thn)
  7415. (create_block els))]
  7416. [(Bool b) (if b thn els)]
  7417. [(If cnd^ thn^ els^) ___]
  7418. [else (error "explicate_pred unhandled case" cnd)]))
  7419. \end{lstlisting}
  7420. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7421. \label{fig:explicate-pred}
  7422. \end{figure}
  7423. \fi}
  7424. \racket{The skeleton for the \code{explicate\_pred} function is given
  7425. in Figure~\ref{fig:explicate-pred}. It takes three parameters:
  7426. 1) \code{cnd}, the condition expression of the \code{if},
  7427. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7428. and 3) \code{els}, the code generated by
  7429. explicate for the ``else'' branch. The \code{explicate\_pred}
  7430. function should match on \code{cnd} with a case for
  7431. every kind of expression that can have type \code{Boolean}.}
  7432. %
  7433. \python{The \code{explicate\_pred} function has four parameters: 1)
  7434. the condition expession, 2) the generated statements for the
  7435. ``then'' branch, 3) the generated statements for the ``else''
  7436. branch, and 4) the dictionary of basic blocks. The
  7437. \code{explicate\_pred} function returns a list of \LangCIf{}
  7438. statements and it may add to the dictionary of basic blocks.}
  7439. Consider the case for comparison operators. We translate the
  7440. comparison to an \code{if} statement whose branches are \code{goto}
  7441. statements created by applying \code{create\_block} to the code
  7442. generated for the \code{thn} and \code{els} branches. Let us
  7443. illustrate this translation with an example. Returning
  7444. to the program with an \code{if} expression in tail position,
  7445. we invoke \code{explicate\_pred} on its condition \code{(eq? x 0)}
  7446. which happens to be a comparison operator.
  7447. \begin{lstlisting}
  7448. (let ([x (read)])
  7449. (if (eq? x 0) 42 777))
  7450. \end{lstlisting}
  7451. The two branches \code{42} and \code{777} were already compiled to \code{return}
  7452. statements, from which we now create the following blocks.
  7453. \begin{center}
  7454. \begin{minipage}{\textwidth}
  7455. \begin{lstlisting}
  7456. block_1:
  7457. return 42;
  7458. block_2:
  7459. return 777;
  7460. \end{lstlisting}
  7461. \end{minipage}
  7462. \end{center}
  7463. %
  7464. So \code{explicate\_pred} compiles the comparison \code{(eq? x 0)}
  7465. to the following \code{if} statement.
  7466. %
  7467. \begin{center}
  7468. \begin{minipage}{\textwidth}
  7469. \begin{lstlisting}
  7470. if (eq? x 0)
  7471. goto block_1;
  7472. else
  7473. goto block_2;
  7474. \end{lstlisting}
  7475. \end{minipage}
  7476. \end{center}
  7477. Next consider the case for Boolean constants. We perform a kind of
  7478. partial evaluation\index{subject}{partial evaluation} and output
  7479. either the \code{thn} or \code{els} branch depending on whether the
  7480. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7481. following program.
  7482. \begin{center}
  7483. \begin{minipage}{\textwidth}
  7484. \begin{lstlisting}
  7485. (if #t 42 777)
  7486. \end{lstlisting}
  7487. \end{minipage}
  7488. \end{center}
  7489. %
  7490. Again, the two branches \code{42} and \code{777} were compiled to
  7491. \code{return} statements, so \code{explicate\_pred} compiles the
  7492. constant \code{\#t} to the code for the ``then'' branch.
  7493. \begin{center}
  7494. \begin{minipage}{\textwidth}
  7495. \begin{lstlisting}
  7496. return 42;
  7497. \end{lstlisting}
  7498. \end{minipage}
  7499. \end{center}
  7500. %
  7501. This case demonstrates that we sometimes discard the \code{thn} or
  7502. \code{els} blocks that are input to \code{explicate\_pred}.
  7503. The case for \key{if} expressions in \code{explicate\_pred} is
  7504. particularly illuminating because it deals with the challenges we
  7505. discussed above regarding nested \key{if} expressions
  7506. (Figure~\ref{fig:explicate-control-s1-38}). The
  7507. \racket{\lstinline{thn^}}\python{\code{body}} and
  7508. \racket{\lstinline{els^}}\python{\code{orlese}} branches of the
  7509. \key{if} inherit their context from the current one, that is,
  7510. predicate context. So you should recursively apply
  7511. \code{explicate\_pred} to the
  7512. \racket{\lstinline{thn^}}\python{\code{body}} and
  7513. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7514. those recursive calls, pass \code{thn} and \code{els} as the extra
  7515. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7516. inside each recursive call. As discussed above, to avoid duplicating
  7517. code, we need to add them to the dictionary of basic blocks so that we
  7518. can instead refer to them by name and execute them with a \key{goto}.
  7519. {\if\edition\pythonEd
  7520. %
  7521. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7522. three parameters: 1) the statement to be compiled, 2) the code for its
  7523. continuation, and 3) the dictionary of basic blocks. The
  7524. \code{explicate\_stmt} returns a list of statements and it may add to
  7525. the dictionary of basic blocks. The cases for assignment and an
  7526. expression-statement are given in full in the skeleton code: they
  7527. simply dispatch to \code{explicate\_assign} and
  7528. \code{explicate\_effect}, respectively. The case for \code{if}
  7529. statements is not given, and is similar to the case for \code{if}
  7530. expressions.
  7531. The \code{explicate\_control} function itself is given in
  7532. Figure~\ref{fig:explicate-control-Lif}. It applies
  7533. \code{explicate\_stmt} to each statement in the program, from back to
  7534. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7535. used as the continuation parameter in the next call to
  7536. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7537. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7538. the dictionary of basic blocks, labeling it as the ``start'' block.
  7539. %
  7540. \fi}
  7541. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7542. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7543. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7544. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7545. %% results from the two recursive calls. We complete the case for
  7546. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7547. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7548. %% the result $B_5$.
  7549. %% \[
  7550. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7551. %% \quad\Rightarrow\quad
  7552. %% B_5
  7553. %% \]
  7554. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7555. %% inherit the current context, so they are in tail position. Thus, the
  7556. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7557. %% \code{explicate\_tail}.
  7558. %% %
  7559. %% We need to pass $B_0$ as the accumulator argument for both of these
  7560. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7561. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7562. %% to the control-flow graph and obtain a promised goto $G_0$.
  7563. %% %
  7564. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7565. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7566. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7567. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7568. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7569. %% \[
  7570. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7571. %% \]
  7572. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7573. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7574. %% should not be confused with the labels for the blocks that appear in
  7575. %% the generated code. We initially construct unlabeled blocks; we only
  7576. %% attach labels to blocks when we add them to the control-flow graph, as
  7577. %% we see in the next case.
  7578. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7579. %% function. The context of the \key{if} is an assignment to some
  7580. %% variable $x$ and then the control continues to some promised block
  7581. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7582. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7583. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7584. %% branches of the \key{if} inherit the current context, so they are in
  7585. %% assignment positions. Let $B_2$ be the result of applying
  7586. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7587. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7588. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7589. %% the result of applying \code{explicate\_pred} to the predicate
  7590. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7591. %% translates to the promise $B_4$.
  7592. %% \[
  7593. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7594. %% \]
  7595. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7596. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7597. \code{remove\_complex\_operands} pass and then the
  7598. \code{explicate\_control} pass on the example program. We walk through
  7599. the output program.
  7600. %
  7601. Following the order of evaluation in the output of
  7602. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7603. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7604. in the predicate of the inner \key{if}. In the output of
  7605. \code{explicate\_control}, in the
  7606. block labeled \code{start}, are two assignment statements followed by a
  7607. \code{if} statement that branches to \code{block\_8} or
  7608. \code{block\_9}. The blocks associated with those labels contain the
  7609. translations of the code
  7610. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7611. and
  7612. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7613. respectively. In particular, we start \code{block\_8} with the
  7614. comparison
  7615. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7616. and then branch to \code{block\_4} or \code{block\_5}.
  7617. Here was see that our algorithm sometimes inserts unnecessary blocks:
  7618. \code{block\_4} is just a \code{goto} to \code{block\_2}
  7619. and \code{block\_5} is just a \code{goto} to \code{block\_3}.
  7620. It would be better to skip blocks \code{block\_4} and \code{block\_5}
  7621. and go directly to \code{block\_2} and \code{block\_3},
  7622. which we investigate in Section~\ref{sec:opt-jumps}.
  7623. Getting back to the example, \code{block\_2} and \code{block\_3},
  7624. corresponds to the two branches of the outer \key{if}, i.e.,
  7625. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7626. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7627. %
  7628. The story for \code{block\_9} is similar to that of \code{block\_8}.
  7629. %
  7630. \python{The \code{block\_1} corresponds to the \code{print} statment
  7631. at the end of the program.}
  7632. \begin{figure}[tbp]
  7633. {\if\edition\racketEd
  7634. \begin{tabular}{lll}
  7635. \begin{minipage}{0.4\textwidth}
  7636. % cond_test_41.rkt
  7637. \begin{lstlisting}
  7638. (let ([x (read)])
  7639. (let ([y (read)])
  7640. (if (if (< x 1)
  7641. (eq? x 0)
  7642. (eq? x 2))
  7643. (+ y 2)
  7644. (+ y 10))))
  7645. \end{lstlisting}
  7646. \end{minipage}
  7647. &
  7648. $\Rightarrow$
  7649. &
  7650. \begin{minipage}{0.55\textwidth}
  7651. \begin{lstlisting}
  7652. start:
  7653. x = (read);
  7654. y = (read);
  7655. if (< x 1)
  7656. goto block_8;
  7657. else
  7658. goto block_9;
  7659. block_8:
  7660. if (eq? x 0)
  7661. goto block_4;
  7662. else
  7663. goto block_5;
  7664. block_9:
  7665. if (eq? x 2)
  7666. goto block_6;
  7667. else
  7668. goto block_7;
  7669. block_4:
  7670. goto block_2;
  7671. block_5:
  7672. goto block_3;
  7673. block_6:
  7674. goto block_2;
  7675. block_7:
  7676. goto block_3;
  7677. block_2:
  7678. return (+ y 2);
  7679. block_3:
  7680. return (+ y 10);
  7681. \end{lstlisting}
  7682. \end{minipage}
  7683. \end{tabular}
  7684. \fi}
  7685. {\if\edition\pythonEd
  7686. \begin{tabular}{lll}
  7687. \begin{minipage}{0.4\textwidth}
  7688. % cond_test_41.rkt
  7689. \begin{lstlisting}
  7690. x = input_int()
  7691. y = input_int()
  7692. print(y + 2 \
  7693. if (x == 0 \
  7694. if x < 1 \
  7695. else x == 2) \
  7696. else y + 10)
  7697. \end{lstlisting}
  7698. \end{minipage}
  7699. &
  7700. $\Rightarrow$
  7701. &
  7702. \begin{minipage}{0.55\textwidth}
  7703. \begin{lstlisting}
  7704. start:
  7705. x = input_int()
  7706. y = input_int()
  7707. if x < 1:
  7708. goto block_8
  7709. else:
  7710. goto block_9
  7711. block_8:
  7712. if x == 0:
  7713. goto block_4
  7714. else:
  7715. goto block_5
  7716. block_9:
  7717. if x == 2:
  7718. goto block_6
  7719. else:
  7720. goto block_7
  7721. block_4:
  7722. goto block_2
  7723. block_5:
  7724. goto block_3
  7725. block_6:
  7726. goto block_2
  7727. block_7:
  7728. goto block_3
  7729. block_2:
  7730. tmp_0 = y + 2
  7731. goto block_1
  7732. block_3:
  7733. tmp_0 = y + 10
  7734. goto block_1
  7735. block_1:
  7736. print(tmp_0)
  7737. return 0
  7738. \end{lstlisting}
  7739. \end{minipage}
  7740. \end{tabular}
  7741. \fi}
  7742. \caption{Translation from \LangIf{} to \LangCIf{}
  7743. via the \code{explicate\_control}.}
  7744. \label{fig:explicate-control-s1-38}
  7745. \end{figure}
  7746. {\if\edition\racketEd
  7747. The way in which the \code{shrink} pass transforms logical operations
  7748. such as \code{and} and \code{or} can impact the quality of code
  7749. generated by \code{explicate\_control}. For example, consider the
  7750. following program.
  7751. % cond_test_21.rkt, and_eq_input.py
  7752. \begin{lstlisting}
  7753. (if (and (eq? (read) 0) (eq? (read) 1))
  7754. 0
  7755. 42)
  7756. \end{lstlisting}
  7757. The \code{and} operation should transform into something that the
  7758. \code{explicate\_pred} function can still analyze and descend through to
  7759. reach the underlying \code{eq?} conditions. Ideally, your
  7760. \code{explicate\_control} pass should generate code similar to the
  7761. following for the above program.
  7762. \begin{center}
  7763. \begin{lstlisting}
  7764. start:
  7765. tmp1 = (read);
  7766. if (eq? tmp1 0) goto block40;
  7767. else goto block39;
  7768. block40:
  7769. tmp2 = (read);
  7770. if (eq? tmp2 1) goto block38;
  7771. else goto block39;
  7772. block38:
  7773. return 0;
  7774. block39:
  7775. return 42;
  7776. \end{lstlisting}
  7777. \end{center}
  7778. \fi}
  7779. \begin{exercise}\normalfont
  7780. \racket{
  7781. Implement the pass \code{explicate\_control} by adding the cases for
  7782. Boolean constants and \key{if} to the \code{explicate\_tail} and
  7783. \code{explicate\_assign} functions. Implement the auxiliary function
  7784. \code{explicate\_pred} for predicate contexts.}
  7785. \python{Implement \code{explicate\_control} pass with its
  7786. four auxiliary functions.}
  7787. %
  7788. Create test cases that exercise all of the new cases in the code for
  7789. this pass.
  7790. %
  7791. {\if\edition\racketEd
  7792. Add the following entry to the list of \code{passes} in
  7793. \code{run-tests.rkt} and then run this script to test your compiler.
  7794. \begin{lstlisting}
  7795. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  7796. \end{lstlisting}
  7797. \fi}
  7798. \end{exercise}
  7799. \clearpage
  7800. \section{Select Instructions}
  7801. \label{sec:select-Lif}
  7802. \index{subject}{instruction selection}
  7803. The \code{select\_instructions} pass translates \LangCIf{} to
  7804. \LangXIfVar{}.
  7805. %
  7806. \racket{Recall that we implement this pass using three auxiliary
  7807. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  7808. $\Tail$.}
  7809. %
  7810. \racket{For $\Atm$, we have new cases for the Booleans.}
  7811. %
  7812. \python{We begin with the Boolean constants.}
  7813. We take the usual approach of encoding them as integers.
  7814. \[
  7815. \TRUE{} \quad\Rightarrow\quad \key{1}
  7816. \qquad\qquad
  7817. \FALSE{} \quad\Rightarrow\quad \key{0}
  7818. \]
  7819. For translating statements, we discuss a couple cases. The \code{not}
  7820. operation can be implemented in terms of \code{xorq} as we discussed
  7821. at the beginning of this section. Given an assignment, if the
  7822. left-hand side variable is the same as the argument of \code{not},
  7823. then just the \code{xorq} instruction suffices.
  7824. \[
  7825. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  7826. \quad\Rightarrow\quad
  7827. \key{xorq}~\key{\$}1\key{,}~\Var
  7828. \]
  7829. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  7830. semantics of x86. In the following translation, let $\Arg$ be the
  7831. result of translating $\Atm$ to x86.
  7832. \[
  7833. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  7834. \quad\Rightarrow\quad
  7835. \begin{array}{l}
  7836. \key{movq}~\Arg\key{,}~\Var\\
  7837. \key{xorq}~\key{\$}1\key{,}~\Var
  7838. \end{array}
  7839. \]
  7840. Next consider the cases for equality. Translating this operation to
  7841. x86 is slightly involved due to the unusual nature of the \key{cmpq}
  7842. instruction discussed above. We recommend translating an assignment
  7843. with an equality on the right-hand side into a sequence of three
  7844. instructions. \\
  7845. \begin{tabular}{lll}
  7846. \begin{minipage}{0.4\textwidth}
  7847. \begin{lstlisting}
  7848. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  7849. \end{lstlisting}
  7850. \end{minipage}
  7851. &
  7852. $\Rightarrow$
  7853. &
  7854. \begin{minipage}{0.4\textwidth}
  7855. \begin{lstlisting}
  7856. cmpq |$\Arg_2$|, |$\Arg_1$|
  7857. sete %al
  7858. movzbq %al, |$\Var$|
  7859. \end{lstlisting}
  7860. \end{minipage}
  7861. \end{tabular} \\
  7862. The translations for the other comparison operators are similar to the
  7863. above but use different suffixes for the \code{set} instruction.
  7864. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  7865. \key{goto} and \key{if} statements. Both are straightforward to
  7866. translate to x86.}
  7867. %
  7868. A \key{goto} statement becomes a jump instruction.
  7869. \[
  7870. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  7871. \]
  7872. %
  7873. An \key{if} statement becomes a compare instruction followed by a
  7874. conditional jump (for the ``then'' branch) and the fall-through is to
  7875. a regular jump (for the ``else'' branch).\\
  7876. \begin{tabular}{lll}
  7877. \begin{minipage}{0.4\textwidth}
  7878. \begin{lstlisting}
  7879. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  7880. goto |$\ell_1$||$\racket{\key{;}}$|
  7881. else|$\python{\key{:}}$|
  7882. goto |$\ell_2$||$\racket{\key{;}}$|
  7883. \end{lstlisting}
  7884. \end{minipage}
  7885. &
  7886. $\Rightarrow$
  7887. &
  7888. \begin{minipage}{0.4\textwidth}
  7889. \begin{lstlisting}
  7890. cmpq |$\Arg_2$|, |$\Arg_1$|
  7891. je |$\ell_1$|
  7892. jmp |$\ell_2$|
  7893. \end{lstlisting}
  7894. \end{minipage}
  7895. \end{tabular} \\
  7896. Again, the translations for the other comparison operators are similar to the
  7897. above but use different suffixes for the conditional jump instruction.
  7898. \python{Regarding the \key{return} statement, we recommend treating it
  7899. as an assignment to the \key{rax} register followed by a jump to the
  7900. conclusion of the \code{main} function.}
  7901. \begin{exercise}\normalfont
  7902. Expand your \code{select\_instructions} pass to handle the new
  7903. features of the \LangIf{} language.
  7904. %
  7905. {\if\edition\racketEd
  7906. Add the following entry to the list of \code{passes} in
  7907. \code{run-tests.rkt}
  7908. \begin{lstlisting}
  7909. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  7910. \end{lstlisting}
  7911. \fi}
  7912. %
  7913. Run the script to test your compiler on all the test programs.
  7914. \end{exercise}
  7915. \section{Register Allocation}
  7916. \label{sec:register-allocation-Lif}
  7917. \index{subject}{register allocation}
  7918. The changes required for \LangIf{} affect liveness analysis, building the
  7919. interference graph, and assigning homes, but the graph coloring
  7920. algorithm itself does not change.
  7921. \subsection{Liveness Analysis}
  7922. \label{sec:liveness-analysis-Lif}
  7923. \index{subject}{liveness analysis}
  7924. Recall that for \LangVar{} we implemented liveness analysis for a
  7925. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  7926. the addition of \key{if} expressions to \LangIf{},
  7927. \code{explicate\_control} produces many basic blocks.
  7928. %% We recommend that you create a new auxiliary function named
  7929. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  7930. %% control-flow graph.
  7931. The first question is: what order should we process the basic blocks?
  7932. Recall that to perform liveness analysis on a basic block we need to
  7933. know the live-after set for the last instruction in the block. If a
  7934. basic block has no successors (i.e. contains no jumps to other
  7935. blocks), then it has an empty live-after set and we can immediately
  7936. apply liveness analysis to it. If a basic block has some successors,
  7937. then we need to complete liveness analysis on those blocks
  7938. first. These ordering contraints are the reverse of a
  7939. \emph{topological order}\index{subject}{topological order} on a graph
  7940. representation of the program. In particular, the \emph{control flow
  7941. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  7942. of a program has a node for each basic block and an edge for each jump
  7943. from one block to another. It is straightforward to generate a CFG
  7944. from the dictionary of basic blocks. One then transposes the CFG and
  7945. applies the topological sort algorithm.
  7946. %
  7947. %
  7948. \racket{We recommend using the \code{tsort} and \code{transpose}
  7949. functions of the Racket \code{graph} package to accomplish this.}
  7950. %
  7951. \python{We provide implementations of \code{topological\_sort} and
  7952. \code{transpose} in the file \code{graph.py} of the support code.}
  7953. %
  7954. As an aside, a topological ordering is only guaranteed to exist if the
  7955. graph does not contain any cycles. This is the case for the
  7956. control-flow graphs that we generate from \LangIf{} programs.
  7957. However, in Chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  7958. and learn how to handle cycles in the control-flow graph.
  7959. \racket{You'll need to construct a directed graph to represent the
  7960. control-flow graph. Do not use the \code{directed-graph} of the
  7961. \code{graph} package because that only allows at most one edge
  7962. between each pair of vertices, but a control-flow graph may have
  7963. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  7964. file in the support code implements a graph representation that
  7965. allows multiple edges between a pair of vertices.}
  7966. {\if\edition\racketEd
  7967. The next question is how to analyze jump instructions. Recall that in
  7968. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  7969. \code{label->live} that maps each label to the set of live locations
  7970. at the beginning of its block. We use \code{label->live} to determine
  7971. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  7972. that we have many basic blocks, \code{label->live} needs to be updated
  7973. as we process the blocks. In particular, after performing liveness
  7974. analysis on a block, we take the live-before set of its first
  7975. instruction and associate that with the block's label in the
  7976. \code{label->live}.
  7977. \fi}
  7978. %
  7979. {\if\edition\pythonEd
  7980. %
  7981. The next question is how to analyze jump instructions. The locations
  7982. that are live before a \code{jmp} should be the locations in
  7983. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  7984. maintaining a dictionary named \code{live\_before\_block} that maps each
  7985. label to the $L_{\mathtt{before}}$ for the first instruction in its
  7986. block. After performing liveness analysis on each block, we take the
  7987. live-before set of its first instruction and associate that with the
  7988. block's label in the \code{live\_before\_block} dictionary.
  7989. %
  7990. \fi}
  7991. In \LangXIfVar{} we also have the conditional jump
  7992. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  7993. this instruction is particularly interesting because, during
  7994. compilation, we do not know which way a conditional jump will go. So
  7995. we do not know whether to use the live-before set for the following
  7996. instruction or the live-before set for the block associated with the
  7997. $\itm{label}$. However, there is no harm to the correctness of the
  7998. generated code if we classify more locations as live than the ones
  7999. that are truly live during one particular execution of the
  8000. instruction. Thus, we can take the union of the live-before sets from
  8001. the following instruction and from the mapping for $\itm{label}$ in
  8002. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8003. The auxiliary functions for computing the variables in an
  8004. instruction's argument and for computing the variables read-from ($R$)
  8005. or written-to ($W$) by an instruction need to be updated to handle the
  8006. new kinds of arguments and instructions in \LangXIfVar{}.
  8007. \begin{exercise}\normalfont
  8008. {\if\edition\racketEd
  8009. %
  8010. Update the \code{uncover\_live} pass to apply liveness analysis to
  8011. every basic block in the program.
  8012. %
  8013. Add the following entry to the list of \code{passes} in the
  8014. \code{run-tests.rkt} script.
  8015. \begin{lstlisting}
  8016. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8017. \end{lstlisting}
  8018. \fi}
  8019. {\if\edition\pythonEd
  8020. %
  8021. Update the \code{uncover\_live} function to perform liveness analysis,
  8022. in reverse topological order, on all of the basic blocks in the
  8023. program.
  8024. %
  8025. \fi}
  8026. % Check that the live-after sets that you generate for
  8027. % example X matches the following... -Jeremy
  8028. \end{exercise}
  8029. \subsection{Build the Interference Graph}
  8030. \label{sec:build-interference-Lif}
  8031. Many of the new instructions in \LangXIfVar{} can be handled in the
  8032. same way as the instructions in \LangXVar{}. Thus, if your code was
  8033. already quite general, it will not need to be changed to handle the
  8034. new instructions. If you code is not general enough, we recommend that
  8035. you change your code to be more general. For example, you can factor
  8036. out the computing of the the read and write sets for each kind of
  8037. instruction into auxiliary functions.
  8038. Note that the \key{movzbq} instruction requires some special care,
  8039. similar to the \key{movq} instruction. See rule number 1 in
  8040. Section~\ref{sec:build-interference}.
  8041. \begin{exercise}\normalfont
  8042. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8043. {\if\edition\racketEd
  8044. Add the following entries to the list of \code{passes} in the
  8045. \code{run-tests.rkt} script.
  8046. \begin{lstlisting}
  8047. (list "build_interference" build_interference interp-pseudo-x86-1)
  8048. (list "allocate_registers" allocate_registers interp-x86-1)
  8049. \end{lstlisting}
  8050. \fi}
  8051. % Check that the interference graph that you generate for
  8052. % example X matches the following graph G... -Jeremy
  8053. \end{exercise}
  8054. \section{Patch Instructions}
  8055. The new instructions \key{cmpq} and \key{movzbq} have some special
  8056. restrictions that need to be handled in the \code{patch\_instructions}
  8057. pass.
  8058. %
  8059. The second argument of the \key{cmpq} instruction must not be an
  8060. immediate value (such as an integer). So if you are comparing two
  8061. immediates, we recommend inserting a \key{movq} instruction to put the
  8062. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8063. one memory reference.
  8064. %
  8065. The second argument of the \key{movzbq} must be a register.
  8066. \begin{exercise}\normalfont
  8067. %
  8068. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8069. %
  8070. {\if\edition\racketEd
  8071. Add the following entry to the list of \code{passes} in
  8072. \code{run-tests.rkt} and then run this script to test your compiler.
  8073. \begin{lstlisting}
  8074. (list "patch_instructions" patch_instructions interp-x86-1)
  8075. \end{lstlisting}
  8076. \fi}
  8077. \end{exercise}
  8078. {\if\edition\pythonEd
  8079. \section{Prelude and Conclusion}
  8080. \label{sec:prelude-conclusion-cond}
  8081. The generation of the \code{main} function with its prelude and
  8082. conclusion must change to accomodate how the program now consists of
  8083. one or more basic blocks. After the prelude in \code{main}, jump to
  8084. the \code{start} block. Place the conclusion in a basic block labelled
  8085. with \code{conclusion}.
  8086. \fi}
  8087. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8088. \LangIf{} translated to x86, showing the results of
  8089. \code{explicate\_control}, \code{select\_instructions}, and the final
  8090. x86 assembly.
  8091. \begin{figure}[tbp]
  8092. {\if\edition\racketEd
  8093. \begin{tabular}{lll}
  8094. \begin{minipage}{0.4\textwidth}
  8095. % cond_test_20.rkt, eq_input.py
  8096. \begin{lstlisting}
  8097. (if (eq? (read) 1) 42 0)
  8098. \end{lstlisting}
  8099. $\Downarrow$
  8100. \begin{lstlisting}
  8101. start:
  8102. tmp7951 = (read);
  8103. if (eq? tmp7951 1)
  8104. goto block7952;
  8105. else
  8106. goto block7953;
  8107. block7952:
  8108. return 42;
  8109. block7953:
  8110. return 0;
  8111. \end{lstlisting}
  8112. $\Downarrow$
  8113. \begin{lstlisting}
  8114. start:
  8115. callq read_int
  8116. movq %rax, tmp7951
  8117. cmpq $1, tmp7951
  8118. je block7952
  8119. jmp block7953
  8120. block7953:
  8121. movq $0, %rax
  8122. jmp conclusion
  8123. block7952:
  8124. movq $42, %rax
  8125. jmp conclusion
  8126. \end{lstlisting}
  8127. \end{minipage}
  8128. &
  8129. $\Rightarrow\qquad$
  8130. \begin{minipage}{0.4\textwidth}
  8131. \begin{lstlisting}
  8132. start:
  8133. callq read_int
  8134. movq %rax, %rcx
  8135. cmpq $1, %rcx
  8136. je block7952
  8137. jmp block7953
  8138. block7953:
  8139. movq $0, %rax
  8140. jmp conclusion
  8141. block7952:
  8142. movq $42, %rax
  8143. jmp conclusion
  8144. .globl main
  8145. main:
  8146. pushq %rbp
  8147. movq %rsp, %rbp
  8148. pushq %r13
  8149. pushq %r12
  8150. pushq %rbx
  8151. pushq %r14
  8152. subq $0, %rsp
  8153. jmp start
  8154. conclusion:
  8155. addq $0, %rsp
  8156. popq %r14
  8157. popq %rbx
  8158. popq %r12
  8159. popq %r13
  8160. popq %rbp
  8161. retq
  8162. \end{lstlisting}
  8163. \end{minipage}
  8164. \end{tabular}
  8165. \fi}
  8166. {\if\edition\pythonEd
  8167. \begin{tabular}{lll}
  8168. \begin{minipage}{0.4\textwidth}
  8169. % cond_test_20.rkt, eq_input.py
  8170. \begin{lstlisting}
  8171. print(42 if input_int() == 1 else 0)
  8172. \end{lstlisting}
  8173. $\Downarrow$
  8174. \begin{lstlisting}
  8175. start:
  8176. tmp_0 = input_int()
  8177. if tmp_0 == 1:
  8178. goto block_3
  8179. else:
  8180. goto block_4
  8181. block_3:
  8182. tmp_1 = 42
  8183. goto block_2
  8184. block_4:
  8185. tmp_1 = 0
  8186. goto block_2
  8187. block_2:
  8188. print(tmp_1)
  8189. return 0
  8190. \end{lstlisting}
  8191. $\Downarrow$
  8192. \begin{lstlisting}
  8193. start:
  8194. callq read_int
  8195. movq %rax, tmp_0
  8196. cmpq 1, tmp_0
  8197. je block_3
  8198. jmp block_4
  8199. block_3:
  8200. movq 42, tmp_1
  8201. jmp block_2
  8202. block_4:
  8203. movq 0, tmp_1
  8204. jmp block_2
  8205. block_2:
  8206. movq tmp_1, %rdi
  8207. callq print_int
  8208. movq 0, %rax
  8209. jmp conclusion
  8210. \end{lstlisting}
  8211. \end{minipage}
  8212. &
  8213. $\Rightarrow\qquad$
  8214. \begin{minipage}{0.4\textwidth}
  8215. \begin{lstlisting}
  8216. .globl main
  8217. main:
  8218. pushq %rbp
  8219. movq %rsp, %rbp
  8220. subq $0, %rsp
  8221. jmp start
  8222. start:
  8223. callq read_int
  8224. movq %rax, %rcx
  8225. cmpq $1, %rcx
  8226. je block_3
  8227. jmp block_4
  8228. block_3:
  8229. movq $42, %rcx
  8230. jmp block_2
  8231. block_4:
  8232. movq $0, %rcx
  8233. jmp block_2
  8234. block_2:
  8235. movq %rcx, %rdi
  8236. callq print_int
  8237. movq $0, %rax
  8238. jmp conclusion
  8239. conclusion:
  8240. addq $0, %rsp
  8241. popq %rbp
  8242. retq
  8243. \end{lstlisting}
  8244. \end{minipage}
  8245. \end{tabular}
  8246. \fi}
  8247. \caption{Example compilation of an \key{if} expression to x86, showing
  8248. the results of \code{explicate\_control},
  8249. \code{select\_instructions}, and the final x86 assembly code. }
  8250. \label{fig:if-example-x86}
  8251. \end{figure}
  8252. \begin{figure}[tbp]
  8253. {\if\edition\racketEd
  8254. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8255. \node (Lif) at (0,2) {\large \LangIf{}};
  8256. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8257. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8258. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8259. \node (Lif-5) at (12,2) {\large \LangIfANF{}};
  8260. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8261. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8262. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8263. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8264. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8265. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8266. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8267. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8268. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8269. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8270. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8271. \path[->,bend left=15] (Lif-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8272. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  8273. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8274. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8275. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8276. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8277. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8278. \end{tikzpicture}
  8279. \fi}
  8280. {\if\edition\pythonEd
  8281. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8282. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8283. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8284. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8285. \node (C-1) at (3,0) {\large \LangCIf{}};
  8286. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8287. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8288. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8289. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8290. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8291. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8292. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8293. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8294. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8295. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8296. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8297. \end{tikzpicture}
  8298. \fi}
  8299. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8300. \label{fig:Lif-passes}
  8301. \end{figure}
  8302. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8303. compilation of \LangIf{}.
  8304. \section{Challenge: Optimize Blocks and Remove Jumps}
  8305. \label{sec:opt-jumps}
  8306. We discuss two optional challenges that involve optimizing the
  8307. control-flow of the program.
  8308. \subsection{Optimize Blocks}
  8309. The algorithm for \code{explicate\_control} that we discussed in
  8310. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8311. blocks. It does so in two different ways.
  8312. %
  8313. First, recall how in Figure~\ref{fig:explicate-control-s1-38},
  8314. \code{block\_4} consists of just a jump to \code{block\_2}. We created
  8315. a new basic block from a single \code{goto} statement, whereas we
  8316. could have simply returned the \code{goto} statement. We can solve
  8317. this problem by modifying the \code{create\_block} function to
  8318. recognize this situation.
  8319. Second, \code{explicate\_control} creates a basic block whenever a
  8320. continuation \emph{might} get used more than once (wheneven a
  8321. continuation is passed into two or more recursive calls). However,
  8322. just because a continuation might get used more than once, doesn't
  8323. mean it will. In fact, some continuation parameters may not be used
  8324. at all because we sometimes ignore them. For example, consider the
  8325. case for the constant \TRUE{} in \code{explicate\_pred}, where we
  8326. discard the \code{els} branch. So the question is how can we decide
  8327. whether to create a basic block?
  8328. The solution to this conundrum is to use \emph{lazy
  8329. evaluation}\index{subject}{lazy evaluation}~\citep{Friedman:1976aa}
  8330. to delay creating a basic block until the point in time where we know
  8331. it will be used.
  8332. %
  8333. {\if\edition\racketEd
  8334. %
  8335. Racket provides support for
  8336. lazy evaluation with the
  8337. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8338. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8339. \index{subject}{delay} creates a
  8340. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8341. expressions is postponed. When \key{(force}
  8342. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8343. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8344. result of $e_n$ is cached in the promise and returned. If \code{force}
  8345. is applied again to the same promise, then the cached result is
  8346. returned. If \code{force} is applied to an argument that is not a
  8347. promise, \code{force} simply returns the argument.
  8348. %
  8349. \fi}
  8350. %
  8351. {\if\edition\pythonEd
  8352. %
  8353. While Python does not provide direct support for lazy evaluation, it
  8354. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8355. by wrapping it inside a function with no parameters. We can
  8356. \emph{force} its evaluation by calling the function. However, in some
  8357. cases of \code{explicate\_pred}, etc., we will return a list of
  8358. statements and in other cases we will return a function that computes
  8359. a list of statements. We use the term \emph{promise} to refer to a
  8360. value that may or may not be delayed. To uniformly deal with
  8361. promises, we define the following \code{force} function that checks
  8362. whether its input is delayed (i.e. whether it is a function) and then
  8363. either 1) calls the function, or 2) returns the input.
  8364. \begin{lstlisting}
  8365. def force(promise):
  8366. if isinstance(promise, types.FunctionType):
  8367. return promise()
  8368. else:
  8369. return promise
  8370. \end{lstlisting}
  8371. %
  8372. \fi}
  8373. We use promises for the input and output of the functions
  8374. \code{explicate\_pred}, \code{explicate\_assign},
  8375. %
  8376. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8377. %
  8378. So instead of taking and returning lists of statments, they take and
  8379. return promises. Furthermore, when we come to a situation in which a
  8380. continuation might be used more than once, as in the case for
  8381. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8382. that creates a basic block for each continuation (if there is not
  8383. already one) and then returns a \code{goto} statement to that basic
  8384. block.
  8385. %
  8386. {\if\edition\racketEd
  8387. %
  8388. The following auxiliary function named \code{create\_block} accomplishes
  8389. this task. It begins with \code{delay} to create a promise. When
  8390. forced, this promise will force the original promise. If that returns
  8391. a \code{goto} (because the block was already added to the control-flow
  8392. graph), then we return the \code{goto}. Otherwise we add the block to
  8393. the control-flow graph with another auxiliary function named
  8394. \code{add-node}. That function returns the label for the new block,
  8395. which we use to create a \code{goto}.
  8396. \begin{lstlisting}
  8397. (define (create_block tail)
  8398. (delay
  8399. (define t (force tail))
  8400. (match t
  8401. [(Goto label) (Goto label)]
  8402. [else (Goto (add-node t))])))
  8403. \end{lstlisting}
  8404. \fi}
  8405. {\if\edition\pythonEd
  8406. %
  8407. Here's the new version of the \code{create\_block} auxiliary function
  8408. that works on promises and that checks whether the block consists of a
  8409. solitary \code{goto} statement.\\
  8410. \begin{minipage}{\textwidth}
  8411. \begin{lstlisting}
  8412. def create_block(promise, basic_blocks):
  8413. stmts = force(promise)
  8414. match stmts:
  8415. case [Goto(l)]:
  8416. return Goto(l)
  8417. case _:
  8418. label = label_name(generate_name('block'))
  8419. basic_blocks[label] = stmts
  8420. return Goto(label)
  8421. \end{lstlisting}
  8422. \end{minipage}
  8423. \fi}
  8424. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8425. \code{explicate\_control} on the example of the nested \code{if}
  8426. expressions with the two improvements discussed above. As you can
  8427. see, the number of basic blocks has been reduced from 10 blocks (see
  8428. Figure~\ref{fig:explicate-control-s1-38}) down to 6 blocks.
  8429. \begin{figure}[tbp]
  8430. {\if\edition\racketEd
  8431. \begin{tabular}{lll}
  8432. \begin{minipage}{0.4\textwidth}
  8433. % cond_test_41.rkt
  8434. \begin{lstlisting}
  8435. (let ([x (read)])
  8436. (let ([y (read)])
  8437. (if (if (< x 1)
  8438. (eq? x 0)
  8439. (eq? x 2))
  8440. (+ y 2)
  8441. (+ y 10))))
  8442. \end{lstlisting}
  8443. \end{minipage}
  8444. &
  8445. $\Rightarrow$
  8446. &
  8447. \begin{minipage}{0.55\textwidth}
  8448. \begin{lstlisting}
  8449. start:
  8450. x = (read);
  8451. y = (read);
  8452. if (< x 1) goto block40;
  8453. else goto block41;
  8454. block40:
  8455. if (eq? x 0) goto block38;
  8456. else goto block39;
  8457. block41:
  8458. if (eq? x 2) goto block38;
  8459. else goto block39;
  8460. block38:
  8461. return (+ y 2);
  8462. block39:
  8463. return (+ y 10);
  8464. \end{lstlisting}
  8465. \end{minipage}
  8466. \end{tabular}
  8467. \fi}
  8468. {\if\edition\pythonEd
  8469. \begin{tabular}{lll}
  8470. \begin{minipage}{0.4\textwidth}
  8471. % cond_test_41.rkt
  8472. \begin{lstlisting}
  8473. x = input_int()
  8474. y = input_int()
  8475. print(y + 2 \
  8476. if (x == 0 \
  8477. if x < 1 \
  8478. else x == 2) \
  8479. else y + 10)
  8480. \end{lstlisting}
  8481. \end{minipage}
  8482. &
  8483. $\Rightarrow$
  8484. &
  8485. \begin{minipage}{0.55\textwidth}
  8486. \begin{lstlisting}
  8487. start:
  8488. x = input_int()
  8489. y = input_int()
  8490. if x < 1:
  8491. goto block_4
  8492. else:
  8493. goto block_5
  8494. block_4:
  8495. if x == 0:
  8496. goto block_2
  8497. else:
  8498. goto block_3
  8499. block_5:
  8500. if x == 2:
  8501. goto block_2
  8502. else:
  8503. goto block_3
  8504. block_2:
  8505. tmp_0 = y + 2
  8506. goto block_1
  8507. block_3:
  8508. tmp_0 = y + 10
  8509. goto block_1
  8510. block_1:
  8511. print(tmp_0)
  8512. return 0
  8513. \end{lstlisting}
  8514. \end{minipage}
  8515. \end{tabular}
  8516. \fi}
  8517. \caption{Translation from \LangIf{} to \LangCIf{}
  8518. via the improved \code{explicate\_control}.}
  8519. \label{fig:explicate-control-challenge}
  8520. \end{figure}
  8521. %% Recall that in the example output of \code{explicate\_control} in
  8522. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8523. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8524. %% block. The first goal of this challenge assignment is to remove those
  8525. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8526. %% \code{explicate\_control} on the left and shows the result of bypassing
  8527. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8528. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8529. %% \code{block55}. The optimized code on the right of
  8530. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8531. %% \code{then} branch jumping directly to \code{block55}. The story is
  8532. %% similar for the \code{else} branch, as well as for the two branches in
  8533. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8534. %% have been optimized in this way, there are no longer any jumps to
  8535. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8536. %% \begin{figure}[tbp]
  8537. %% \begin{tabular}{lll}
  8538. %% \begin{minipage}{0.4\textwidth}
  8539. %% \begin{lstlisting}
  8540. %% block62:
  8541. %% tmp54 = (read);
  8542. %% if (eq? tmp54 2) then
  8543. %% goto block59;
  8544. %% else
  8545. %% goto block60;
  8546. %% block61:
  8547. %% tmp53 = (read);
  8548. %% if (eq? tmp53 0) then
  8549. %% goto block57;
  8550. %% else
  8551. %% goto block58;
  8552. %% block60:
  8553. %% goto block56;
  8554. %% block59:
  8555. %% goto block55;
  8556. %% block58:
  8557. %% goto block56;
  8558. %% block57:
  8559. %% goto block55;
  8560. %% block56:
  8561. %% return (+ 700 77);
  8562. %% block55:
  8563. %% return (+ 10 32);
  8564. %% start:
  8565. %% tmp52 = (read);
  8566. %% if (eq? tmp52 1) then
  8567. %% goto block61;
  8568. %% else
  8569. %% goto block62;
  8570. %% \end{lstlisting}
  8571. %% \end{minipage}
  8572. %% &
  8573. %% $\Rightarrow$
  8574. %% &
  8575. %% \begin{minipage}{0.55\textwidth}
  8576. %% \begin{lstlisting}
  8577. %% block62:
  8578. %% tmp54 = (read);
  8579. %% if (eq? tmp54 2) then
  8580. %% goto block55;
  8581. %% else
  8582. %% goto block56;
  8583. %% block61:
  8584. %% tmp53 = (read);
  8585. %% if (eq? tmp53 0) then
  8586. %% goto block55;
  8587. %% else
  8588. %% goto block56;
  8589. %% block56:
  8590. %% return (+ 700 77);
  8591. %% block55:
  8592. %% return (+ 10 32);
  8593. %% start:
  8594. %% tmp52 = (read);
  8595. %% if (eq? tmp52 1) then
  8596. %% goto block61;
  8597. %% else
  8598. %% goto block62;
  8599. %% \end{lstlisting}
  8600. %% \end{minipage}
  8601. %% \end{tabular}
  8602. %% \caption{Optimize jumps by removing trivial blocks.}
  8603. %% \label{fig:optimize-jumps}
  8604. %% \end{figure}
  8605. %% The name of this pass is \code{optimize-jumps}. We recommend
  8606. %% implementing this pass in two phases. The first phrase builds a hash
  8607. %% table that maps labels to possibly improved labels. The second phase
  8608. %% changes the target of each \code{goto} to use the improved label. If
  8609. %% the label is for a trivial block, then the hash table should map the
  8610. %% label to the first non-trivial block that can be reached from this
  8611. %% label by jumping through trivial blocks. If the label is for a
  8612. %% non-trivial block, then the hash table should map the label to itself;
  8613. %% we do not want to change jumps to non-trivial blocks.
  8614. %% The first phase can be accomplished by constructing an empty hash
  8615. %% table, call it \code{short-cut}, and then iterating over the control
  8616. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8617. %% then update the hash table, mapping the block's source to the target
  8618. %% of the \code{goto}. Also, the hash table may already have mapped some
  8619. %% labels to the block's source, to you must iterate through the hash
  8620. %% table and update all of those so that they instead map to the target
  8621. %% of the \code{goto}.
  8622. %% For the second phase, we recommend iterating through the $\Tail$ of
  8623. %% each block in the program, updating the target of every \code{goto}
  8624. %% according to the mapping in \code{short-cut}.
  8625. \begin{exercise}\normalfont
  8626. Implement the improvements to the \code{explicate\_control} pass.
  8627. Check that it removes trivial blocks in a few example programs. Then
  8628. check that your compiler still passes all of your tests.
  8629. \end{exercise}
  8630. \subsection{Remove Jumps}
  8631. There is an opportunity for removing jumps that is apparent in the
  8632. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8633. ends with a jump to \code{block\_4} and there are no other jumps to
  8634. \code{block\_4} in the rest of the program. In this situation we can
  8635. avoid the runtime overhead of this jump by merging \code{block\_4}
  8636. into the preceding block, in this case the \code{start} block.
  8637. Figure~\ref{fig:remove-jumps} shows the output of
  8638. \code{select\_instructions} on the left and the result of this
  8639. optimization on the right.
  8640. \begin{figure}[tbp]
  8641. {\if\edition\racketEd
  8642. \begin{tabular}{lll}
  8643. \begin{minipage}{0.5\textwidth}
  8644. % cond_test_20.rkt
  8645. \begin{lstlisting}
  8646. start:
  8647. callq read_int
  8648. movq %rax, tmp7951
  8649. cmpq $1, tmp7951
  8650. je block7952
  8651. jmp block7953
  8652. block7953:
  8653. movq $0, %rax
  8654. jmp conclusion
  8655. block7952:
  8656. movq $42, %rax
  8657. jmp conclusion
  8658. \end{lstlisting}
  8659. \end{minipage}
  8660. &
  8661. $\Rightarrow\qquad$
  8662. \begin{minipage}{0.4\textwidth}
  8663. \begin{lstlisting}
  8664. start:
  8665. callq read_int
  8666. movq %rax, tmp7951
  8667. cmpq $1, tmp7951
  8668. je block7952
  8669. movq $0, %rax
  8670. jmp conclusion
  8671. block7952:
  8672. movq $42, %rax
  8673. jmp conclusion
  8674. \end{lstlisting}
  8675. \end{minipage}
  8676. \end{tabular}
  8677. \fi}
  8678. {\if\edition\pythonEd
  8679. \begin{tabular}{lll}
  8680. \begin{minipage}{0.5\textwidth}
  8681. % cond_test_20.rkt
  8682. \begin{lstlisting}
  8683. start:
  8684. callq read_int
  8685. movq %rax, tmp_0
  8686. cmpq 1, tmp_0
  8687. je block_3
  8688. jmp block_4
  8689. block_3:
  8690. movq 42, tmp_1
  8691. jmp block_2
  8692. block_4:
  8693. movq 0, tmp_1
  8694. jmp block_2
  8695. block_2:
  8696. movq tmp_1, %rdi
  8697. callq print_int
  8698. movq 0, %rax
  8699. jmp conclusion
  8700. \end{lstlisting}
  8701. \end{minipage}
  8702. &
  8703. $\Rightarrow\qquad$
  8704. \begin{minipage}{0.4\textwidth}
  8705. \begin{lstlisting}
  8706. start:
  8707. callq read_int
  8708. movq %rax, tmp_0
  8709. cmpq 1, tmp_0
  8710. je block_3
  8711. movq 0, tmp_1
  8712. jmp block_2
  8713. block_3:
  8714. movq 42, tmp_1
  8715. jmp block_2
  8716. block_2:
  8717. movq tmp_1, %rdi
  8718. callq print_int
  8719. movq 0, %rax
  8720. jmp conclusion
  8721. \end{lstlisting}
  8722. \end{minipage}
  8723. \end{tabular}
  8724. \fi}
  8725. \caption{Merging basic blocks by removing unnecessary jumps.}
  8726. \label{fig:remove-jumps}
  8727. \end{figure}
  8728. \begin{exercise}\normalfont
  8729. %
  8730. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8731. into their preceding basic block, when there is only one preceding
  8732. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8733. %
  8734. {\if\edition\racketEd
  8735. In the \code{run-tests.rkt} script, add the following entry to the
  8736. list of \code{passes} between \code{allocate\_registers}
  8737. and \code{patch\_instructions}.
  8738. \begin{lstlisting}
  8739. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8740. \end{lstlisting}
  8741. \fi}
  8742. %
  8743. Run the script to test your compiler.
  8744. %
  8745. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8746. blocks on several test programs.
  8747. \end{exercise}
  8748. \section{Further Reading}
  8749. \label{sec:cond-further-reading}
  8750. The algorithm for the \code{explicate\_control} pass is based on the
  8751. the \code{explose-basic-blocks} pass in the course notes of
  8752. \citet{Dybvig:2010aa}.
  8753. %
  8754. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  8755. \citet{Appel:2003fk}, and is related to translations into continuation
  8756. passing
  8757. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  8758. %
  8759. The treatment of conditionals in the \code{explicate\_control} pass is
  8760. similar to short-cut boolean
  8761. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  8762. and the case-of-case transformation of \citet{PeytonJones:1998}.
  8763. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8764. \chapter{Loops and Dataflow Analysis}
  8765. \label{ch:Lwhile}
  8766. % TODO: define R'_8
  8767. % TODO: multi-graph
  8768. {\if\edition\racketEd
  8769. %
  8770. In this chapter we study two features that are the hallmarks of
  8771. imperative programming languages: loops and assignments to local
  8772. variables. The following example demonstrates these new features by
  8773. computing the sum of the first five positive integers.
  8774. % similar to loop_test_1.rkt
  8775. \begin{lstlisting}
  8776. (let ([sum 0])
  8777. (let ([i 5])
  8778. (begin
  8779. (while (> i 0)
  8780. (begin
  8781. (set! sum (+ sum i))
  8782. (set! i (- i 1))))
  8783. sum)))
  8784. \end{lstlisting}
  8785. The \code{while} loop consists of a condition and a
  8786. body\footnote{The \code{while} loop in particular is not a built-in
  8787. feature of the Racket language, but Racket includes many looping
  8788. constructs and it is straightforward to define \code{while} as a
  8789. macro.}. The body is evaluated repeatedly so long as the condition
  8790. remains true.
  8791. %
  8792. The \code{set!} consists of a variable and a right-hand-side
  8793. expression. The \code{set!} updates value of the variable to the
  8794. value of the right-hand-side.
  8795. %
  8796. The primary purpose of both the \code{while} loop and \code{set!} is
  8797. to cause side effects, so they do not have a meaningful result
  8798. value. Instead their result is the \code{\#<void>} value. The
  8799. expression \code{(void)} is an explicit way to create the
  8800. \code{\#<void>} value and it has type \code{Void}. The
  8801. \code{\#<void>} value can be passed around just like other values
  8802. inside an \LangLoop{} program and a \code{\#<void>} value can be
  8803. compared for equality with another \code{\#<void>} value. However,
  8804. there are no other operations specific to the the \code{\#<void>}
  8805. value in \LangLoop{}. In contrast, Racket defines the \code{void?}
  8806. predicate that returns \code{\#t} when applied to \code{\#<void>} and
  8807. \code{\#f} otherwise.
  8808. %
  8809. \footnote{Racket's \code{Void} type corresponds to what is called the
  8810. \code{Unit} type in the programming languages literature. Racket's
  8811. \code{Void} type is inhabited by a single value \code{\#<void>}
  8812. which corresponds to \code{unit} or \code{()} in the
  8813. literature~\citep{Pierce:2002hj}.}.
  8814. %
  8815. With the addition of side-effecting features such as \code{while} loop
  8816. and \code{set!}, it is helpful to also include in a language feature
  8817. for sequencing side effects: the \code{begin} expression. It consists
  8818. of one or more subexpressions that are evaluated left-to-right.
  8819. %
  8820. \fi}
  8821. {\if\edition\pythonEd
  8822. %
  8823. In this chapter we study loops, one of the hallmarks of imperative
  8824. programming languages. The following example demonstrates the
  8825. \code{while} loop by computing the sum of the first five positive
  8826. integers.
  8827. \begin{lstlisting}
  8828. sum = 0
  8829. i = 5
  8830. while i > 0:
  8831. sum = sum + i
  8832. i = i - 1
  8833. print(sum)
  8834. \end{lstlisting}
  8835. The \code{while} loop consists of a condition expression and a body (a
  8836. sequence of statements). The body is evaluated repeatedly so long as
  8837. the condition remains true.
  8838. %
  8839. \fi}
  8840. \section{The \LangLoop{} Language}
  8841. \newcommand{\LwhileGrammarRacket}{
  8842. \begin{array}{lcl}
  8843. \Type &::=& \key{Void}\\
  8844. \Exp &::=& \CSETBANG{\Var}{\Exp}
  8845. \MID \CBEGIN{\Exp\ldots}{\Exp}
  8846. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  8847. \end{array}
  8848. }
  8849. \newcommand{\LwhileASTRacket}{
  8850. \begin{array}{lcl}
  8851. \Type &::=& \key{Void}\\
  8852. \Exp &::=& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}\\
  8853. &\MID& \WHILE{\Exp}{\Exp} \MID \VOID{}
  8854. \end{array}
  8855. }
  8856. \newcommand{\LwhileGrammarPython}{
  8857. \begin{array}{rcl}
  8858. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  8859. \end{array}
  8860. }
  8861. \newcommand{\LwhileASTPython}{
  8862. \begin{array}{lcl}
  8863. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  8864. \end{array}
  8865. }
  8866. \begin{figure}[tp]
  8867. \centering
  8868. \fbox{
  8869. \begin{minipage}{0.96\textwidth}
  8870. \small
  8871. {\if\edition\racketEd
  8872. \[
  8873. \begin{array}{l}
  8874. \gray{\LintGrammarRacket{}} \\ \hline
  8875. \gray{\LvarGrammarRacket{}} \\ \hline
  8876. \gray{\LifGrammarRacket{}} \\ \hline
  8877. \LwhileGrammarRacket \\
  8878. \begin{array}{lcl}
  8879. \LangLoopM{} &::=& \Exp
  8880. \end{array}
  8881. \end{array}
  8882. \]
  8883. \fi}
  8884. {\if\edition\pythonEd
  8885. \[
  8886. \begin{array}{l}
  8887. \gray{\LintGrammarPython} \\ \hline
  8888. \gray{\LvarGrammarPython} \\ \hline
  8889. \gray{\LifGrammarPython} \\ \hline
  8890. \LwhileGrammarPython \\
  8891. \begin{array}{rcl}
  8892. \LangLoopM{} &::=& \Stmt^{*}
  8893. \end{array}
  8894. \end{array}
  8895. \]
  8896. \fi}
  8897. \end{minipage}
  8898. }
  8899. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-concrete-syntax}).}
  8900. \label{fig:Lwhile-concrete-syntax}
  8901. \end{figure}
  8902. \begin{figure}[tp]
  8903. \centering
  8904. \fbox{
  8905. \begin{minipage}{0.96\textwidth}
  8906. \small
  8907. {\if\edition\racketEd
  8908. \[
  8909. \begin{array}{l}
  8910. \gray{\LintOpAST} \\ \hline
  8911. \gray{\LvarASTRacket{}} \\ \hline
  8912. \gray{\LifASTRacket{}} \\ \hline
  8913. \LwhileASTRacket{} \\
  8914. \begin{array}{lcl}
  8915. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  8916. \end{array}
  8917. \end{array}
  8918. \]
  8919. \fi}
  8920. {\if\edition\pythonEd
  8921. \[
  8922. \begin{array}{l}
  8923. \gray{\LintASTPython} \\ \hline
  8924. \gray{\LvarASTPython} \\ \hline
  8925. \gray{\LifASTPython} \\ \hline
  8926. \LwhileASTPython \\
  8927. \begin{array}{lcl}
  8928. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  8929. \end{array}
  8930. \end{array}
  8931. \]
  8932. \fi}
  8933. \end{minipage}
  8934. }
  8935. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-syntax}).}
  8936. \label{fig:Lwhile-syntax}
  8937. \end{figure}
  8938. The concrete syntax of \LangLoop{} is defined in
  8939. Figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  8940. in Figure~\ref{fig:Lwhile-syntax}.
  8941. %
  8942. The definitional interpreter for \LangLoop{} is shown in
  8943. Figure~\ref{fig:interp-Rwhile}.
  8944. %
  8945. {\if\edition\racketEd
  8946. %
  8947. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  8948. and \code{Void} and we make changes to the cases for \code{Var} and
  8949. \code{Let} regarding variables. To support assignment to variables and
  8950. to make their lifetimes indefinite (see the second example in
  8951. Section~\ref{sec:assignment-scoping}), we box the value that is bound
  8952. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  8953. value.
  8954. %
  8955. Now to discuss the new cases. For \code{SetBang}, we lookup the
  8956. variable in the environment to obtain a boxed value and then we change
  8957. it using \code{set-box!} to the result of evaluating the right-hand
  8958. side. The result value of a \code{SetBang} is \code{void}.
  8959. %
  8960. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  8961. if the result is true, 2) evaluate the body.
  8962. The result value of a \code{while} loop is also \code{void}.
  8963. %
  8964. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  8965. subexpressions \itm{es} for their effects and then evaluates
  8966. and returns the result from \itm{body}.
  8967. %
  8968. The $\VOID{}$ expression produces the \code{void} value.
  8969. %
  8970. \fi}
  8971. {\if\edition\pythonEd
  8972. %
  8973. We add a new case for \code{While} in the \code{interp\_stmts}
  8974. function, where we repeatedly interpret the \code{body} so long as the
  8975. \code{test} expression remains true.
  8976. %
  8977. \fi}
  8978. \begin{figure}[tbp]
  8979. {\if\edition\racketEd
  8980. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8981. (define interp-Rwhile_class
  8982. (class interp-Rany_class
  8983. (super-new)
  8984. (define/override ((interp-exp env) e)
  8985. (define recur (interp-exp env))
  8986. (match e
  8987. [(SetBang x rhs)
  8988. (set-box! (lookup x env) (recur rhs))]
  8989. [(WhileLoop cnd body)
  8990. (define (loop)
  8991. (cond [(recur cnd) (recur body) (loop)]
  8992. [else (void)]))
  8993. (loop)]
  8994. [(Begin es body)
  8995. (for ([e es]) (recur e))
  8996. (recur body)]
  8997. [(Void) (void)]
  8998. [else ((super interp-exp env) e)]))
  8999. ))
  9000. (define (interp-Rwhile p)
  9001. (send (new interp-Rwhile_class) interp-program p))
  9002. \end{lstlisting}
  9003. \fi}
  9004. {\if\edition\pythonEd
  9005. \begin{lstlisting}
  9006. class InterpLwhile(InterpLif):
  9007. def interp_stmts(self, ss, env):
  9008. if len(ss) == 0:
  9009. return
  9010. match ss[0]:
  9011. case While(test, body, []):
  9012. while self.interp_exp(test, env):
  9013. self.interp_stmts(body, env)
  9014. return self.interp_stmts(ss[1:], env)
  9015. case _:
  9016. return super().interp_stmts(ss, env)
  9017. \end{lstlisting}
  9018. \fi}
  9019. \caption{Interpreter for \LangLoop{}.}
  9020. \label{fig:interp-Rwhile}
  9021. \end{figure}
  9022. The type checker for \LangLoop{} is defined in
  9023. Figure~\ref{fig:type-check-Rwhile}.
  9024. %
  9025. {\if\edition\racketEd
  9026. %
  9027. For \LangLoop{} we add a type named \code{Void} and the only value of
  9028. this type is the \code{void} value.
  9029. %
  9030. The type checking of the \code{SetBang} expression requires the type of
  9031. the variable and the right-hand-side to agree. The result type is
  9032. \code{Void}. For \code{while}, the condition must be a
  9033. \code{Boolean}. The result type is also \code{Void}. For
  9034. \code{Begin}, the result type is the type of its last subexpression.
  9035. %
  9036. \fi}
  9037. %
  9038. {\if\edition\pythonEd
  9039. %
  9040. A \code{while} loop is well typed if the type of the \code{test}
  9041. expression is \code{bool} and the statements in the \code{body} are
  9042. well typed.
  9043. %
  9044. \fi}
  9045. \begin{figure}[tbp]
  9046. {\if\edition\racketEd
  9047. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9048. (define type-check-Rwhile_class
  9049. (class type-check-Rany_class
  9050. (super-new)
  9051. (inherit check-type-equal?)
  9052. (define/override (type-check-exp env)
  9053. (lambda (e)
  9054. (define recur (type-check-exp env))
  9055. (match e
  9056. [(SetBang x rhs)
  9057. (define-values (rhs^ rhsT) (recur rhs))
  9058. (define varT (dict-ref env x))
  9059. (check-type-equal? rhsT varT e)
  9060. (values (SetBang x rhs^) 'Void)]
  9061. [(WhileLoop cnd body)
  9062. (define-values (cnd^ Tc) (recur cnd))
  9063. (check-type-equal? Tc 'Boolean e)
  9064. (define-values (body^ Tbody) ((type-check-exp env) body))
  9065. (values (WhileLoop cnd^ body^) 'Void)]
  9066. [(Begin es body)
  9067. (define-values (es^ ts)
  9068. (for/lists (l1 l2) ([e es]) (recur e)))
  9069. (define-values (body^ Tbody) (recur body))
  9070. (values (Begin es^ body^) Tbody)]
  9071. [else ((super type-check-exp env) e)])))
  9072. ))
  9073. (define (type-check-Rwhile p)
  9074. (send (new type-check-Rwhile_class) type-check-program p))
  9075. \end{lstlisting}
  9076. \fi}
  9077. {\if\edition\pythonEd
  9078. \begin{lstlisting}
  9079. class TypeCheckLwhile(TypeCheckLif):
  9080. def type_check_stmts(self, ss, env):
  9081. if len(ss) == 0:
  9082. return
  9083. match ss[0]:
  9084. case While(test, body, []):
  9085. test_t = self.type_check_exp(test, env)
  9086. check_type_equal(bool, test_t, test)
  9087. body_t = self.type_check_stmts(body, env)
  9088. return self.type_check_stmts(ss[1:], env)
  9089. case _:
  9090. return super().type_check_stmts(ss, env)
  9091. \end{lstlisting}
  9092. \fi}
  9093. \caption{Type checker for the \LangLoop{} language.}
  9094. \label{fig:type-check-Rwhile}
  9095. \end{figure}
  9096. {\if\edition\racketEd
  9097. %
  9098. At first glance, the translation of these language features to x86
  9099. seems straightforward because the \LangCIf{} intermediate language
  9100. already supports all of the ingredients that we need: assignment,
  9101. \code{goto}, conditional branching, and sequencing. However, there are
  9102. complications that arise which we discuss in the next section. After
  9103. that we introduce the changes necessary to the existing passes.
  9104. %
  9105. \fi}
  9106. {\if\edition\pythonEd
  9107. %
  9108. At first glance, the translation of \code{while} loops to x86 seems
  9109. straightforward because the \LangCIf{} intermediate language already
  9110. supports \code{goto} and conditional branching. However, there are
  9111. complications that arise which we discuss in the next section. After
  9112. that we introduce the changes necessary to the existing passes.
  9113. %
  9114. \fi}
  9115. \section{Cyclic Control Flow and Dataflow Analysis}
  9116. \label{sec:dataflow-analysis}
  9117. Up until this point the control-flow graphs of the programs generated
  9118. in \code{explicate\_control} were guaranteed to be acyclic. However,
  9119. each \code{while} loop introduces a cycle in the control-flow graph.
  9120. But does that matter?
  9121. %
  9122. Indeed it does. Recall that for register allocation, the compiler
  9123. performs liveness analysis to determine which variables can share the
  9124. same register. To accomplish this we analyzed the control-flow graph
  9125. in reverse topological order
  9126. (Section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9127. only well-defined for acyclic graphs.
  9128. Let us return to the example of computing the sum of the first five
  9129. positive integers. Here is the program after instruction selection but
  9130. before register allocation.
  9131. \begin{center}
  9132. {\if\edition\racketEd
  9133. \begin{minipage}{0.45\textwidth}
  9134. \begin{lstlisting}
  9135. (define (main) : Integer
  9136. mainstart:
  9137. movq $0, sum
  9138. movq $5, i
  9139. jmp block5
  9140. block5:
  9141. movq i, tmp3
  9142. cmpq tmp3, $0
  9143. jl block7
  9144. jmp block8
  9145. \end{lstlisting}
  9146. \end{minipage}
  9147. \begin{minipage}{0.45\textwidth}
  9148. \begin{lstlisting}
  9149. block7:
  9150. addq i, sum
  9151. movq $1, tmp4
  9152. negq tmp4
  9153. addq tmp4, i
  9154. jmp block5
  9155. block8:
  9156. movq $27, %rax
  9157. addq sum, %rax
  9158. jmp mainconclusion
  9159. )
  9160. \end{lstlisting}
  9161. \end{minipage}
  9162. \fi}
  9163. {\if\edition\pythonEd
  9164. \begin{minipage}{0.45\textwidth}
  9165. \begin{lstlisting}
  9166. mainstart:
  9167. movq $0, sum
  9168. movq $5, i
  9169. jmp block5
  9170. block5:
  9171. cmpq $0, i
  9172. jg block7
  9173. jmp block8
  9174. \end{lstlisting}
  9175. \end{minipage}
  9176. \begin{minipage}{0.45\textwidth}
  9177. \begin{lstlisting}
  9178. block7:
  9179. addq i, sum
  9180. subq $1, i
  9181. jmp block5
  9182. block8:
  9183. movq sum, %rdi
  9184. callq print_int
  9185. movq $0, %rax
  9186. jmp mainconclusion
  9187. \end{lstlisting}
  9188. \end{minipage}
  9189. \fi}
  9190. \end{center}
  9191. Recall that liveness analysis works backwards, starting at the end
  9192. of each function. For this example we could start with \code{block8}
  9193. because we know what is live at the beginning of the conclusion,
  9194. just \code{rax} and \code{rsp}. So the live-before set
  9195. for \code{block8} is $\{\ttm{rsp},\ttm{sum}\}$.
  9196. %
  9197. Next we might try to analyze \code{block5} or \code{block7}, but
  9198. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9199. we are stuck.
  9200. The way out of this impasse is to realize that we can compute an
  9201. under-approximation of the live-before set by starting with empty
  9202. live-after sets. By \emph{under-approximation}, we mean that the set
  9203. only contains variables that are live for some execution of the
  9204. program, but the set may be missing some variables. Next, the
  9205. under-approximations for each block can be improved by 1) updating the
  9206. live-after set for each block using the approximate live-before sets
  9207. from the other blocks and 2) perform liveness analysis again on each
  9208. block. In fact, by iterating this process, the under-approximations
  9209. eventually become the correct solutions!
  9210. %
  9211. This approach of iteratively analyzing a control-flow graph is
  9212. applicable to many static analysis problems and goes by the name
  9213. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9214. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9215. Washington.
  9216. Let us apply this approach to the above example. We use the empty set
  9217. for the initial live-before set for each block. Let $m_0$ be the
  9218. following mapping from label names to sets of locations (variables and
  9219. registers).
  9220. \begin{center}
  9221. \begin{lstlisting}
  9222. mainstart: {}, block5: {}, block7: {}, block8: {}
  9223. \end{lstlisting}
  9224. \end{center}
  9225. Using the above live-before approximations, we determine the
  9226. live-after for each block and then apply liveness analysis to each
  9227. block. This produces our next approximation $m_1$ of the live-before
  9228. sets.
  9229. \begin{center}
  9230. \begin{lstlisting}
  9231. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9232. \end{lstlisting}
  9233. \end{center}
  9234. For the second round, the live-after for \code{mainstart} is the
  9235. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9236. liveness analysis for \code{mainstart} computes the empty set. The
  9237. live-after for \code{block5} is the union of the live-before sets for
  9238. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9239. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9240. sum\}}. The live-after for \code{block7} is the live-before for
  9241. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9242. So the liveness analysis for \code{block7} remains \code{\{i,
  9243. sum\}}. Together these yield the following approximation $m_2$ of
  9244. the live-before sets.
  9245. \begin{center}
  9246. \begin{lstlisting}
  9247. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9248. \end{lstlisting}
  9249. \end{center}
  9250. In the preceding iteration, only \code{block5} changed, so we can
  9251. limit our attention to \code{mainstart} and \code{block7}, the two
  9252. blocks that jump to \code{block5}. As a result, the live-before sets
  9253. for \code{mainstart} and \code{block7} are updated to include
  9254. \code{rsp}, yielding the following approximation $m_3$.
  9255. \begin{center}
  9256. \begin{lstlisting}
  9257. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9258. \end{lstlisting}
  9259. \end{center}
  9260. Because \code{block7} changed, we analyze \code{block5} once more, but
  9261. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9262. our approximations have converged, so $m_3$ is the solution.
  9263. This iteration process is guaranteed to converge to a solution by the
  9264. Kleene Fixed-Point Theorem, a general theorem about functions on
  9265. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9266. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9267. elements, a least element $\bot$ (pronounced bottom), and a join
  9268. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9269. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9270. working with join semi-lattices.} When two elements are ordered $m_i
  9271. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9272. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9273. approximation than $m_i$. The bottom element $\bot$ represents the
  9274. complete lack of information, i.e., the worst approximation. The join
  9275. operator takes two lattice elements and combines their information,
  9276. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9277. bound}
  9278. A dataflow analysis typically involves two lattices: one lattice to
  9279. represent abstract states and another lattice that aggregates the
  9280. abstract states of all the blocks in the control-flow graph. For
  9281. liveness analysis, an abstract state is a set of locations. We form
  9282. the lattice $L$ by taking its elements to be sets of locations, the
  9283. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9284. set, and the join operator to be set union.
  9285. %
  9286. We form a second lattice $M$ by taking its elements to be mappings
  9287. from the block labels to sets of locations (elements of $L$). We
  9288. order the mappings point-wise, using the ordering of $L$. So given any
  9289. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9290. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9291. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9292. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9293. We can think of one iteration of liveness analysis applied to the
  9294. whole program as being a function $f$ on the lattice $M$. It takes a
  9295. mapping as input and computes a new mapping.
  9296. \[
  9297. f(m_i) = m_{i+1}
  9298. \]
  9299. Next let us think for a moment about what a final solution $m_s$
  9300. should look like. If we perform liveness analysis using the solution
  9301. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9302. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9303. \[
  9304. f(m_s) = m_s
  9305. \]
  9306. Furthermore, the solution should only include locations that are
  9307. forced to be there by performing liveness analysis on the program, so
  9308. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9309. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9310. monotone (better inputs produce better outputs), then the least fixed
  9311. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9312. chain} obtained by starting at $\bot$ and iterating $f$ as
  9313. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9314. \[
  9315. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9316. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9317. \]
  9318. When a lattice contains only finitely-long ascending chains, then
  9319. every Kleene chain tops out at some fixed point after some number of
  9320. iterations of $f$.
  9321. \[
  9322. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9323. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9324. \]
  9325. The liveness analysis is indeed a monotone function and the lattice
  9326. $M$ only has finitely-long ascending chains because there are only a
  9327. finite number of variables and blocks in the program. Thus we are
  9328. guaranteed that iteratively applying liveness analysis to all blocks
  9329. in the program will eventually produce the least fixed point solution.
  9330. Next let us consider dataflow analysis in general and discuss the
  9331. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9332. %
  9333. The algorithm has four parameters: the control-flow graph \code{G}, a
  9334. function \code{transfer} that applies the analysis to one block, the
  9335. \code{bottom} and \code{join} operator for the lattice of abstract
  9336. states. The algorithm begins by creating the bottom mapping,
  9337. represented by a hash table. It then pushes all of the nodes in the
  9338. control-flow graph onto the work list (a queue). The algorithm repeats
  9339. the \code{while} loop as long as there are items in the work list. In
  9340. each iteration, a node is popped from the work list and processed. The
  9341. \code{input} for the node is computed by taking the join of the
  9342. abstract states of all the predecessor nodes. The \code{transfer}
  9343. function is then applied to obtain the \code{output} abstract
  9344. state. If the output differs from the previous state for this block,
  9345. the mapping for this block is updated and its successor nodes are
  9346. pushed onto the work list.
  9347. Note that the \code{analyze\_dataflow} function is formulated as a
  9348. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9349. function come from the predecessor nodes in the control-flow
  9350. graph. However, liveness analysis is a \emph{backward} dataflow
  9351. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9352. function with the transpose of the control-flow graph.
  9353. \begin{figure}[tb]
  9354. {\if\edition\racketEd
  9355. \begin{lstlisting}
  9356. (define (analyze_dataflow G transfer bottom join)
  9357. (define mapping (make-hash))
  9358. (for ([v (in-vertices G)])
  9359. (dict-set! mapping v bottom))
  9360. (define worklist (make-queue))
  9361. (for ([v (in-vertices G)])
  9362. (enqueue! worklist v))
  9363. (define trans-G (transpose G))
  9364. (while (not (queue-empty? worklist))
  9365. (define node (dequeue! worklist))
  9366. (define input (for/fold ([state bottom])
  9367. ([pred (in-neighbors trans-G node)])
  9368. (join state (dict-ref mapping pred))))
  9369. (define output (transfer node input))
  9370. (cond [(not (equal? output (dict-ref mapping node)))
  9371. (dict-set! mapping node output)
  9372. (for ([v (in-neighbors G node)])
  9373. (enqueue! worklist v))]))
  9374. mapping)
  9375. \end{lstlisting}
  9376. \fi}
  9377. {\if\edition\pythonEd
  9378. \begin{lstlisting}
  9379. def analyze_dataflow(G, transfer, bottom, join):
  9380. trans_G = transpose(G)
  9381. mapping = {}
  9382. for v in G.vertices():
  9383. mapping[v] = bottom
  9384. worklist = deque()
  9385. for v in G.vertices():
  9386. worklist.append(v)
  9387. while worklist:
  9388. node = worklist.pop()
  9389. input = reduce(join, [mapping[v] for v in trans_G.adjacent(node)], bottom)
  9390. output = transfer(node, input)
  9391. if output != mapping[node]:
  9392. mapping[node] = output
  9393. for v in G.adjacent(node):
  9394. worklist.append(v)
  9395. \end{lstlisting}
  9396. \fi}
  9397. \caption{Generic work list algorithm for dataflow analysis}
  9398. \label{fig:generic-dataflow}
  9399. \end{figure}
  9400. {\if\edition\racketEd
  9401. \section{Mutable Variables \& Remove Complex Operands}
  9402. There is a subtle interaction between the addition of \code{set!}, the
  9403. \code{remove\_complex\_operands} pass, and the left-to-right order of
  9404. evaluation of Racket. Consider the following example.
  9405. \begin{lstlisting}
  9406. (let ([x 2])
  9407. (+ x (begin (set! x 40) x)))
  9408. \end{lstlisting}
  9409. The result of this program is \code{42} because the first read from
  9410. \code{x} produces \code{2} and the second produces \code{40}. However,
  9411. if we naively apply the \code{remove\_complex\_operands} pass to this
  9412. example we obtain the following program whose result is \code{80}!
  9413. \begin{lstlisting}
  9414. (let ([x 2])
  9415. (let ([tmp (begin (set! x 40) x)])
  9416. (+ x tmp)))
  9417. \end{lstlisting}
  9418. The problem is that, with mutable variables, the ordering between
  9419. reads and writes is important, and the
  9420. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9421. before the first read of \code{x}.
  9422. We recommend solving this problem by giving special treatment to reads
  9423. from mutable variables, that is, variables that occur on the left-hand
  9424. side of a \code{set!}. We mark each read from a mutable variable with
  9425. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9426. that the read operation is effectful in that it can produce different
  9427. results at different points in time. Let's apply this idea to the
  9428. following variation that also involves a variable that is not mutated.
  9429. % loop_test_24.rkt
  9430. \begin{lstlisting}
  9431. (let ([x 2])
  9432. (let ([y 0])
  9433. (+ y (+ x (begin (set! x 40) x)))))
  9434. \end{lstlisting}
  9435. We analyze the above program to discover that variable \code{x} is
  9436. mutable but \code{y} is not. We then transform the program as follows,
  9437. replacing each occurence of \code{x} with \code{(get! x)}.
  9438. \begin{lstlisting}
  9439. (let ([x 2])
  9440. (let ([y 0])
  9441. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9442. \end{lstlisting}
  9443. Now that we have a clear distinction between reads from mutable and
  9444. immutable variables, we can apply the \code{remove\_complex\_operands}
  9445. pass, where reads from immutable variables are still classified as
  9446. atomic expressions but reads from mutable variables are classified as
  9447. complex. Thus, \code{remove\_complex\_operands} yields the following
  9448. program.
  9449. \begin{lstlisting}
  9450. (let ([x 2])
  9451. (let ([y 0])
  9452. (+ y (let ([t1 (get! x)])
  9453. (let ([t2 (begin (set! x 40) (get! x))])
  9454. (+ t1 t2))))))
  9455. \end{lstlisting}
  9456. The temporary variable \code{t1} gets the value of \code{x} before the
  9457. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9458. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9459. do not generate a temporary variable for the occurence of \code{y}
  9460. because it's an immutable variable. We want to avoid such unnecessary
  9461. extra temporaries because they would needless increase the number of
  9462. variables, making it more likely for some of them to be spilled. The
  9463. result of this program is \code{42}, the same as the result prior to
  9464. \code{remove\_complex\_operands}.
  9465. The approach that we've sketched above requires only a small
  9466. modification to \code{remove\_complex\_operands} to handle
  9467. \code{get!}. However, it requires a new pass, called
  9468. \code{uncover-get!}, that we discuss in
  9469. Section~\ref{sec:uncover-get-bang}.
  9470. As an aside, this problematic interaction between \code{set!} and the
  9471. pass \code{remove\_complex\_operands} is particular to Racket and not
  9472. its predecessor, the Scheme language. The key difference is that
  9473. Scheme does not specify an order of evaluation for the arguments of an
  9474. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9475. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9476. would be correct results for the example program. Interestingly,
  9477. Racket is implemented on top of the Chez Scheme
  9478. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9479. presented in this section (using extra \code{let} bindings to control
  9480. the order of evaluation) is used in the translation from Racket to
  9481. Scheme~\citep{Flatt:2019tb}.
  9482. \fi} % racket
  9483. Having discussed the complications that arise from adding support for
  9484. assignment and loops, we turn to discussing the individual compilation
  9485. passes.
  9486. {\if\edition\racketEd
  9487. \section{Uncover \texttt{get!}}
  9488. \label{sec:uncover-get-bang}
  9489. The goal of this pass it to mark uses of mutable variables so that
  9490. \code{remove\_complex\_operands} can treat them as complex expressions
  9491. and thereby preserve their ordering relative to the side-effects in
  9492. other operands. So the first step is to collect all the mutable
  9493. variables. We recommend creating an auxilliary function for this,
  9494. named \code{collect-set!}, that recursively traverses expressions,
  9495. returning a set of all variables that occur on the left-hand side of a
  9496. \code{set!}. Here's an exerpt of its implementation.
  9497. \begin{center}
  9498. \begin{minipage}{\textwidth}
  9499. \begin{lstlisting}
  9500. (define (collect-set! e)
  9501. (match e
  9502. [(Var x) (set)]
  9503. [(Int n) (set)]
  9504. [(Let x rhs body)
  9505. (set-union (collect-set! rhs) (collect-set! body))]
  9506. [(SetBang var rhs)
  9507. (set-union (set var) (collect-set! rhs))]
  9508. ...))
  9509. \end{lstlisting}
  9510. \end{minipage}
  9511. \end{center}
  9512. By placing this pass after \code{uniquify}, we need not worry about
  9513. variable shadowing and our logic for \code{let} can remain simple, as
  9514. in the exerpt above.
  9515. The second step is to mark the occurences of the mutable variables
  9516. with the new \code{GetBang} AST node (\code{get!} in concrete
  9517. syntax). The following is an exerpt of the \code{uncover-get!-exp}
  9518. function, which takes two parameters: the set of mutable varaibles
  9519. \code{set!-vars}, and the expression \code{e} to be processed. The
  9520. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9521. mutable variable or leaves it alone if not.
  9522. \begin{center}
  9523. \begin{minipage}{\textwidth}
  9524. \begin{lstlisting}
  9525. (define ((uncover-get!-exp set!-vars) e)
  9526. (match e
  9527. [(Var x)
  9528. (if (set-member? set!-vars x)
  9529. (GetBang x)
  9530. (Var x))]
  9531. ...))
  9532. \end{lstlisting}
  9533. \end{minipage}
  9534. \end{center}
  9535. To wrap things up, define the \code{uncover-get!} function for
  9536. processing a whole program, using \code{collect-set!} to obtain the
  9537. set of mutable variables and then \code{uncover-get!-exp} to replace
  9538. their occurences with \code{GetBang}.
  9539. \fi}
  9540. \section{Remove Complex Operands}
  9541. \label{sec:rco-loop}
  9542. {\if\edition\racketEd
  9543. %
  9544. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9545. \code{while} are all complex expressions. The subexpressions of
  9546. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9547. %
  9548. \fi}
  9549. {\if\edition\pythonEd
  9550. %
  9551. The change needed for this pass is to add a case for the \code{while}
  9552. statement. The condition of a \code{while} loop is allowed to be a
  9553. complex expression, just like the condition of the \code{if}
  9554. statement.
  9555. %
  9556. \fi}
  9557. %
  9558. Figure~\ref{fig:Rwhile-anf-syntax} defines the output language
  9559. \LangLoopANF{} of this pass.
  9560. \begin{figure}[tp]
  9561. \centering
  9562. \fbox{
  9563. \begin{minipage}{0.96\textwidth}
  9564. \small
  9565. {\if\edition\racketEd
  9566. \[
  9567. \begin{array}{rcl}
  9568. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} } \MID \VOID{} \\
  9569. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9570. &\MID& \GETBANG{\Var}
  9571. \MID \SETBANG{\Var}{\Exp} \\
  9572. &\MID& \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9573. \MID \WHILE{\Exp}{\Exp} \\
  9574. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9575. \LangLoopANF &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9576. \end{array}
  9577. \]
  9578. \fi}
  9579. {\if\edition\pythonEd
  9580. \[
  9581. \begin{array}{rcl}
  9582. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9583. \Exp &::=& \Atm \MID \READ{} \\
  9584. &\MID& \BINOP{\itm{binaryop}}{\Atm}{\Atm} \MID \UNIOP{\key{unaryop}}{\Atm} \\
  9585. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9586. % &\MID& \LET{\Var}{\Exp}{\Exp}\\
  9587. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9588. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9589. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9590. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9591. \end{array}
  9592. \]
  9593. \fi}
  9594. \end{minipage}
  9595. }
  9596. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9597. \label{fig:Rwhile-anf-syntax}
  9598. \end{figure}
  9599. {\if\edition\racketEd
  9600. As usual, when a complex expression appears in a grammar position that
  9601. needs to be atomic, such as the argument of a primitive operator, we
  9602. must introduce a temporary variable and bind it to the complex
  9603. expression. This approach applies, unchanged, to handle the new
  9604. language forms. For example, in the following code there are two
  9605. \code{begin} expressions appearing as arguments to \code{+}. The
  9606. output of \code{rco\_exp} is shown below, in which the \code{begin}
  9607. expressions have been bound to temporary variables. Recall that
  9608. \code{let} expressions in \LangLoopANF{} are allowed to have
  9609. arbitrary expressions in their right-hand-side expression, so it is
  9610. fine to place \code{begin} there.
  9611. \begin{center}
  9612. \begin{minipage}{\textwidth}
  9613. \begin{lstlisting}
  9614. (let ([x0 10])
  9615. (let ([y1 0])
  9616. (+ (+ (begin (set! y1 (read)) x0)
  9617. (begin (set! x0 (read)) y1))
  9618. x0)))
  9619. |$\Rightarrow$|
  9620. (let ([x0 10])
  9621. (let ([y1 0])
  9622. (let ([tmp2 (begin (set! y1 (read)) x0)])
  9623. (let ([tmp3 (begin (set! x0 (read)) y1)])
  9624. (let ([tmp4 (+ tmp2 tmp3)])
  9625. (+ tmp4 x0))))))
  9626. \end{lstlisting}
  9627. \end{minipage}
  9628. \end{center}
  9629. \fi}
  9630. \section{Explicate Control \racket{and \LangCLoop{}}}
  9631. \label{sec:explicate-loop}
  9632. \newcommand{\CloopASTRacket}{
  9633. \begin{array}{lcl}
  9634. \Atm &::=& \VOID \\
  9635. \Stmt &::=& \READ{}\\
  9636. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9637. \end{array}
  9638. }
  9639. {\if\edition\racketEd
  9640. Recall that in the \code{explicate\_control} pass we define one helper
  9641. function for each kind of position in the program. For the \LangVar{}
  9642. language of integers and variables we needed kinds of positions:
  9643. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  9644. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  9645. yet another kind of position: effect position. Except for the last
  9646. subexpression, the subexpressions inside a \code{begin} are evaluated
  9647. only for their effect. Their result values are discarded. We can
  9648. generate better code by taking this fact into account.
  9649. The output language of \code{explicate\_control} is \LangCLoop{}
  9650. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9651. \LangCLam{}. The only syntactic difference is that \code{Call} and
  9652. \code{read} may also appear as statements. The most significant
  9653. difference between \LangCLam{} and \LangCLoop{} is that the
  9654. control-flow graphs of the later may contain cycles.
  9655. \begin{figure}[tp]
  9656. \fbox{
  9657. \begin{minipage}{0.96\textwidth}
  9658. \small
  9659. {\if\edition\racketEd
  9660. \[
  9661. \begin{array}{l}
  9662. \gray{\CvarASTRacket} \\ \hline
  9663. \gray{\CifASTRacket} \\ \hline
  9664. \CloopASTRacket \\
  9665. \begin{array}{lcl}
  9666. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9667. \end{array}
  9668. \end{array}
  9669. \]
  9670. \fi}
  9671. {\if\edition\pythonEd
  9672. UNDER CONSTRUCTION
  9673. \fi}
  9674. \end{minipage}
  9675. }
  9676. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  9677. \label{fig:c7-syntax}
  9678. \end{figure}
  9679. The new auxiliary function \code{explicate\_effect} takes an
  9680. expression (in an effect position) and a continuation. The function
  9681. returns a $\Tail$ that includes the generated code for the input
  9682. expression followed by the continuation. If the expression is
  9683. obviously pure, that is, never causes side effects, then the
  9684. expression can be removed, so the result is just the continuation.
  9685. %
  9686. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9687. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9688. the loop. Recursively process the \itm{body} (in effect position)
  9689. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9690. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9691. \itm{body'} as the then-branch and the continuation block as the
  9692. else-branch. The result should be added to the control-flow graph with
  9693. the label \itm{loop}. The result for the whole \code{while} loop is a
  9694. \code{goto} to the \itm{loop} label.
  9695. The auxiliary functions for tail, assignment, and predicate positions
  9696. need to be updated. The three new language forms, \code{while},
  9697. \code{set!}, and \code{begin}, can appear in assignment and tail
  9698. positions. Only \code{begin} may appear in predicate positions; the
  9699. other two have result type \code{Void}.
  9700. \fi}
  9701. %
  9702. {\if\edition\pythonEd
  9703. %
  9704. The output of this pass is the language \LangCIf{}. No new language
  9705. features are needed in the output because a \code{while} loop can be
  9706. expressed in terms of \code{goto} and \code{if} statements, which are
  9707. already in \LangCIf{}.
  9708. %
  9709. Add a case for the \code{while} statement to the
  9710. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  9711. the condition expression.
  9712. %
  9713. \fi}
  9714. {\if\edition\racketEd
  9715. \section{Select Instructions}
  9716. \label{sec:select-instructions-loop}
  9717. Only three small additions are needed in the
  9718. \code{select\_instructions} pass to handle the changes to
  9719. \LangCLoop{}. That is, a \code{Call} to \code{read} may now appear as a
  9720. stand-alone statement instead of only appearing on the right-hand
  9721. side of an assignment statement. The code generation is nearly
  9722. identical; just leave off the instruction for moving the result into
  9723. the left-hand side.
  9724. \fi}
  9725. \section{Register Allocation}
  9726. \label{sec:register-allocation-loop}
  9727. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9728. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9729. which complicates the liveness analysis needed for register
  9730. allocation.
  9731. \subsection{Liveness Analysis}
  9732. \label{sec:liveness-analysis-r8}
  9733. We recommend using the generic \code{analyze\_dataflow} function that
  9734. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9735. perform liveness analysis, replacing the code in
  9736. \code{uncover\_live} that processed the basic blocks in topological
  9737. order (Section~\ref{sec:liveness-analysis-Lif}).
  9738. The \code{analyze\_dataflow} function has four parameters.
  9739. \begin{enumerate}
  9740. \item The first parameter \code{G} should be a directed graph from the
  9741. \racket{
  9742. \code{racket/graph} package (see the sidebar in
  9743. Section~\ref{sec:build-interference})}
  9744. \python{\code{graph.py} file in the support code}
  9745. that represents the
  9746. control-flow graph.
  9747. \item The second parameter \code{transfer} is a function that applies
  9748. liveness analysis to a basic block. It takes two parameters: the
  9749. label for the block to analyze and the live-after set for that
  9750. block. The transfer function should return the live-before set for
  9751. the block.
  9752. %
  9753. \racket{Also, as a side-effect, it should update the block's
  9754. $\itm{info}$ with the liveness information for each instruction.}
  9755. %
  9756. \python{Also, as a side-effect, it should update the live-before and
  9757. live-after sets for each instruction.}
  9758. %
  9759. To implement the \code{transfer} function, you should be able to
  9760. reuse the code you already have for analyzing basic blocks.
  9761. \item The third and fourth parameters of \code{analyze\_dataflow} are
  9762. \code{bottom} and \code{join} for the lattice of abstract states,
  9763. i.e. sets of locations. The bottom of the lattice is the empty set
  9764. and the join operator is set union.
  9765. \end{enumerate}
  9766. \begin{figure}[p]
  9767. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9768. \node (Rfun) at (0,2) {\large \LangLoop{}};
  9769. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  9770. %\node (Rfun-3) at (6,2) {\large \LangLoop{}};
  9771. %\node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  9772. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  9773. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  9774. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  9775. \node (F1-4) at (6,2) {\large \LangLoop{}};
  9776. \node (F1-5) at (9,2) {\large \LangLoopANF{}};
  9777. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  9778. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  9779. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  9780. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  9781. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  9782. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  9783. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  9784. %% \path[->,bend left=15] (Rfun) edge [above] node
  9785. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  9786. \path[->,bend left=15] (Rfun) edge [above] node
  9787. {\ttfamily\footnotesize shrink} (Rfun-2);
  9788. \path[->,bend left=15] (Rfun-2) edge [above] node
  9789. {\ttfamily\footnotesize uniquify} (F1-4);
  9790. %% \path[->,bend left=15] (Rfun-3) edge [above] node
  9791. %% {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  9792. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9793. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  9794. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9795. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  9796. %% \path[->,bend right=15] (F1-2) edge [above] node
  9797. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  9798. %% \path[->,bend right=15] (F1-3) edge [above] node
  9799. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9800. \path[->,bend left=15] (F1-4) edge [above] node
  9801. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  9802. \path[->,bend left=15] (F1-5) edge [right] node
  9803. {\ttfamily\footnotesize explicate\_control} (C3-2);
  9804. \path[->,bend left=15] (C3-2) edge [left] node
  9805. {\ttfamily\footnotesize select\_instr.} (x86-2);
  9806. \path[->,bend right=15] (x86-2) edge [left] node
  9807. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9808. \path[->,bend right=15] (x86-2-1) edge [below] node
  9809. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  9810. \path[->,bend right=15] (x86-2-2) edge [left] node
  9811. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  9812. \path[->,bend left=15] (x86-3) edge [above] node
  9813. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  9814. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  9815. \end{tikzpicture}
  9816. \caption{Diagram of the passes for \LangLoop{}.}
  9817. \label{fig:Rwhile-passes}
  9818. \end{figure}
  9819. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  9820. for the compilation of \LangLoop{}.
  9821. % Further Reading: dataflow analysis
  9822. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9823. \chapter{Tuples and Garbage Collection}
  9824. \label{ch:Lvec}
  9825. \index{subject}{tuple}
  9826. \index{subject}{vector}
  9827. \index{subject}{allocate}
  9828. \index{subject}{heap allocate}
  9829. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  9830. %% all the IR grammars are spelled out! \\ --Jeremy}
  9831. %% \margincomment{\scriptsize Be more explicit about how to deal with
  9832. %% the root stack. \\ --Jeremy}
  9833. In this chapter we study the implementation of
  9834. tuples\racket{, called vectors in Racket}.
  9835. %
  9836. This language feature is the first of ours to use the computer's
  9837. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  9838. indefinite, that is, a tuple lives forever from the programmer's
  9839. viewpoint. Of course, from an implementer's viewpoint, it is important
  9840. to reclaim the space associated with a tuple when it is no longer
  9841. needed, which is why we also study \emph{garbage collection}
  9842. \index{garbage collection} techniques in this chapter.
  9843. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  9844. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  9845. language of Chapter~\ref{ch:Lwhile} with tuples.
  9846. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  9847. copying live objects back and forth between two halves of the
  9848. heap. The garbage collector requires coordination with the compiler so
  9849. that it can see all of the \emph{root} pointers, that is, pointers in
  9850. registers or on the procedure call stack.
  9851. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  9852. discuss all the necessary changes and additions to the compiler
  9853. passes, including a new compiler pass named \code{expose\_allocation}.
  9854. \section{The \LangVec{} Language}
  9855. \label{sec:r3}
  9856. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  9857. \LangVec{} and Figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  9858. %
  9859. \racket{The \LangVec{} language includes the forms: \code{vector} for
  9860. creating a tuple, \code{vector-ref} for reading an element of a
  9861. tuple, \code{vector-set!} for writing to an element of a tuple, and
  9862. \code{vector-length} for obtaining the number of elements of a
  9863. tuple.}
  9864. %
  9865. \python{The \LangVec{} language adds 1) tuple creation via a
  9866. comma-separated list of expressions, 2) accessing an element of a
  9867. tuple with the square bracket notation, i.e., \code{t[n]} returns
  9868. the nth element of the tuple \code{t}, 3) the \code{is} comparison
  9869. operator, and 4) obtaining the number of elements (the length) of a
  9870. tuple.}
  9871. %
  9872. The program below shows an example use of tuples. It creates a 3-tuple
  9873. \code{t} and a 1-tuple that is stored at index $2$ of the 3-tuple,
  9874. demonstrating that tuples are first-class values. The element at
  9875. index $1$ of \code{t} is \racket{\code{\#t}}\python{\code{True}}, so the
  9876. ``then'' branch of the \key{if} is taken. The element at index $0$ of
  9877. \code{t} is \code{40}, to which we add \code{2}, the element at index
  9878. $0$ of the 1-tuple. So the result of the program is \code{42}.
  9879. %
  9880. {\if\edition\racketEd
  9881. \begin{lstlisting}
  9882. (let ([t (vector 40 #t (vector 2))])
  9883. (if (vector-ref t 1)
  9884. (+ (vector-ref t 0)
  9885. (vector-ref (vector-ref t 2) 0))
  9886. 44))
  9887. \end{lstlisting}
  9888. \fi}
  9889. {\if\edition\pythonEd
  9890. \begin{lstlisting}
  9891. t = 40, True, (2,)
  9892. print( t[0] + t[2][0] if t[1] else 44 )
  9893. \end{lstlisting}
  9894. \fi}
  9895. \newcommand{\LtupGrammarRacket}{
  9896. \begin{array}{lcl}
  9897. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  9898. \Exp &::=& \LP\key{vector}\;\Exp\ldots\RP
  9899. \MID \LP\key{vector-length}\;\Exp\RP \\
  9900. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  9901. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  9902. \end{array}
  9903. }
  9904. \newcommand{\LtupASTRacket}{
  9905. \begin{array}{lcl}
  9906. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  9907. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  9908. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  9909. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  9910. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  9911. \end{array}
  9912. }
  9913. \newcommand{\LtupGrammarPython}{
  9914. \begin{array}{rcl}
  9915. \itm{cmp} &::= & \key{is} \\
  9916. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp} \MID \CLEN{\Exp}
  9917. \end{array}
  9918. }
  9919. \newcommand{\LtupASTPython}{
  9920. \begin{array}{lcl}
  9921. \itm{cmp} &::= & \code{Is()} \\
  9922. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  9923. &\MID& \LEN{\Exp}
  9924. \end{array}
  9925. }
  9926. \begin{figure}[tbp]
  9927. \centering
  9928. \fbox{
  9929. \begin{minipage}{0.96\textwidth}
  9930. {\if\edition\racketEd
  9931. \[
  9932. \begin{array}{l}
  9933. \gray{\LintGrammarRacket{}} \\ \hline
  9934. \gray{\LvarGrammarRacket{}} \\ \hline
  9935. \gray{\LifGrammarRacket{}} \\ \hline
  9936. \gray{\LwhileGrammarRacket} \\ \hline
  9937. \LtupGrammarRacket \\
  9938. \begin{array}{lcl}
  9939. \LangVecM{} &::=& \Exp
  9940. \end{array}
  9941. \end{array}
  9942. \]
  9943. \fi}
  9944. {\if\edition\pythonEd
  9945. \[
  9946. \begin{array}{l}
  9947. \gray{\LintGrammarPython{}} \\ \hline
  9948. \gray{\LvarGrammarPython{}} \\ \hline
  9949. \gray{\LifGrammarPython{}} \\ \hline
  9950. \gray{\LwhileGrammarPython} \\ \hline
  9951. \LtupGrammarPython \\
  9952. \begin{array}{rcl}
  9953. \LangVecM{} &::=& \Stmt^{*}
  9954. \end{array}
  9955. \end{array}
  9956. \]
  9957. \fi}
  9958. \end{minipage}
  9959. }
  9960. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  9961. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  9962. \label{fig:Lvec-concrete-syntax}
  9963. \end{figure}
  9964. \begin{figure}[tp]
  9965. \centering
  9966. \fbox{
  9967. \begin{minipage}{0.96\textwidth}
  9968. {\if\edition\racketEd
  9969. \[
  9970. \begin{array}{l}
  9971. \gray{\LintOpAST} \\ \hline
  9972. \gray{\LvarASTRacket{}} \\ \hline
  9973. \gray{\LifASTRacket{}} \\ \hline
  9974. \gray{\LwhileASTRacket{}} \\ \hline
  9975. \LtupASTRacket{} \\
  9976. \begin{array}{lcl}
  9977. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  9978. \end{array}
  9979. \end{array}
  9980. \]
  9981. \fi}
  9982. {\if\edition\pythonEd
  9983. \[
  9984. \begin{array}{l}
  9985. \gray{\LintASTPython} \\ \hline
  9986. \gray{\LvarASTPython} \\ \hline
  9987. \gray{\LifASTPython} \\ \hline
  9988. \gray{\LwhileASTPython} \\ \hline
  9989. \LtupASTPython \\
  9990. \begin{array}{lcl}
  9991. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9992. \end{array}
  9993. \end{array}
  9994. \]
  9995. \fi}
  9996. \end{minipage}
  9997. }
  9998. \caption{The abstract syntax of \LangVec{}.}
  9999. \label{fig:Lvec-syntax}
  10000. \end{figure}
  10001. Tuples raises several interesting new issues. First, variable binding
  10002. performs a shallow-copy when dealing with tuples, which means that
  10003. different variables can refer to the same tuple, that is, two
  10004. variables can be \emph{aliases}\index{subject}{alias} for the same
  10005. entity. Consider the following example in which both \code{t1} and
  10006. \code{t2} refer to the same tuple value but \code{t3} refers to a
  10007. different tuple value but with equal elements. The result of the
  10008. program is \code{42}.
  10009. \begin{center}
  10010. \begin{minipage}{0.96\textwidth}
  10011. {\if\edition\racketEd
  10012. \begin{lstlisting}
  10013. (let ([t1 (vector 3 7)])
  10014. (let ([t2 t1])
  10015. (let ([t3 (vector 3 7)])
  10016. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10017. 42
  10018. 0))))
  10019. \end{lstlisting}
  10020. \fi}
  10021. {\if\edition\pythonEd
  10022. \begin{lstlisting}
  10023. t1 = 3, 7
  10024. t2 = t1
  10025. t3 = 3, 7
  10026. print( 42 if (t1 is t2) and not (t1 is t3) else 0)
  10027. \end{lstlisting}
  10028. \fi}
  10029. \end{minipage}
  10030. \end{center}
  10031. {\if\edition\racketEd
  10032. Whether two variables are aliased or not affects what happens
  10033. when the underlying tuple is mutated\index{subject}{mutation}.
  10034. Consider the following example in which \code{t1} and \code{t2}
  10035. again refer to the same tuple value.
  10036. \begin{center}
  10037. \begin{minipage}{0.96\textwidth}
  10038. \begin{lstlisting}
  10039. (let ([t1 (vector 3 7)])
  10040. (let ([t2 t1])
  10041. (let ([_ (vector-set! t2 0 42)])
  10042. (vector-ref t1 0))))
  10043. \end{lstlisting}
  10044. \end{minipage}
  10045. \end{center}
  10046. The mutation through \code{t2} is visible when referencing the tuple
  10047. from \code{t1}, so the result of this program is \code{42}.
  10048. \fi}
  10049. The next issue concerns the lifetime of tuples. When does their
  10050. lifetime end? Notice that \LangVec{} does not include an operation
  10051. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10052. to any notion of static scoping.
  10053. %
  10054. {\if\edition\racketEd
  10055. %
  10056. For example, the following program returns \code{42} even though the
  10057. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10058. that reads from the vector it was bound to.
  10059. \begin{center}
  10060. \begin{minipage}{0.96\textwidth}
  10061. \begin{lstlisting}
  10062. (let ([v (vector (vector 44))])
  10063. (let ([x (let ([w (vector 42)])
  10064. (let ([_ (vector-set! v 0 w)])
  10065. 0))])
  10066. (+ x (vector-ref (vector-ref v 0) 0))))
  10067. \end{lstlisting}
  10068. \end{minipage}
  10069. \end{center}
  10070. \fi}
  10071. %
  10072. {\if\edition\pythonEd
  10073. %
  10074. For example, the following program returns \code{42} even though the
  10075. variable \code{x} goes out of scope when the function returns, prior
  10076. to reading the tuple element at index zero. (We study the compilation
  10077. of functions in Chapter~\ref{ch:Rfun}.)
  10078. %
  10079. \begin{center}
  10080. \begin{minipage}{0.96\textwidth}
  10081. \begin{lstlisting}
  10082. def f():
  10083. x = 42, 43
  10084. return x
  10085. t = f()
  10086. print( t[0] )
  10087. \end{lstlisting}
  10088. \end{minipage}
  10089. \end{center}
  10090. \fi}
  10091. %
  10092. From the perspective of programmer-observable behavior, tuples live
  10093. forever. Of course, if they really lived forever then many programs
  10094. would run out of memory. The language's runtime system must therefore
  10095. perform automatic garbage collection.
  10096. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10097. \LangVec{} language.
  10098. %
  10099. \racket{We define the \code{vector}, \code{vector-ref},
  10100. \code{vector-set!}, and \code{vector-length} operations for
  10101. \LangVec{} in terms of the corresponding operations in Racket. One
  10102. subtle point is that the \code{vector-set!} operation returns the
  10103. \code{\#<void>} value.}
  10104. %
  10105. \python{We define tuple creation, element access, and the \code{len}
  10106. operator for \LangVec{} in terms of the corresponding operations in
  10107. Python.}
  10108. \begin{figure}[tbp]
  10109. {\if\edition\racketEd
  10110. \begin{lstlisting}
  10111. (define interp-Lvec_class
  10112. (class interp-Lif_class
  10113. (super-new)
  10114. (define/override (interp-op op)
  10115. (match op
  10116. ['eq? (lambda (v1 v2)
  10117. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10118. (and (boolean? v1) (boolean? v2))
  10119. (and (vector? v1) (vector? v2))
  10120. (and (void? v1) (void? v2)))
  10121. (eq? v1 v2)]))]
  10122. ['vector vector]
  10123. ['vector-length vector-length]
  10124. ['vector-ref vector-ref]
  10125. ['vector-set! vector-set!]
  10126. [else (super interp-op op)]
  10127. ))
  10128. (define/override ((interp-exp env) e)
  10129. (define recur (interp-exp env))
  10130. (match e
  10131. [(HasType e t) (recur e)]
  10132. [(Void) (void)]
  10133. [else ((super interp-exp env) e)]
  10134. ))
  10135. ))
  10136. (define (interp-Lvec p)
  10137. (send (new interp-Lvec_class) interp-program p))
  10138. \end{lstlisting}
  10139. \fi}
  10140. %
  10141. {\if\edition\pythonEd
  10142. \begin{lstlisting}
  10143. class InterpLtup(InterpLwhile):
  10144. def interp_cmp(self, cmp):
  10145. match cmp:
  10146. case Is():
  10147. return lambda x, y: x is y
  10148. case _:
  10149. return super().interp_cmp(cmp)
  10150. def interp_exp(self, e, env):
  10151. match e:
  10152. case Tuple(es, Load()):
  10153. return tuple([self.interp_exp(e, env) for e in es])
  10154. case Subscript(tup, index, Load()):
  10155. t = self.interp_exp(tup, env)
  10156. n = self.interp_exp(index, env)
  10157. return t[n]
  10158. case _:
  10159. return super().interp_exp(e, env)
  10160. \end{lstlisting}
  10161. \fi}
  10162. \caption{Interpreter for the \LangVec{} language.}
  10163. \label{fig:interp-Lvec}
  10164. \end{figure}
  10165. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10166. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10167. we need to know which elements of the tuple are pointers (i.e. are
  10168. also tuple) for garbage collection purposes. We can obtain this
  10169. information during type checking. The type checker in
  10170. Figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10171. expression, it also
  10172. %
  10173. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10174. where $T$ is the vector's type.
  10175. To create the s-expression for the \code{Vector} type in
  10176. Figure~\ref{fig:type-check-Lvec}, we use the
  10177. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10178. operator} \code{,@} to insert the list \code{t*} without its usual
  10179. start and end parentheses. \index{subject}{unquote-slicing}}
  10180. %
  10181. \python{records the type of each tuple expression in a new field
  10182. named \code{has\_type}.}
  10183. \begin{figure}[tp]
  10184. {\if\edition\racketEd
  10185. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10186. (define type-check-Lvec_class
  10187. (class type-check-Lif_class
  10188. (super-new)
  10189. (inherit check-type-equal?)
  10190. (define/override (type-check-exp env)
  10191. (lambda (e)
  10192. (define recur (type-check-exp env))
  10193. (match e
  10194. [(Void) (values (Void) 'Void)]
  10195. [(Prim 'vector es)
  10196. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10197. (define t `(Vector ,@t*))
  10198. (values (HasType (Prim 'vector e*) t) t)]
  10199. [(Prim 'vector-ref (list e1 (Int i)))
  10200. (define-values (e1^ t) (recur e1))
  10201. (match t
  10202. [`(Vector ,ts ...)
  10203. (unless (and (0 . <= . i) (i . < . (length ts)))
  10204. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10205. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10206. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10207. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10208. (define-values (e-vec t-vec) (recur e1))
  10209. (define-values (e-arg^ t-arg) (recur arg))
  10210. (match t-vec
  10211. [`(Vector ,ts ...)
  10212. (unless (and (0 . <= . i) (i . < . (length ts)))
  10213. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10214. (check-type-equal? (list-ref ts i) t-arg e)
  10215. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10216. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10217. [(Prim 'vector-length (list e))
  10218. (define-values (e^ t) (recur e))
  10219. (match t
  10220. [`(Vector ,ts ...)
  10221. (values (Prim 'vector-length (list e^)) 'Integer)]
  10222. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10223. [(Prim 'eq? (list arg1 arg2))
  10224. (define-values (e1 t1) (recur arg1))
  10225. (define-values (e2 t2) (recur arg2))
  10226. (match* (t1 t2)
  10227. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10228. [(other wise) (check-type-equal? t1 t2 e)])
  10229. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10230. [(HasType (Prim 'vector es) t)
  10231. ((type-check-exp env) (Prim 'vector es))]
  10232. [(HasType e1 t)
  10233. (define-values (e1^ t^) (recur e1))
  10234. (check-type-equal? t t^ e)
  10235. (values (HasType e1^ t) t)]
  10236. [else ((super type-check-exp env) e)]
  10237. )))
  10238. ))
  10239. (define (type-check-Lvec p)
  10240. (send (new type-check-Lvec_class) type-check-program p))
  10241. \end{lstlisting}
  10242. \fi}
  10243. {\if\edition\pythonEd
  10244. \begin{lstlisting}
  10245. class TypeCheckLtup(TypeCheckLwhile):
  10246. def type_check_exp(self, e, env):
  10247. match e:
  10248. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10249. l = self.type_check_exp(left, env)
  10250. r = self.type_check_exp(right, env)
  10251. check_type_equal(l, r, e)
  10252. return bool
  10253. case Tuple(es, Load()):
  10254. ts = [self.type_check_exp(e, env) for e in es]
  10255. e.has_type = tuple(ts)
  10256. return e.has_type
  10257. case Subscript(tup, Constant(index), Load()):
  10258. tup_ty = self.type_check_exp(tup, env)
  10259. index_ty = self.type_check_exp(Constant(index), env)
  10260. check_type_equal(index_ty, int, index)
  10261. match tup_ty:
  10262. case tuple(ts):
  10263. return ts[index]
  10264. case _:
  10265. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10266. case _:
  10267. return super().type_check_exp(e, env)
  10268. \end{lstlisting}
  10269. \fi}
  10270. \caption{Type checker for the \LangVec{} language.}
  10271. \label{fig:type-check-Lvec}
  10272. \end{figure}
  10273. \section{Garbage Collection}
  10274. \label{sec:GC}
  10275. Here we study a relatively simple algorithm for garbage collection
  10276. that is the basis of state-of-the-art garbage
  10277. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10278. particular, we describe a two-space copying
  10279. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10280. perform the
  10281. copy~\citep{Cheney:1970aa}.
  10282. \index{subject}{copying collector}
  10283. \index{subject}{two-space copying collector}
  10284. Figure~\ref{fig:copying-collector} gives a
  10285. coarse-grained depiction of what happens in a two-space collector,
  10286. showing two time steps, prior to garbage collection (on the top) and
  10287. after garbage collection (on the bottom). In a two-space collector,
  10288. the heap is divided into two parts named the FromSpace and the
  10289. ToSpace. Initially, all allocations go to the FromSpace until there is
  10290. not enough room for the next allocation request. At that point, the
  10291. garbage collector goes to work to make more room.
  10292. \index{subject}{ToSpace}
  10293. \index{subject}{FromSpace}
  10294. The garbage collector must be careful not to reclaim tuples that will
  10295. be used by the program in the future. Of course, it is impossible in
  10296. general to predict what a program will do, but we can over approximate
  10297. the will-be-used tuples by preserving all tuples that could be
  10298. accessed by \emph{any} program given the current computer state. A
  10299. program could access any tuple whose address is in a register or on
  10300. the procedure call stack. These addresses are called the \emph{root
  10301. set}\index{subject}{root set}. In addition, a program could access any tuple that is
  10302. transitively reachable from the root set. Thus, it is safe for the
  10303. garbage collector to reclaim the tuples that are not reachable in this
  10304. way.
  10305. So the goal of the garbage collector is twofold:
  10306. \begin{enumerate}
  10307. \item preserve all tuple that are reachable from the root set via a
  10308. path of pointers, that is, the \emph{live} tuples, and
  10309. \item reclaim the memory of everything else, that is, the
  10310. \emph{garbage}.
  10311. \end{enumerate}
  10312. A copying collector accomplishes this by copying all of the live
  10313. objects from the FromSpace into the ToSpace and then performs a sleight
  10314. of hand, treating the ToSpace as the new FromSpace and the old
  10315. FromSpace as the new ToSpace. In the example of
  10316. Figure~\ref{fig:copying-collector}, there are three pointers in the
  10317. root set, one in a register and two on the stack. All of the live
  10318. objects have been copied to the ToSpace (the right-hand side of
  10319. Figure~\ref{fig:copying-collector}) in a way that preserves the
  10320. pointer relationships. For example, the pointer in the register still
  10321. points to a 2-tuple whose first element is a 3-tuple and whose second
  10322. element is a 2-tuple. There are four tuples that are not reachable
  10323. from the root set and therefore do not get copied into the ToSpace.
  10324. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  10325. created by a well-typed program in \LangVec{} because it contains a
  10326. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  10327. We design the garbage collector to deal with cycles to begin with so
  10328. we will not need to revisit this issue.
  10329. \begin{figure}[tbp]
  10330. \centering
  10331. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  10332. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  10333. \caption{A copying collector in action.}
  10334. \label{fig:copying-collector}
  10335. \end{figure}
  10336. There are many alternatives to copying collectors (and their bigger
  10337. siblings, the generational collectors) when its comes to garbage
  10338. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  10339. reference counting~\citep{Collins:1960aa}. The strengths of copying
  10340. collectors are that allocation is fast (just a comparison and pointer
  10341. increment), there is no fragmentation, cyclic garbage is collected,
  10342. and the time complexity of collection only depends on the amount of
  10343. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  10344. main disadvantages of a two-space copying collector is that it uses a
  10345. lot of space and takes a long time to perform the copy, though these
  10346. problems are ameliorated in generational collectors. Racket and
  10347. Scheme programs tend to allocate many small objects and generate a lot
  10348. of garbage, so copying and generational collectors are a good fit.
  10349. Garbage collection is an active research topic, especially concurrent
  10350. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  10351. developing new techniques and revisiting old
  10352. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  10353. meet every year at the International Symposium on Memory Management to
  10354. present these findings.
  10355. \subsection{Graph Copying via Cheney's Algorithm}
  10356. \label{sec:cheney}
  10357. \index{subject}{Cheney's algorithm}
  10358. Let us take a closer look at the copying of the live objects. The
  10359. allocated objects and pointers can be viewed as a graph and we need to
  10360. copy the part of the graph that is reachable from the root set. To
  10361. make sure we copy all of the reachable vertices in the graph, we need
  10362. an exhaustive graph traversal algorithm, such as depth-first search or
  10363. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10364. such algorithms take into account the possibility of cycles by marking
  10365. which vertices have already been visited, so as to ensure termination
  10366. of the algorithm. These search algorithms also use a data structure
  10367. such as a stack or queue as a to-do list to keep track of the vertices
  10368. that need to be visited. We use breadth-first search and a trick
  10369. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10370. and copying tuples into the ToSpace.
  10371. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10372. copy progresses. The queue is represented by a chunk of contiguous
  10373. memory at the beginning of the ToSpace, using two pointers to track
  10374. the front and the back of the queue. The algorithm starts by copying
  10375. all tuples that are immediately reachable from the root set into the
  10376. ToSpace to form the initial queue. When we copy a tuple, we mark the
  10377. old tuple to indicate that it has been visited. We discuss how this
  10378. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  10379. pointers inside the copied tuples in the queue still point back to the
  10380. FromSpace. Once the initial queue has been created, the algorithm
  10381. enters a loop in which it repeatedly processes the tuple at the front
  10382. of the queue and pops it off the queue. To process a tuple, the
  10383. algorithm copies all the tuple that are directly reachable from it to
  10384. the ToSpace, placing them at the back of the queue. The algorithm then
  10385. updates the pointers in the popped tuple so they point to the newly
  10386. copied tuples.
  10387. \begin{figure}[tbp]
  10388. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  10389. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10390. \label{fig:cheney}
  10391. \end{figure}
  10392. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  10393. tuple whose second element is $42$ to the back of the queue. The other
  10394. pointer goes to a tuple that has already been copied, so we do not
  10395. need to copy it again, but we do need to update the pointer to the new
  10396. location. This can be accomplished by storing a \emph{forwarding
  10397. pointer} to the new location in the old tuple, back when we initially
  10398. copied the tuple into the ToSpace. This completes one step of the
  10399. algorithm. The algorithm continues in this way until the front of the
  10400. queue is empty, that is, until the front catches up with the back.
  10401. \subsection{Data Representation}
  10402. \label{sec:data-rep-gc}
  10403. The garbage collector places some requirements on the data
  10404. representations used by our compiler. First, the garbage collector
  10405. needs to distinguish between pointers and other kinds of data. There
  10406. are several ways to accomplish this.
  10407. \begin{enumerate}
  10408. \item Attached a tag to each object that identifies what type of
  10409. object it is~\citep{McCarthy:1960dz}.
  10410. \item Store different types of objects in different
  10411. regions~\citep{Steele:1977ab}.
  10412. \item Use type information from the program to either generate
  10413. type-specific code for collecting or to generate tables that can
  10414. guide the
  10415. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10416. \end{enumerate}
  10417. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10418. need to tag objects anyways, so option 1 is a natural choice for those
  10419. languages. However, \LangVec{} is a statically typed language, so it
  10420. would be unfortunate to require tags on every object, especially small
  10421. and pervasive objects like integers and Booleans. Option 3 is the
  10422. best-performing choice for statically typed languages, but comes with
  10423. a relatively high implementation complexity. To keep this chapter
  10424. within a 2-week time budget, we recommend a combination of options 1
  10425. and 2, using separate strategies for the stack and the heap.
  10426. Regarding the stack, we recommend using a separate stack for pointers,
  10427. which we call a \emph{root stack}\index{subject}{root stack}
  10428. (a.k.a. ``shadow
  10429. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10430. is, when a local variable needs to be spilled and is of type
  10431. \racket{\code{Vector}}\python{\code{TupleType}}, then we put it on the
  10432. root stack instead of the normal procedure call stack. Furthermore, we
  10433. always spill tuple-typed variables if they are live during a call to
  10434. the collector, thereby ensuring that no pointers are in registers
  10435. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  10436. example from Figure~\ref{fig:copying-collector} and contrasts it with
  10437. the data layout using a root stack. The root stack contains the two
  10438. pointers from the regular stack and also the pointer in the second
  10439. register.
  10440. \begin{figure}[tbp]
  10441. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  10442. \caption{Maintaining a root stack to facilitate garbage collection.}
  10443. \label{fig:shadow-stack}
  10444. \end{figure}
  10445. The problem of distinguishing between pointers and other kinds of data
  10446. also arises inside of each tuple on the heap. We solve this problem by
  10447. attaching a tag, an extra 64-bits, to each
  10448. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10449. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  10450. that we have drawn the bits in a big-endian way, from right-to-left,
  10451. with bit location 0 (the least significant bit) on the far right,
  10452. which corresponds to the direction of the x86 shifting instructions
  10453. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10454. is dedicated to specifying which elements of the tuple are pointers,
  10455. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10456. indicates there is a pointer and a 0 bit indicates some other kind of
  10457. data. The pointer mask starts at bit location 7. We have limited
  10458. tuples to a maximum size of 50 elements, so we just need 50 bits for
  10459. the pointer mask. The tag also contains two other pieces of
  10460. information. The length of the tuple (number of elements) is stored in
  10461. bits location 1 through 6. Finally, the bit at location 0 indicates
  10462. whether the tuple has yet to be copied to the ToSpace. If the bit has
  10463. value 1, then this tuple has not yet been copied. If the bit has
  10464. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  10465. of a pointer are always zero anyways because our tuples are 8-byte
  10466. aligned.)
  10467. \begin{figure}[tbp]
  10468. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10469. \caption{Representation of tuples in the heap.}
  10470. \label{fig:tuple-rep}
  10471. \end{figure}
  10472. \subsection{Implementation of the Garbage Collector}
  10473. \label{sec:organize-gz}
  10474. \index{subject}{prelude}
  10475. An implementation of the copying collector is provided in the
  10476. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10477. interface to the garbage collector that is used by the compiler. The
  10478. \code{initialize} function creates the FromSpace, ToSpace, and root
  10479. stack and should be called in the prelude of the \code{main}
  10480. function. The arguments of \code{initialize} are the root stack size
  10481. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10482. good choice for both. The \code{initialize} function puts the address
  10483. of the beginning of the FromSpace into the global variable
  10484. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10485. the address that is 1-past the last element of the FromSpace. (We use
  10486. half-open intervals to represent chunks of
  10487. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  10488. points to the first element of the root stack.
  10489. As long as there is room left in the FromSpace, your generated code
  10490. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10491. %
  10492. The amount of room left in FromSpace is the difference between the
  10493. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10494. function should be called when there is not enough room left in the
  10495. FromSpace for the next allocation. The \code{collect} function takes
  10496. a pointer to the current top of the root stack (one past the last item
  10497. that was pushed) and the number of bytes that need to be
  10498. allocated. The \code{collect} function performs the copying collection
  10499. and leaves the heap in a state such that the next allocation will
  10500. succeed.
  10501. \begin{figure}[tbp]
  10502. \begin{lstlisting}
  10503. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10504. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10505. int64_t* free_ptr;
  10506. int64_t* fromspace_begin;
  10507. int64_t* fromspace_end;
  10508. int64_t** rootstack_begin;
  10509. \end{lstlisting}
  10510. \caption{The compiler's interface to the garbage collector.}
  10511. \label{fig:gc-header}
  10512. \end{figure}
  10513. %% \begin{exercise}
  10514. %% In the file \code{runtime.c} you will find the implementation of
  10515. %% \code{initialize} and a partial implementation of \code{collect}.
  10516. %% The \code{collect} function calls another function, \code{cheney},
  10517. %% to perform the actual copy, and that function is left to the reader
  10518. %% to implement. The following is the prototype for \code{cheney}.
  10519. %% \begin{lstlisting}
  10520. %% static void cheney(int64_t** rootstack_ptr);
  10521. %% \end{lstlisting}
  10522. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10523. %% rootstack (which is an array of pointers). The \code{cheney} function
  10524. %% also communicates with \code{collect} through the global
  10525. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10526. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  10527. %% the ToSpace:
  10528. %% \begin{lstlisting}
  10529. %% static int64_t* tospace_begin;
  10530. %% static int64_t* tospace_end;
  10531. %% \end{lstlisting}
  10532. %% The job of the \code{cheney} function is to copy all the live
  10533. %% objects (reachable from the root stack) into the ToSpace, update
  10534. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10535. %% update the root stack so that it points to the objects in the
  10536. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10537. %% and ToSpace.
  10538. %% \end{exercise}
  10539. %% \section{Compiler Passes}
  10540. %% \label{sec:code-generation-gc}
  10541. The introduction of garbage collection has a non-trivial impact on our
  10542. compiler passes. We introduce a new compiler pass named
  10543. \code{expose\_allocation}. We make significant changes to
  10544. \code{select\_instructions}, \code{build\_interference},
  10545. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10546. make minor changes in several more passes. The following program will
  10547. serve as our running example. It creates two tuples, one nested
  10548. inside the other. Both tuples have length one. The program accesses
  10549. the element in the inner tuple tuple.
  10550. % tests/vectors_test_17.rkt
  10551. {\if\edition\racketEd
  10552. \begin{lstlisting}
  10553. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10554. \end{lstlisting}
  10555. \fi}
  10556. {\if\edition\pythonEd
  10557. \begin{lstlisting}
  10558. print( ((42,),)[0][0] )
  10559. \end{lstlisting}
  10560. \fi}
  10561. {\if\edition\racketEd
  10562. \section{Shrink}
  10563. \label{sec:shrink-Lvec}
  10564. Recall that the \code{shrink} pass translates the primitives operators
  10565. into a smaller set of primitives.
  10566. %
  10567. This pass comes after type checking and the type checker adds a
  10568. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10569. need to add a case for \code{HasType} to the \code{shrink} pass.
  10570. \fi}
  10571. \section{Expose Allocation}
  10572. \label{sec:expose-allocation}
  10573. The pass \code{expose\_allocation} lowers tuple creation into a
  10574. conditional call to the collector followed by allocating the
  10575. appropriate amount of memory and initializing it. We choose to place
  10576. the \code{expose\_allocation} pass before
  10577. \code{remove\_complex\_operands} because the code generated by
  10578. \code{expose\_allocation} contains complex operands.
  10579. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10580. that extends \LangVec{} with new forms that we use in the translation
  10581. of tuple creation.
  10582. %
  10583. {\if\edition\racketEd
  10584. \[
  10585. \begin{array}{lcl}
  10586. \Exp &::=& \cdots
  10587. \MID (\key{collect} \,\itm{int})
  10588. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10589. \MID (\key{global-value} \,\itm{name})
  10590. \end{array}
  10591. \]
  10592. \fi}
  10593. {\if\edition\pythonEd
  10594. \[
  10595. \begin{array}{lcl}
  10596. \Exp &::=& \cdots\\
  10597. &\MID& \key{collect}(\itm{int})
  10598. \MID \key{allocate}(\itm{int},\itm{type})
  10599. \MID \key{global\_value}(\itm{name}) \\
  10600. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp
  10601. \end{array}
  10602. \]
  10603. \fi}
  10604. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10605. make sure that there are $n$ bytes ready to be allocated. During
  10606. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10607. the \code{collect} function in \code{runtime.c}.
  10608. %
  10609. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10610. space at the front for the 64 bit tag), but the elements are not
  10611. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10612. of the tuple:
  10613. %
  10614. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10615. %
  10616. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10617. \CGLOBAL{\itm{name}} form reads the value of a global variable, such
  10618. as \code{free\_ptr}.
  10619. %
  10620. \python{The \code{begin} form is an expression that executes a
  10621. sequence of statements and then produces the value of the expression
  10622. at the end.}
  10623. The following shows the transformation of tuple creation into 1) a
  10624. sequence of temporary variables bindings for the initializing
  10625. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10626. \code{allocate}, and 4) the initialization of the tuple. The
  10627. \itm{len} placeholder refers to the length of the tuple and
  10628. \itm{bytes} is how many total bytes need to be allocated for the
  10629. tuple, which is 8 for the tag plus \itm{len} times 8.
  10630. %
  10631. \python{The \itm{type} needed for the second argument of the
  10632. \code{allocate} form can be obtained from the \code{has\_type} field
  10633. of the tuple AST node, which is stored there by running the type
  10634. checker for \LangVec{} immediately before this pass.}
  10635. %
  10636. \begin{center}
  10637. \begin{minipage}{\textwidth}
  10638. {\if\edition\racketEd
  10639. \begin{lstlisting}
  10640. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10641. |$\Longrightarrow$|
  10642. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10643. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10644. (global-value fromspace_end))
  10645. (void)
  10646. (collect |\itm{bytes}|))])
  10647. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  10648. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  10649. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  10650. |$v$|) ... )))) ...)
  10651. \end{lstlisting}
  10652. \fi}
  10653. {\if\edition\pythonEd
  10654. \begin{lstlisting}
  10655. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  10656. |$\Longrightarrow$|
  10657. begin:
  10658. |$x_0$| = |$e_0$|
  10659. |$\vdots$|
  10660. |$x_{n-1}$| = |$e_{n-1}$|
  10661. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  10662. 0
  10663. else:
  10664. collect(|\itm{bytes}|)
  10665. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  10666. |$v$|[0] = |$x_0$|
  10667. |$\vdots$|
  10668. |$v$|[|$n-1$|] = |$x_{n-1}$|
  10669. |$v$|
  10670. \end{lstlisting}
  10671. \fi}
  10672. \end{minipage}
  10673. \end{center}
  10674. %
  10675. \noindent The sequencing of the initializing expressions
  10676. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  10677. they may trigger garbage collection and we cannot have an allocated
  10678. but uninitialized tuple on the heap during a collection.
  10679. Figure~\ref{fig:expose-alloc-output} shows the output of the
  10680. \code{expose\_allocation} pass on our running example.
  10681. \begin{figure}[tbp]
  10682. % tests/s2_17.rkt
  10683. {\if\edition\racketEd
  10684. \begin{lstlisting}
  10685. (vector-ref
  10686. (vector-ref
  10687. (let ([vecinit7976
  10688. (let ([vecinit7972 42])
  10689. (let ([collectret7974
  10690. (if (< (+ (global-value free_ptr) 16)
  10691. (global-value fromspace_end))
  10692. (void)
  10693. (collect 16)
  10694. )])
  10695. (let ([alloc7971 (allocate 1 (Vector Integer))])
  10696. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  10697. alloc7971))))])
  10698. (let ([collectret7978
  10699. (if (< (+ (global-value free_ptr) 16)
  10700. (global-value fromspace_end))
  10701. (void)
  10702. (collect 16)
  10703. )])
  10704. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  10705. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  10706. alloc7975))))
  10707. 0)
  10708. 0)
  10709. \end{lstlisting}
  10710. \fi}
  10711. {\if\edition\pythonEd
  10712. \begin{lstlisting}
  10713. print( |$T_1$|[0][0] )
  10714. \end{lstlisting}
  10715. where $T_1$ is
  10716. \begin{lstlisting}
  10717. begin:
  10718. tmp.1 = |$T_2$|
  10719. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10720. 0
  10721. else:
  10722. collect(16)
  10723. tmp.2 = allocate(1, TupleType(TupleType([int])))
  10724. tmp.2[0] = tmp.1
  10725. tmp.2
  10726. \end{lstlisting}
  10727. and $T_2$ is
  10728. \begin{lstlisting}
  10729. begin:
  10730. tmp.3 = 42
  10731. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10732. 0
  10733. else:
  10734. collect(16)
  10735. tmp.4 = allocate(1, TupleType([int]))
  10736. tmp.4[0] = tmp.3
  10737. tmp.4
  10738. \end{lstlisting}
  10739. \fi}
  10740. \caption{Output of the \code{expose\_allocation} pass.}
  10741. \label{fig:expose-alloc-output}
  10742. \end{figure}
  10743. \section{Remove Complex Operands}
  10744. \label{sec:remove-complex-opera-Lvec}
  10745. {\if\edition\racketEd
  10746. %
  10747. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  10748. should be treated as complex operands.
  10749. %
  10750. \fi}
  10751. %
  10752. {\if\edition\pythonEd
  10753. %
  10754. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  10755. and tuple access should be treated as complex operands. The
  10756. sub-expressions of tuple access must be atomic.
  10757. %
  10758. \fi}
  10759. %% A new case for
  10760. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  10761. %% handled carefully to prevent the \code{Prim} node from being separated
  10762. %% from its enclosing \code{HasType}.
  10763. Figure~\ref{fig:Lvec-anf-syntax}
  10764. shows the grammar for the output language \LangAllocANF{} of this
  10765. pass, which is \LangAlloc{} in monadic normal form.
  10766. \begin{figure}[tp]
  10767. \centering
  10768. \fbox{
  10769. \begin{minipage}{0.96\textwidth}
  10770. \small
  10771. {\if\edition\racketEd
  10772. \[
  10773. \begin{array}{rcl}
  10774. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  10775. \MID \VOID{} } \\
  10776. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  10777. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  10778. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10779. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  10780. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  10781. &\MID& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  10782. \MID \GLOBALVALUE{\Var}\\
  10783. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  10784. \LangAllocANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10785. \end{array}
  10786. \]
  10787. \fi}
  10788. {\if\edition\pythonEd
  10789. \[
  10790. \begin{array}{lcl}
  10791. \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  10792. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  10793. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \MID \code{Is()} \\
  10794. \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  10795. \itm{bool} &::=& \code{True} \MID \code{False} \\
  10796. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  10797. \Exp &::=& \Atm \MID \READ{} \MID \\
  10798. &\MID& \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  10799. \MID \UNIOP{\itm{unaryop}}{\Exp}\\
  10800. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp}
  10801. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  10802. &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  10803. &\MID& \GET{\Atm}{\Atm} \\
  10804. &\MID& \LEN{\Exp}\\
  10805. &\MID& \ALLOCATE{\Int}{\Type}
  10806. \MID \GLOBALVALUE{\Var}\RP\\
  10807. &\MID& \BEGIN{\Stmt^{*}}{\Exp} \\
  10808. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  10809. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  10810. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Exp} \\
  10811. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10812. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}
  10813. \MID \COLLECT{\Int} \\
  10814. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10815. \end{array}
  10816. \]
  10817. \fi}
  10818. \end{minipage}
  10819. }
  10820. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  10821. \label{fig:Lvec-anf-syntax}
  10822. \end{figure}
  10823. \section{Explicate Control and the \LangCVec{} language}
  10824. \label{sec:explicate-control-r3}
  10825. \newcommand{\CtupASTRacket}{
  10826. \begin{array}{lcl}
  10827. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  10828. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  10829. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  10830. &\MID& \VECLEN{\Atm} \\
  10831. &\MID& \GLOBALVALUE{\Var} \\
  10832. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  10833. &\MID& \LP\key{Collect} \,\itm{int}\RP
  10834. \end{array}
  10835. }
  10836. \newcommand{\CtupASTPython}{
  10837. \begin{array}{lcl}
  10838. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  10839. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  10840. \Stmt &::=& \COLLECT{\Int} \\
  10841. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  10842. \end{array}
  10843. }
  10844. \begin{figure}[tp]
  10845. \fbox{
  10846. \begin{minipage}{0.96\textwidth}
  10847. \small
  10848. {\if\edition\racketEd
  10849. \[
  10850. \begin{array}{l}
  10851. \gray{\CvarASTRacket} \\ \hline
  10852. \gray{\CifASTRacket} \\ \hline
  10853. \gray{\CloopASTRacket} \\ \hline
  10854. \CtupASTRacket \\
  10855. \begin{array}{lcl}
  10856. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10857. \end{array}
  10858. \end{array}
  10859. \]
  10860. \fi}
  10861. {\if\edition\pythonEd
  10862. \[
  10863. \begin{array}{l}
  10864. \gray{\CifASTPython} \\ \hline
  10865. \CtupASTPython \\
  10866. \begin{array}{lcl}
  10867. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  10868. \end{array}
  10869. \end{array}
  10870. \]
  10871. \fi}
  10872. \end{minipage}
  10873. }
  10874. \caption{The abstract syntax of \LangCVec{}, extending \LangCLoop{}
  10875. (Figure~\ref{fig:c7-syntax}).}
  10876. \label{fig:c2-syntax}
  10877. \end{figure}
  10878. The output of \code{explicate\_control} is a program in the
  10879. intermediate language \LangCVec{}, whose abstract syntax is defined in
  10880. Figure~\ref{fig:c2-syntax}.
  10881. %
  10882. \racket{(The concrete syntax is defined in
  10883. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  10884. %
  10885. The new expressions of \LangCVec{} include \key{allocate},
  10886. %
  10887. \racket{\key{vector-ref}, and \key{vector-set!},}
  10888. %
  10889. \python{accessing tuple elements,}
  10890. %
  10891. and \key{global\_value}.
  10892. %
  10893. \python{\LangCVec{} also includes the \code{collect} statement and
  10894. assignment to a tuple element.}
  10895. %
  10896. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  10897. %
  10898. The \code{explicate\_control} pass can treat these new forms much like
  10899. the other forms that we've already encoutered.
  10900. \section{Select Instructions and the \LangXGlobal{} Language}
  10901. \label{sec:select-instructions-gc}
  10902. \index{subject}{instruction selection}
  10903. %% void (rep as zero)
  10904. %% allocate
  10905. %% collect (callq collect)
  10906. %% vector-ref
  10907. %% vector-set!
  10908. %% vector-length
  10909. %% global (postpone)
  10910. In this pass we generate x86 code for most of the new operations that
  10911. were needed to compile tuples, including \code{Allocate},
  10912. \code{Collect}, and accessing tuple elements.
  10913. %
  10914. We compile \code{GlobalValue} to \code{Global} because the later has a
  10915. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  10916. \ref{fig:x86-2}). \index{subject}{x86}
  10917. The tuple read and write forms translate into \code{movq}
  10918. instructions. (The plus one in the offset is to get past the tag at
  10919. the beginning of the tuple representation.)
  10920. %
  10921. \begin{center}
  10922. \begin{minipage}{\textwidth}
  10923. {\if\edition\racketEd
  10924. \begin{lstlisting}
  10925. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  10926. |$\Longrightarrow$|
  10927. movq |$\itm{tup}'$|, %r11
  10928. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  10929. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  10930. |$\Longrightarrow$|
  10931. movq |$\itm{tup}'$|, %r11
  10932. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  10933. movq $0, |$\itm{lhs'}$|
  10934. \end{lstlisting}
  10935. \fi}
  10936. {\if\edition\pythonEd
  10937. \begin{lstlisting}
  10938. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  10939. |$\Longrightarrow$|
  10940. movq |$\itm{tup}'$|, %r11
  10941. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  10942. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  10943. |$\Longrightarrow$|
  10944. movq |$\itm{tup}'$|, %r11
  10945. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  10946. movq $0, |$\itm{lhs'}$|
  10947. \end{lstlisting}
  10948. \fi}
  10949. \end{minipage}
  10950. \end{center}
  10951. The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$ are obtained by
  10952. translating $\itm{tup}$ and $\itm{rhs}$ to x86. The move of $\itm{tup}'$ to
  10953. register \code{r11} ensures that offset expression
  10954. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  10955. removing \code{r11} from consideration by the register allocating.
  10956. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  10957. \code{rax}. Then the generated code for tuple assignment would be
  10958. \begin{lstlisting}
  10959. movq |$\itm{tup}'$|, %rax
  10960. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  10961. movq $0, |$\itm{lhs}'$|
  10962. \end{lstlisting}
  10963. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  10964. \code{patch\_instructions} would insert a move through \code{rax}
  10965. as follows.
  10966. \begin{lstlisting}
  10967. movq |$\itm{tup}'$|, %rax
  10968. movq |$\itm{rhs}'$|, %rax
  10969. movq %rax, |$8(n+1)$|(%rax)
  10970. movq $0, |$\itm{lhs}'$|
  10971. \end{lstlisting}
  10972. But the above sequence of instructions does not work because we're
  10973. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  10974. $\itm{rhs}'$) at the same time!
  10975. The \racket{\code{vector-length}}\python{\code{len}} operation should
  10976. be translated into a sequence of instructions that read the tag of the
  10977. tuple and extract the six bits that represent the tuple length, which
  10978. are the bits starting at index 1 and going up to and including bit 6.
  10979. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  10980. (shift right) can be used to accomplish this.
  10981. We compile the \code{allocate} form to operations on the
  10982. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  10983. is the next free address in the FromSpace, so we copy it into
  10984. \code{r11} and then move it forward by enough space for the tuple
  10985. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  10986. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  10987. initialize the \itm{tag} and finally copy the address in \code{r11} to
  10988. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  10989. tag is organized.
  10990. %
  10991. \racket{We recommend using the Racket operations
  10992. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  10993. during compilation.}
  10994. %
  10995. \python{We recommend using the bitwise-or operator \code{|} and the
  10996. shift-left operator \code{<<} to compute the tag during
  10997. compilation.}
  10998. %
  10999. The type annotation in the \code{allocate} form is used to determine
  11000. the pointer mask region of the tag.
  11001. %
  11002. {\if\edition\racketEd
  11003. \begin{lstlisting}
  11004. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11005. |$\Longrightarrow$|
  11006. movq free_ptr(%rip), %r11
  11007. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11008. movq $|$\itm{tag}$|, 0(%r11)
  11009. movq %r11, |$\itm{lhs}'$|
  11010. \end{lstlisting}
  11011. \fi}
  11012. {\if\edition\pythonEd
  11013. \begin{lstlisting}
  11014. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  11015. |$\Longrightarrow$|
  11016. movq free_ptr(%rip), %r11
  11017. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11018. movq $|$\itm{tag}$|, 0(%r11)
  11019. movq %r11, |$\itm{lhs}'$|
  11020. \end{lstlisting}
  11021. \fi}
  11022. The \code{collect} form is compiled to a call to the \code{collect}
  11023. function in the runtime. The arguments to \code{collect} are 1) the
  11024. top of the root stack and 2) the number of bytes that need to be
  11025. allocated. We use another dedicated register, \code{r15}, to
  11026. store the pointer to the top of the root stack. So \code{r15} is not
  11027. available for use by the register allocator.
  11028. {\if\edition\racketEd
  11029. \begin{lstlisting}
  11030. (collect |$\itm{bytes}$|)
  11031. |$\Longrightarrow$|
  11032. movq %r15, %rdi
  11033. movq $|\itm{bytes}|, %rsi
  11034. callq collect
  11035. \end{lstlisting}
  11036. \fi}
  11037. {\if\edition\pythonEd
  11038. \begin{lstlisting}
  11039. collect(|$\itm{bytes}$|)
  11040. |$\Longrightarrow$|
  11041. movq %r15, %rdi
  11042. movq $|\itm{bytes}|, %rsi
  11043. callq collect
  11044. \end{lstlisting}
  11045. \fi}
  11046. \begin{figure}[tp]
  11047. \fbox{
  11048. \begin{minipage}{0.96\textwidth}
  11049. \[
  11050. \begin{array}{lcl}
  11051. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  11052. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  11053. & & \gray{ \key{main:} \; \Instr\ldots }
  11054. \end{array}
  11055. \]
  11056. \end{minipage}
  11057. }
  11058. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  11059. \label{fig:x86-2-concrete}
  11060. \end{figure}
  11061. \begin{figure}[tp]
  11062. \fbox{
  11063. \begin{minipage}{0.96\textwidth}
  11064. \small
  11065. \[
  11066. \begin{array}{lcl}
  11067. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  11068. \MID \BYTEREG{\Reg}} \\
  11069. &\MID& \GLOBAL{\Var} \\
  11070. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  11071. \end{array}
  11072. \]
  11073. \end{minipage}
  11074. }
  11075. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  11076. \label{fig:x86-2}
  11077. \end{figure}
  11078. The concrete and abstract syntax of the \LangXGlobal{} language is
  11079. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  11080. differs from \LangXIf{} just in the addition of global variables.
  11081. %
  11082. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11083. \code{select\_instructions} pass on the running example.
  11084. \begin{figure}[tbp]
  11085. \centering
  11086. % tests/s2_17.rkt
  11087. \begin{minipage}[t]{0.5\textwidth}
  11088. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11089. block35:
  11090. movq free_ptr(%rip), alloc9024
  11091. addq $16, free_ptr(%rip)
  11092. movq alloc9024, %r11
  11093. movq $131, 0(%r11)
  11094. movq alloc9024, %r11
  11095. movq vecinit9025, 8(%r11)
  11096. movq $0, initret9026
  11097. movq alloc9024, %r11
  11098. movq 8(%r11), tmp9034
  11099. movq tmp9034, %r11
  11100. movq 8(%r11), %rax
  11101. jmp conclusion
  11102. block36:
  11103. movq $0, collectret9027
  11104. jmp block35
  11105. block38:
  11106. movq free_ptr(%rip), alloc9020
  11107. addq $16, free_ptr(%rip)
  11108. movq alloc9020, %r11
  11109. movq $3, 0(%r11)
  11110. movq alloc9020, %r11
  11111. movq vecinit9021, 8(%r11)
  11112. movq $0, initret9022
  11113. movq alloc9020, vecinit9025
  11114. movq free_ptr(%rip), tmp9031
  11115. movq tmp9031, tmp9032
  11116. addq $16, tmp9032
  11117. movq fromspace_end(%rip), tmp9033
  11118. cmpq tmp9033, tmp9032
  11119. jl block36
  11120. jmp block37
  11121. block37:
  11122. movq %r15, %rdi
  11123. movq $16, %rsi
  11124. callq 'collect
  11125. jmp block35
  11126. block39:
  11127. movq $0, collectret9023
  11128. jmp block38
  11129. \end{lstlisting}
  11130. \end{minipage}
  11131. \begin{minipage}[t]{0.45\textwidth}
  11132. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11133. start:
  11134. movq $42, vecinit9021
  11135. movq free_ptr(%rip), tmp9028
  11136. movq tmp9028, tmp9029
  11137. addq $16, tmp9029
  11138. movq fromspace_end(%rip), tmp9030
  11139. cmpq tmp9030, tmp9029
  11140. jl block39
  11141. jmp block40
  11142. block40:
  11143. movq %r15, %rdi
  11144. movq $16, %rsi
  11145. callq 'collect
  11146. jmp block38
  11147. \end{lstlisting}
  11148. \end{minipage}
  11149. \caption{Output of the \code{select\_instructions} pass.}
  11150. \label{fig:select-instr-output-gc}
  11151. \end{figure}
  11152. \clearpage
  11153. \section{Register Allocation}
  11154. \label{sec:reg-alloc-gc}
  11155. \index{subject}{register allocation}
  11156. As discussed earlier in this chapter, the garbage collector needs to
  11157. access all the pointers in the root set, that is, all variables that
  11158. are tuples. It will be the responsibility of the register allocator
  11159. to make sure that:
  11160. \begin{enumerate}
  11161. \item the root stack is used for spilling tuple-typed variables, and
  11162. \item if a tuple-typed variable is live during a call to the
  11163. collector, it must be spilled to ensure it is visible to the
  11164. collector.
  11165. \end{enumerate}
  11166. The later responsibility can be handled during construction of the
  11167. interference graph, by adding interference edges between the call-live
  11168. tuple-typed variables and all the callee-saved registers. (They
  11169. already interfere with the caller-saved registers.)
  11170. %
  11171. \racket{The type information for variables is in the \code{Program}
  11172. form, so we recommend adding another parameter to the
  11173. \code{build\_interference} function to communicate this alist.}
  11174. %
  11175. \python{The type information for variables is generated by the type
  11176. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11177. the \code{CProgram} AST mode. You'll need to propagate that
  11178. information so that it is available in this pass.}
  11179. The spilling of tuple-typed variables to the root stack can be handled
  11180. after graph coloring, when choosing how to assign the colors
  11181. (integers) to registers and stack locations. The
  11182. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11183. changes to also record the number of spills to the root stack.
  11184. % build-interference
  11185. %
  11186. % callq
  11187. % extra parameter for var->type assoc. list
  11188. % update 'program' and 'if'
  11189. % allocate-registers
  11190. % allocate spilled vectors to the rootstack
  11191. % don't change color-graph
  11192. % TODO:
  11193. %\section{Patch Instructions}
  11194. %[mention that global variables are memory references]
  11195. \section{Prelude and Conclusion}
  11196. \label{sec:print-x86-gc}
  11197. \label{sec:prelude-conclusion-x86-gc}
  11198. \index{subject}{prelude}\index{subject}{conclusion}
  11199. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11200. \code{prelude\_and\_conclusion} pass on the running example. In the
  11201. prelude and conclusion of the \code{main} function, we treat the root
  11202. stack very much like the regular stack in that we move the root stack
  11203. pointer (\code{r15}) to make room for the spills to the root stack,
  11204. except that the root stack grows up instead of down. For the running
  11205. example, there was just one spill so we increment \code{r15} by 8
  11206. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  11207. One issue that deserves special care is that there may be a call to
  11208. \code{collect} prior to the initializing assignments for all the
  11209. variables in the root stack. We do not want the garbage collector to
  11210. accidentally think that some uninitialized variable is a pointer that
  11211. needs to be followed. Thus, we zero-out all locations on the root
  11212. stack in the prelude of \code{main}. In
  11213. Figure~\ref{fig:print-x86-output-gc}, the instruction
  11214. %
  11215. \lstinline{movq $0, 0(%r15)}
  11216. %
  11217. accomplishes this task. The garbage collector tests each root to see
  11218. if it is null prior to dereferencing it.
  11219. \begin{figure}[htbp]
  11220. % TODO: Python Version -Jeremy
  11221. \begin{minipage}[t]{0.5\textwidth}
  11222. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11223. block35:
  11224. movq free_ptr(%rip), %rcx
  11225. addq $16, free_ptr(%rip)
  11226. movq %rcx, %r11
  11227. movq $131, 0(%r11)
  11228. movq %rcx, %r11
  11229. movq -8(%r15), %rax
  11230. movq %rax, 8(%r11)
  11231. movq $0, %rdx
  11232. movq %rcx, %r11
  11233. movq 8(%r11), %rcx
  11234. movq %rcx, %r11
  11235. movq 8(%r11), %rax
  11236. jmp conclusion
  11237. block36:
  11238. movq $0, %rcx
  11239. jmp block35
  11240. block38:
  11241. movq free_ptr(%rip), %rcx
  11242. addq $16, free_ptr(%rip)
  11243. movq %rcx, %r11
  11244. movq $3, 0(%r11)
  11245. movq %rcx, %r11
  11246. movq %rbx, 8(%r11)
  11247. movq $0, %rdx
  11248. movq %rcx, -8(%r15)
  11249. movq free_ptr(%rip), %rcx
  11250. addq $16, %rcx
  11251. movq fromspace_end(%rip), %rdx
  11252. cmpq %rdx, %rcx
  11253. jl block36
  11254. movq %r15, %rdi
  11255. movq $16, %rsi
  11256. callq collect
  11257. jmp block35
  11258. block39:
  11259. movq $0, %rcx
  11260. jmp block38
  11261. \end{lstlisting}
  11262. \end{minipage}
  11263. \begin{minipage}[t]{0.45\textwidth}
  11264. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11265. start:
  11266. movq $42, %rbx
  11267. movq free_ptr(%rip), %rdx
  11268. addq $16, %rdx
  11269. movq fromspace_end(%rip), %rcx
  11270. cmpq %rcx, %rdx
  11271. jl block39
  11272. movq %r15, %rdi
  11273. movq $16, %rsi
  11274. callq collect
  11275. jmp block38
  11276. .globl main
  11277. main:
  11278. pushq %rbp
  11279. movq %rsp, %rbp
  11280. pushq %r13
  11281. pushq %r12
  11282. pushq %rbx
  11283. pushq %r14
  11284. subq $0, %rsp
  11285. movq $16384, %rdi
  11286. movq $16384, %rsi
  11287. callq initialize
  11288. movq rootstack_begin(%rip), %r15
  11289. movq $0, 0(%r15)
  11290. addq $8, %r15
  11291. jmp start
  11292. conclusion:
  11293. subq $8, %r15
  11294. addq $0, %rsp
  11295. popq %r14
  11296. popq %rbx
  11297. popq %r12
  11298. popq %r13
  11299. popq %rbp
  11300. retq
  11301. \end{lstlisting}
  11302. \end{minipage}
  11303. \caption{Output of the \code{prelude\_and\_conclusion} pass.}
  11304. \label{fig:print-x86-output-gc}
  11305. \end{figure}
  11306. \begin{figure}[tbp]
  11307. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11308. \node (Lvec) at (0,2) {\large \LangVec{}};
  11309. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11310. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11311. \node (Lvec-4) at (9,2) {\large \LangVec{}};
  11312. \node (Lvec-5) at (9,0) {\large \LangAllocANF{}};
  11313. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11314. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11315. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11316. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11317. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11318. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11319. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11320. %\path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize type-check} (Lvec-2);
  11321. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11322. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11323. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11324. \path[->,bend left=15] (Lvec-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvec-5);
  11325. \path[->,bend left=10] (Lvec-5) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11326. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11327. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11328. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11329. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11330. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11331. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  11332. \end{tikzpicture}
  11333. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11334. \label{fig:Lvec-passes}
  11335. \end{figure}
  11336. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11337. for the compilation of \LangVec{}.
  11338. \clearpage
  11339. {\if\edition\racketEd
  11340. \section{Challenge: Simple Structures}
  11341. \label{sec:simple-structures}
  11342. \index{subject}{struct}
  11343. \index{subject}{structure}
  11344. The language \LangStruct{} extends \LangVec{} with support for simple
  11345. structures. Its concrete syntax is defined in
  11346. Figure~\ref{fig:Lstruct-concrete-syntax} and the abstract syntax is in
  11347. Figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct} in Typed
  11348. Racket is a user-defined data type that contains named fields and that
  11349. is heap allocated, similar to a vector. The following is an example of
  11350. a structure definition, in this case the definition of a \code{point}
  11351. type.
  11352. \begin{lstlisting}
  11353. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11354. \end{lstlisting}
  11355. \newcommand{\LstructGrammarRacket}{
  11356. \begin{array}{lcl}
  11357. \Type &::=& \Var \\
  11358. \Exp &::=& (\Var\;\Exp \ldots)\\
  11359. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11360. \end{array}
  11361. }
  11362. \newcommand{\LstructASTRacket}{
  11363. \begin{array}{lcl}
  11364. \Type &::=& \VAR{\Var} \\
  11365. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11366. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11367. \end{array}
  11368. }
  11369. \begin{figure}[tbp]
  11370. \centering
  11371. \fbox{
  11372. \begin{minipage}{0.96\textwidth}
  11373. \[
  11374. \begin{array}{l}
  11375. \gray{\LintGrammarRacket{}} \\ \hline
  11376. \gray{\LvarGrammarRacket{}} \\ \hline
  11377. \gray{\LifGrammarRacket{}} \\ \hline
  11378. \gray{\LwhileGrammarRacket} \\ \hline
  11379. \gray{\LtupGrammarRacket} \\ \hline
  11380. \LstructGrammarRacket \\
  11381. \begin{array}{lcl}
  11382. \LangStruct{} &::=& \Def \ldots \; \Exp
  11383. \end{array}
  11384. \end{array}
  11385. \]
  11386. \end{minipage}
  11387. }
  11388. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11389. (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11390. \label{fig:Lstruct-concrete-syntax}
  11391. \end{figure}
  11392. \begin{figure}[tbp]
  11393. \centering
  11394. \fbox{
  11395. \begin{minipage}{0.96\textwidth}
  11396. \[
  11397. \begin{array}{l}
  11398. \gray{\LintASTRacket{}} \\ \hline
  11399. \gray{\LvarASTRacket{}} \\ \hline
  11400. \gray{\LifASTRacket{}} \\ \hline
  11401. \gray{\LwhileASTRacket} \\ \hline
  11402. \gray{\LtupASTRacket} \\ \hline
  11403. \LstructASTRacket \\
  11404. \begin{array}{lcl}
  11405. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11406. \end{array}
  11407. \end{array}
  11408. \]
  11409. \end{minipage}
  11410. }
  11411. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11412. (Figure~\ref{fig:Lvec-syntax}).}
  11413. \label{fig:Lstruct-syntax}
  11414. \end{figure}
  11415. An instance of a structure is created using function call syntax, with
  11416. the name of the structure in the function position:
  11417. \begin{lstlisting}
  11418. (point 7 12)
  11419. \end{lstlisting}
  11420. Function-call syntax is also used to read the value in a field of a
  11421. structure. The function name is formed by the structure name, a dash,
  11422. and the field name. The following example uses \code{point-x} and
  11423. \code{point-y} to access the \code{x} and \code{y} fields of two point
  11424. instances.
  11425. \begin{center}
  11426. \begin{lstlisting}
  11427. (let ([pt1 (point 7 12)])
  11428. (let ([pt2 (point 4 3)])
  11429. (+ (- (point-x pt1) (point-x pt2))
  11430. (- (point-y pt1) (point-y pt2)))))
  11431. \end{lstlisting}
  11432. \end{center}
  11433. Similarly, to write to a field of a structure, use its set function,
  11434. whose name starts with \code{set-}, followed by the structure name,
  11435. then a dash, then the field name, and concluded with an exclamation
  11436. mark. The following example uses \code{set-point-x!} to change the
  11437. \code{x} field from \code{7} to \code{42}.
  11438. \begin{center}
  11439. \begin{lstlisting}
  11440. (let ([pt (point 7 12)])
  11441. (let ([_ (set-point-x! pt 42)])
  11442. (point-x pt)))
  11443. \end{lstlisting}
  11444. \end{center}
  11445. \begin{exercise}\normalfont
  11446. Create a type checker for \LangStruct{} by extending the type
  11447. checker for \LangVec{}. Extend your compiler with support for simple
  11448. structures, compiling \LangStruct{} to x86 assembly code. Create
  11449. five new test cases that use structures and test your compiler.
  11450. \end{exercise}
  11451. % TODO: create an interpreter for L_struct
  11452. \clearpage
  11453. \section{Challenge: Arrays}
  11454. \label{sec:arrays}
  11455. In Chapter~\ref{ch:Lvec} we studied tuples, that is, sequences of
  11456. elements whose length is determined at compile-time and where each
  11457. element of a tuple may have a different type (they are
  11458. heterogeous). This challenge is also about sequences, but this time
  11459. the length is determined at run-time and all the elements have the same
  11460. type (they are homogeneous). We use the term ``array'' for this later
  11461. kind of sequence.
  11462. The Racket language does not distinguish between tuples and arrays,
  11463. they are both represented by vectors. However, Typed Racket
  11464. distinguishes between tuples and arrays: the \code{Vector} type is for
  11465. tuples and the \code{Vectorof} type is for arrays.
  11466. %
  11467. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11468. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  11469. and the \code{make-vector} primitive operator for creating an array,
  11470. whose arguments are the length of the array and an initial value for
  11471. all the elements in the array. The \code{vector-length},
  11472. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11473. for tuples become overloaded for use with arrays.
  11474. %
  11475. We also include integer multiplication in \LangArray{}, as it is
  11476. useful in many examples involving arrays such as computing the
  11477. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  11478. \begin{figure}[tp]
  11479. \centering
  11480. \fbox{
  11481. \begin{minipage}{0.96\textwidth}
  11482. \small
  11483. \[
  11484. \begin{array}{lcl}
  11485. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  11486. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11487. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  11488. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11489. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11490. \MID \LP\key{and}\;\Exp\;\Exp\RP
  11491. \MID \LP\key{or}\;\Exp\;\Exp\RP
  11492. \MID \LP\key{not}\;\Exp\RP } \\
  11493. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11494. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  11495. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  11496. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  11497. \MID \LP\Exp \; \Exp\ldots\RP } \\
  11498. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11499. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11500. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  11501. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11502. \MID \CWHILE{\Exp}{\Exp} } \\
  11503. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  11504. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11505. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  11506. \end{array}
  11507. \]
  11508. \end{minipage}
  11509. }
  11510. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  11511. \label{fig:Lvecof-concrete-syntax}
  11512. \end{figure}
  11513. \begin{figure}[tp]
  11514. \begin{lstlisting}
  11515. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11516. [n : Integer]) : Integer
  11517. (let ([i 0])
  11518. (let ([prod 0])
  11519. (begin
  11520. (while (< i n)
  11521. (begin
  11522. (set! prod (+ prod (* (vector-ref A i)
  11523. (vector-ref B i))))
  11524. (set! i (+ i 1))
  11525. ))
  11526. prod))))
  11527. (let ([A (make-vector 2 2)])
  11528. (let ([B (make-vector 2 3)])
  11529. (+ (inner-product A B 2)
  11530. 30)))
  11531. \end{lstlisting}
  11532. \caption{Example program that computes the inner-product.}
  11533. \label{fig:inner-product}
  11534. \end{figure}
  11535. The type checker for \LangArray{} is define in
  11536. Figure~\ref{fig:type-check-Lvecof}. The result type of
  11537. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11538. of the intializing expression. The length expression is required to
  11539. have type \code{Integer}. The type checking of the operators
  11540. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11541. updated to handle the situation where the vector has type
  11542. \code{Vectorof}. In these cases we translate the operators to their
  11543. \code{vectorof} form so that later passes can easily distinguish
  11544. between operations on tuples versus arrays. We override the
  11545. \code{operator-types} method to provide the type signature for
  11546. multiplication: it takes two integers and returns an integer. To
  11547. support injection and projection of arrays to the \code{Any} type
  11548. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  11549. predicate.
  11550. \begin{figure}[tbp]
  11551. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11552. (define type-check-Lvecof_class
  11553. (class type-check-Rwhile_class
  11554. (super-new)
  11555. (inherit check-type-equal?)
  11556. (define/override (flat-ty? ty)
  11557. (match ty
  11558. ['(Vectorof Any) #t]
  11559. [else (super flat-ty? ty)]))
  11560. (define/override (operator-types)
  11561. (append '((* . ((Integer Integer) . Integer)))
  11562. (super operator-types)))
  11563. (define/override (type-check-exp env)
  11564. (lambda (e)
  11565. (define recur (type-check-exp env))
  11566. (match e
  11567. [(Prim 'make-vector (list e1 e2))
  11568. (define-values (e1^ t1) (recur e1))
  11569. (define-values (e2^ elt-type) (recur e2))
  11570. (define vec-type `(Vectorof ,elt-type))
  11571. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  11572. vec-type)]
  11573. [(Prim 'vector-ref (list e1 e2))
  11574. (define-values (e1^ t1) (recur e1))
  11575. (define-values (e2^ t2) (recur e2))
  11576. (match* (t1 t2)
  11577. [(`(Vectorof ,elt-type) 'Integer)
  11578. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  11579. [(other wise) ((super type-check-exp env) e)])]
  11580. [(Prim 'vector-set! (list e1 e2 e3) )
  11581. (define-values (e-vec t-vec) (recur e1))
  11582. (define-values (e2^ t2) (recur e2))
  11583. (define-values (e-arg^ t-arg) (recur e3))
  11584. (match t-vec
  11585. [`(Vectorof ,elt-type)
  11586. (check-type-equal? elt-type t-arg e)
  11587. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  11588. [else ((super type-check-exp env) e)])]
  11589. [(Prim 'vector-length (list e1))
  11590. (define-values (e1^ t1) (recur e1))
  11591. (match t1
  11592. [`(Vectorof ,t)
  11593. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  11594. [else ((super type-check-exp env) e)])]
  11595. [else ((super type-check-exp env) e)])))
  11596. ))
  11597. (define (type-check-Lvecof p)
  11598. (send (new type-check-Lvecof_class) type-check-program p))
  11599. \end{lstlisting}
  11600. \caption{Type checker for the \LangArray{} language.}
  11601. \label{fig:type-check-Lvecof}
  11602. \end{figure}
  11603. The interpreter for \LangArray{} is defined in
  11604. Figure~\ref{fig:interp-Lvecof}. The \code{make-vector} operator is
  11605. implemented with Racket's \code{make-vector} function and
  11606. multiplication is \code{fx*}, multiplication for \code{fixnum}
  11607. integers.
  11608. \begin{figure}[tbp]
  11609. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11610. (define interp-Lvecof_class
  11611. (class interp-Rwhile_class
  11612. (super-new)
  11613. (define/override (interp-op op)
  11614. (verbose "Lvecof/interp-op" op)
  11615. (match op
  11616. ['make-vector make-vector]
  11617. ['* fx*]
  11618. [else (super interp-op op)]))
  11619. ))
  11620. (define (interp-Lvecof p)
  11621. (send (new interp-Lvecof_class) interp-program p))
  11622. \end{lstlisting}
  11623. \caption{Interpreter for \LangArray{}.}
  11624. \label{fig:interp-Lvecof}
  11625. \end{figure}
  11626. \subsection{Data Representation}
  11627. \label{sec:array-rep}
  11628. Just like tuples, we store arrays on the heap which means that the
  11629. garbage collector will need to inspect arrays. An immediate thought is
  11630. to use the same representation for arrays that we use for tuples.
  11631. However, we limit tuples to a length of $50$ so that their length and
  11632. pointer mask can fit into the 64-bit tag at the beginning of each
  11633. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  11634. millions of elements, so we need more bits to store the length.
  11635. However, because arrays are homogeneous, we only need $1$ bit for the
  11636. pointer mask instead of one bit per array elements. Finally, the
  11637. garbage collector will need to be able to distinguish between tuples
  11638. and arrays, so we need to reserve $1$ bit for that purpose. So we
  11639. arrive at the following layout for the 64-bit tag at the beginning of
  11640. an array:
  11641. \begin{itemize}
  11642. \item The right-most bit is the forwarding bit, just like in a tuple.
  11643. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  11644. it is not.
  11645. \item The next bit to the left is the pointer mask. A $0$ indicates
  11646. that none of the elements are pointers to the heap and a $1$
  11647. indicates that all of the elements are pointers.
  11648. \item The next $61$ bits store the length of the array.
  11649. \item The left-most bit distinguishes between a tuple ($0$) versus an
  11650. array ($1$).
  11651. \end{itemize}
  11652. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  11653. differentiate the kinds of values that have been injected into the
  11654. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  11655. to indicate that the value is an array.
  11656. In the following subsections we provide hints regarding how to update
  11657. the passes to handle arrays.
  11658. \subsection{Reveal Casts}
  11659. The array-access operators \code{vectorof-ref} and
  11660. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  11661. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  11662. that the type checker cannot tell whether the index will be in bounds,
  11663. so the bounds check must be performed at run time. Recall that the
  11664. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  11665. an \code{If} arround a vector reference for update to check whether
  11666. the index is less than the length. You should do the same for
  11667. \code{vectorof-ref} and \code{vectorof-set!} .
  11668. In addition, the handling of the \code{any-vector} operators in
  11669. \code{reveal-casts} needs to be updated to account for arrays that are
  11670. injected to \code{Any}. For the \code{any-vector-length} operator, the
  11671. generated code should test whether the tag is for tuples (\code{010})
  11672. or arrays (\code{110}) and then dispatch to either
  11673. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  11674. we add a case in \code{select\_instructions} to generate the
  11675. appropriate instructions for accessing the array length from the
  11676. header of an array.
  11677. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  11678. the generated code needs to check that the index is less than the
  11679. vector length, so like the code for \code{any-vector-length}, check
  11680. the tag to determine whether to use \code{any-vector-length} or
  11681. \code{any-vectorof-length} for this purpose. Once the bounds checking
  11682. is complete, the generated code can use \code{any-vector-ref} and
  11683. \code{any-vector-set!} for both tuples and arrays because the
  11684. instructions used for those operators do not look at the tag at the
  11685. front of the tuple or array.
  11686. \subsection{Expose Allocation}
  11687. This pass should translate the \code{make-vector} operator into
  11688. lower-level operations. In particular, the new AST node
  11689. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  11690. length specified by the $\Exp$, but does not initialize the elements
  11691. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  11692. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  11693. element type for the array. Regarding the initialization of the array,
  11694. we recommend generated a \code{while} loop that uses
  11695. \code{vector-set!} to put the initializing value into every element of
  11696. the array.
  11697. \subsection{Remove Complex Operands}
  11698. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  11699. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  11700. complex and its subexpression must be atomic.
  11701. \subsection{Explicate Control}
  11702. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  11703. \code{explicate\_assign}.
  11704. \subsection{Select Instructions}
  11705. Generate instructions for \code{AllocateArray} similar to those for
  11706. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  11707. that the tag at the front of the array should instead use the
  11708. representation discussed in Section~\ref{sec:array-rep}.
  11709. Regarding \code{vectorof-length}, extract the length from the tag
  11710. according to the representation discussed in
  11711. Section~\ref{sec:array-rep}.
  11712. The instructions generated for \code{vectorof-ref} differ from those
  11713. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  11714. that the index is not a constant so the offset must be computed at
  11715. runtime, similar to the instructions generated for
  11716. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  11717. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  11718. appear in an assignment and as a stand-alone statement, so make sure
  11719. to handle both situations in this pass.
  11720. Finally, the instructions for \code{any-vectorof-length} should be
  11721. similar to those for \code{vectorof-length}, except that one must
  11722. first project the array by writing zeroes into the $3$-bit tag
  11723. \begin{exercise}\normalfont
  11724. Implement a compiler for the \LangArray{} language by extending your
  11725. compiler for \LangLoop{}. Test your compiler on a half dozen new
  11726. programs, including the one in Figure~\ref{fig:inner-product} and also
  11727. a program that multiplies two matrices. Note that matrices are
  11728. 2-dimensional arrays, but those can be encoded into 1-dimensional
  11729. arrays by laying out each row in the array, one after the next.
  11730. \end{exercise}
  11731. \section{Challenge: Generational Collection}
  11732. The copying collector described in Section~\ref{sec:GC} can incur
  11733. significant runtime overhead because the call to \code{collect} takes
  11734. time proportional to all of the live data. One way to reduce this
  11735. overhead is to reduce how much data is inspected in each call to
  11736. \code{collect}. In particular, researchers have observed that recently
  11737. allocated data is more likely to become garbage then data that has
  11738. survived one or more previous calls to \code{collect}. This insight
  11739. motivated the creation of \emph{generational garbage collectors}
  11740. \index{subject}{generational garbage collector} that
  11741. 1) segregates data according to its age into two or more generations,
  11742. 2) allocates less space for younger generations, so collecting them is
  11743. faster, and more space for the older generations, and 3) performs
  11744. collection on the younger generations more frequently then for older
  11745. generations~\citep{Wilson:1992fk}.
  11746. For this challenge assignment, the goal is to adapt the copying
  11747. collector implemented in \code{runtime.c} to use two generations, one
  11748. for young data and one for old data. Each generation consists of a
  11749. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  11750. \code{collect} function to use the two generations.
  11751. \begin{enumerate}
  11752. \item Copy the young generation's FromSpace to its ToSpace then switch
  11753. the role of the ToSpace and FromSpace
  11754. \item If there is enough space for the requested number of bytes in
  11755. the young FromSpace, then return from \code{collect}.
  11756. \item If there is not enough space in the young FromSpace for the
  11757. requested bytes, then move the data from the young generation to the
  11758. old one with the following steps:
  11759. \begin{enumerate}
  11760. \item If there is enough room in the old FromSpace, copy the young
  11761. FromSpace to the old FromSpace and then return.
  11762. \item If there is not enough room in the old FromSpace, then collect
  11763. the old generation by copying the old FromSpace to the old ToSpace
  11764. and swap the roles of the old FromSpace and ToSpace.
  11765. \item If there is enough room now, copy the young FromSpace to the
  11766. old FromSpace and return. Otherwise, allocate a larger FromSpace
  11767. and ToSpace for the old generation. Copy the young FromSpace and
  11768. the old FromSpace into the larger FromSpace for the old
  11769. generation and then return.
  11770. \end{enumerate}
  11771. \end{enumerate}
  11772. We recommend that you generalize the \code{cheney} function so that it
  11773. can be used for all the copies mentioned above: between the young
  11774. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  11775. between the young FromSpace and old FromSpace. This can be
  11776. accomplished by adding parameters to \code{cheney} that replace its
  11777. use of the global variables \code{fromspace\_begin},
  11778. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  11779. Note that the collection of the young generation does not traverse the
  11780. old generation. This introduces a potential problem: there may be
  11781. young data that is only reachable through pointers in the old
  11782. generation. If these pointers are not taken into account, the
  11783. collector could throw away young data that is live! One solution,
  11784. called \emph{pointer recording}, is to maintain a set of all the
  11785. pointers from the old generation into the new generation and consider
  11786. this set as part of the root set. To maintain this set, the compiler
  11787. must insert extra instructions around every \code{vector-set!}. If the
  11788. vector being modified is in the old generation, and if the value being
  11789. written is a pointer into the new generation, than that pointer must
  11790. be added to the set. Also, if the value being overwritten was a
  11791. pointer into the new generation, then that pointer should be removed
  11792. from the set.
  11793. \begin{exercise}\normalfont
  11794. Adapt the \code{collect} function in \code{runtime.c} to implement
  11795. generational garbage collection, as outlined in this section.
  11796. Update the code generation for \code{vector-set!} to implement
  11797. pointer recording. Make sure that your new compiler and runtime
  11798. passes your test suite.
  11799. \end{exercise}
  11800. \fi}
  11801. % Further Reading
  11802. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11803. \chapter{Functions}
  11804. \label{ch:Rfun}
  11805. \index{subject}{function}
  11806. This chapter studies the compilation of functions similar to those
  11807. found in the C language. This corresponds to a subset of \racket{Typed
  11808. Racket} \python{Python} in which only top-level function definitions
  11809. are allowed. This kind of function is an important stepping stone to
  11810. implementing lexically-scoped functions in the form of \key{lambda}
  11811. abstractions, which is the topic of Chapter~\ref{ch:Rlam}.
  11812. \section{The \LangFun{} Language}
  11813. The concrete and abstract syntax for function definitions and function
  11814. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  11815. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  11816. \LangFun{} begin with zero or more function definitions. The function
  11817. names from these definitions are in-scope for the entire program,
  11818. including all other function definitions (so the ordering of function
  11819. definitions does not matter).
  11820. %
  11821. \python{The abstract syntax for function parameters in
  11822. Figure~\ref{fig:Rfun-syntax} is a list of pairs, where each pair
  11823. consists of a parameter name and its type. This differs from
  11824. Python's \code{ast} module, which has a more complex syntax for
  11825. function parameters, for example, to handle keyword parameters and
  11826. defaults. The type checker in \code{type\_check\_Lfun} converts the
  11827. more commplex syntax into the simpler syntax of
  11828. Figure~\ref{fig:Rfun-syntax}. The fourth and sixth parameters of the
  11829. \code{FunctionDef} constructor are for decorators and a type
  11830. comment, neither of which are used by our compiler. We recommend
  11831. replacing them with \code{None} in the \code{shrink} pass.
  11832. }
  11833. %
  11834. The concrete syntax for function application\index{subject}{function
  11835. application} is $\CAPPLY{\Exp}{\Exp \ldots}$ where the first expression
  11836. must evaluate to a function and the rest are the arguments. The
  11837. abstract syntax for function application is
  11838. $\APPLY{\Exp}{\Exp\ldots}$.
  11839. %% The syntax for function application does not include an explicit
  11840. %% keyword, which is error prone when using \code{match}. To alleviate
  11841. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  11842. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  11843. Functions are first-class in the sense that a function pointer
  11844. \index{subject}{function pointer} is data and can be stored in memory or passed
  11845. as a parameter to another function. Thus, there is a function
  11846. type, written
  11847. {\if\edition\racketEd
  11848. \begin{lstlisting}
  11849. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  11850. \end{lstlisting}
  11851. \fi}
  11852. {\if\edition\pythonEd
  11853. \begin{lstlisting}
  11854. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  11855. \end{lstlisting}
  11856. \fi}
  11857. %
  11858. \noindent for a function whose $n$ parameters have the types $\Type_1$
  11859. through $\Type_n$ and whose return type is $\Type_R$. The main
  11860. limitation of these functions (with respect to
  11861. \racket{Racket}\python{Python} functions) is that they are not
  11862. lexically scoped. That is, the only external entities that can be
  11863. referenced from inside a function body are other globally-defined
  11864. functions. The syntax of \LangFun{} prevents functions from being
  11865. nested inside each other.
  11866. \newcommand{\LfunGrammarRacket}{
  11867. \begin{array}{lcl}
  11868. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  11869. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  11870. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  11871. \end{array}
  11872. }
  11873. \newcommand{\LfunASTRacket}{
  11874. \begin{array}{lcl}
  11875. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  11876. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  11877. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  11878. \end{array}
  11879. }
  11880. \newcommand{\LfunGrammarPython}{
  11881. \begin{array}{lcl}
  11882. \Type &::=& \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  11883. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  11884. \Stmt &::=& \CRETURN{\Exp} \\
  11885. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  11886. \end{array}
  11887. }
  11888. \newcommand{\LfunASTPython}{
  11889. \begin{array}{lcl}
  11890. \Type &::=& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  11891. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  11892. \Stmt &::=& \RETURN{\Exp} \\
  11893. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  11894. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  11895. \end{array}
  11896. }
  11897. \begin{figure}[tp]
  11898. \centering
  11899. \fbox{
  11900. \begin{minipage}{0.96\textwidth}
  11901. \small
  11902. {\if\edition\racketEd
  11903. \[
  11904. \begin{array}{l}
  11905. \gray{\LintGrammarRacket{}} \\ \hline
  11906. \gray{\LvarGrammarRacket{}} \\ \hline
  11907. \gray{\LifGrammarRacket{}} \\ \hline
  11908. \gray{\LwhileGrammarRacket} \\ \hline
  11909. \gray{\LtupGrammarRacket} \\ \hline
  11910. \LfunGrammarRacket \\
  11911. \begin{array}{lcl}
  11912. \LangFunM{} &::=& \Def \ldots \; \Exp
  11913. \end{array}
  11914. \end{array}
  11915. \]
  11916. \fi}
  11917. {\if\edition\pythonEd
  11918. \[
  11919. \begin{array}{l}
  11920. \gray{\LintGrammarPython{}} \\ \hline
  11921. \gray{\LvarGrammarPython{}} \\ \hline
  11922. \gray{\LifGrammarPython{}} \\ \hline
  11923. \gray{\LwhileGrammarPython} \\ \hline
  11924. \gray{\LtupGrammarPython} \\ \hline
  11925. \LfunGrammarPython \\
  11926. \begin{array}{rcl}
  11927. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  11928. \end{array}
  11929. \end{array}
  11930. \]
  11931. \fi}
  11932. \end{minipage}
  11933. }
  11934. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11935. \label{fig:Rfun-concrete-syntax}
  11936. \end{figure}
  11937. \begin{figure}[tp]
  11938. \centering
  11939. \fbox{
  11940. \begin{minipage}{0.96\textwidth}
  11941. \small
  11942. {\if\edition\racketEd
  11943. \[
  11944. \begin{array}{l}
  11945. \gray{\LintOpAST} \\ \hline
  11946. \gray{\LvarASTRacket{}} \\ \hline
  11947. \gray{\LifASTRacket{}} \\ \hline
  11948. \gray{\LwhileASTRacket{}} \\ \hline
  11949. \gray{\LtupASTRacket{}} \\ \hline
  11950. \LfunASTRacket \\
  11951. \begin{array}{lcl}
  11952. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11953. \end{array}
  11954. \end{array}
  11955. \]
  11956. \fi}
  11957. {\if\edition\pythonEd
  11958. \[
  11959. \begin{array}{l}
  11960. \gray{\LintASTPython{}} \\ \hline
  11961. \gray{\LvarASTPython{}} \\ \hline
  11962. \gray{\LifASTPython{}} \\ \hline
  11963. \gray{\LwhileASTPython} \\ \hline
  11964. \gray{\LtupASTPython} \\ \hline
  11965. \LfunASTPython \\
  11966. \begin{array}{rcl}
  11967. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  11968. \end{array}
  11969. \end{array}
  11970. \]
  11971. \fi}
  11972. \end{minipage}
  11973. }
  11974. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  11975. \label{fig:Rfun-syntax}
  11976. \end{figure}
  11977. The program in Figure~\ref{fig:Rfun-function-example} is a
  11978. representative example of defining and using functions in \LangFun{}.
  11979. We define a function \code{map} that applies some other function
  11980. \code{f} to both elements of a tuple and returns a new tuple
  11981. containing the results. We also define a function \code{inc}. The
  11982. program applies \code{map} to \code{inc} and
  11983. %
  11984. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  11985. %
  11986. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  11987. %
  11988. from which we return the \code{42}.
  11989. \begin{figure}[tbp]
  11990. {\if\edition\racketEd
  11991. \begin{lstlisting}
  11992. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  11993. : (Vector Integer Integer)
  11994. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11995. (define (inc [x : Integer]) : Integer
  11996. (+ x 1))
  11997. (vector-ref (map inc (vector 0 41)) 1)
  11998. \end{lstlisting}
  11999. \fi}
  12000. {\if\edition\pythonEd
  12001. \begin{lstlisting}
  12002. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12003. return f(v[0]), f(v[1])
  12004. def inc(x : int) -> int:
  12005. return x + 1
  12006. print( map(inc, (0, 41))[1] )
  12007. \end{lstlisting}
  12008. \fi}
  12009. \caption{Example of using functions in \LangFun{}.}
  12010. \label{fig:Rfun-function-example}
  12011. \end{figure}
  12012. The definitional interpreter for \LangFun{} is in
  12013. Figure~\ref{fig:interp-Rfun}. The case for the
  12014. %
  12015. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12016. %
  12017. AST is responsible for setting up the mutual recursion between the
  12018. top-level function definitions.
  12019. %
  12020. \racket{We use the classic back-patching
  12021. \index{subject}{back-patching} approach that uses mutable variables
  12022. and makes two passes over the function
  12023. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12024. top-level environment using a mutable cons cell for each function
  12025. definition. Note that the \code{lambda} value for each function is
  12026. incomplete; it does not yet include the environment. Once the
  12027. top-level environment is constructed, we then iterate over it and
  12028. update the \code{lambda} values to use the top-level environment.}
  12029. %
  12030. \python{We create a dictionary named \code{env} and fill it in
  12031. by mapping each function name to a new \code{Function} value,
  12032. each of which stores a reference to the \code{env}.
  12033. (We define the class \code{Function} for this purpose.)}
  12034. %
  12035. To interpret a function \racket{application}\python{call}, we match
  12036. the result of the function expression to obtain a function value. We
  12037. then extend the function's environment with mapping of parameters to
  12038. argument values. Finally, we interpret the body of the function in
  12039. this extended environment.
  12040. \begin{figure}[tp]
  12041. {\if\edition\racketEd
  12042. \begin{lstlisting}
  12043. (define interp-Rfun_class
  12044. (class interp-Lvec_class
  12045. (super-new)
  12046. (define/override ((interp-exp env) e)
  12047. (define recur (interp-exp env))
  12048. (match e
  12049. [(Var x) (unbox (dict-ref env x))]
  12050. [(Let x e body)
  12051. (define new-env (dict-set env x (box (recur e))))
  12052. ((interp-exp new-env) body)]
  12053. [(Apply fun args)
  12054. (define fun-val (recur fun))
  12055. (define arg-vals (for/list ([e args]) (recur e)))
  12056. (match fun-val
  12057. [`(function (,xs ...) ,body ,fun-env)
  12058. (define params-args (for/list ([x xs] [arg arg-vals])
  12059. (cons x (box arg))))
  12060. (define new-env (append params-args fun-env))
  12061. ((interp-exp new-env) body)]
  12062. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12063. [else ((super interp-exp env) e)]
  12064. ))
  12065. (define/public (interp-def d)
  12066. (match d
  12067. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12068. (cons f (box `(function ,xs ,body ())))]))
  12069. (define/override (interp-program p)
  12070. (match p
  12071. [(ProgramDefsExp info ds body)
  12072. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12073. (for/list ([f (in-dict-values top-level)])
  12074. (set-box! f (match (unbox f)
  12075. [`(function ,xs ,body ())
  12076. `(function ,xs ,body ,top-level)])))
  12077. ((interp-exp top-level) body))]))
  12078. ))
  12079. (define (interp-Rfun p)
  12080. (send (new interp-Rfun_class) interp-program p))
  12081. \end{lstlisting}
  12082. \fi}
  12083. {\if\edition\pythonEd
  12084. \begin{lstlisting}
  12085. class InterpLfun(InterpLtup):
  12086. def apply_fun(self, fun, args, e):
  12087. match fun:
  12088. case Function(name, xs, body, env):
  12089. new_env = {x: v for (x,v) in env.items()}
  12090. for (x,arg) in zip(xs, args):
  12091. new_env[x] = arg
  12092. return self.interp_stmts(body, new_env)
  12093. case _:
  12094. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12095. def interp_exp(self, e, env):
  12096. match e:
  12097. case Call(Name('input_int'), []):
  12098. return super().interp_exp(e, env)
  12099. case Call(func, args):
  12100. f = self.interp_exp(func, env)
  12101. vs = [self.interp_exp(arg, env) for arg in args]
  12102. return self.apply_fun(f, vs, e)
  12103. case _:
  12104. return super().interp_exp(e, env)
  12105. def interp_stmts(self, ss, env):
  12106. if len(ss) == 0:
  12107. return
  12108. match ss[0]:
  12109. case Return(value):
  12110. return self.interp_exp(value, env)
  12111. case _:
  12112. return super().interp_stmts(ss, env)
  12113. def interp(self, p):
  12114. match p:
  12115. case Module(defs):
  12116. env = {}
  12117. for d in defs:
  12118. match d:
  12119. case FunctionDef(name, params, bod, dl, returns, comment):
  12120. env[name] = Function(name, [x for (x,t) in params], bod, env)
  12121. self.apply_fun(env['main'], [], None)
  12122. case _:
  12123. raise Exception('interp: unexpected ' + repr(p))
  12124. \end{lstlisting}
  12125. \fi}
  12126. \caption{Interpreter for the \LangFun{} language.}
  12127. \label{fig:interp-Rfun}
  12128. \end{figure}
  12129. %\margincomment{TODO: explain type checker}
  12130. The type checker for \LangFun{} is in
  12131. Figure~\ref{fig:type-check-Rfun}. (We omit the code that parses
  12132. function parameters into the simpler abstract syntax.) Similar to the
  12133. interpreter, the case for the
  12134. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12135. %
  12136. AST is responsible for setting up the mutual recursion between the
  12137. top-level function definitions. We begin by create a mapping
  12138. \code{env} from every function name to its type. We then type check
  12139. the program using this \code{env}.
  12140. %
  12141. In the case for function \racket{application}\python{call}, we match
  12142. the type of the function expression to a function type and check that
  12143. the types of the argument expressions are equal to the function's
  12144. parameter types. The type of the \racket{application}\python{call} as
  12145. a whole is the return type from the function type.
  12146. \begin{figure}[tp]
  12147. {\if\edition\racketEd
  12148. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12149. (define type-check-Rfun_class
  12150. (class type-check-Lvec_class
  12151. (super-new)
  12152. (inherit check-type-equal?)
  12153. (define/public (type-check-apply env e es)
  12154. (define-values (e^ ty) ((type-check-exp env) e))
  12155. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  12156. ((type-check-exp env) e)))
  12157. (match ty
  12158. [`(,ty^* ... -> ,rt)
  12159. (for ([arg-ty ty*] [param-ty ty^*])
  12160. (check-type-equal? arg-ty param-ty (Apply e es)))
  12161. (values e^ e* rt)]))
  12162. (define/override (type-check-exp env)
  12163. (lambda (e)
  12164. (match e
  12165. [(FunRef f)
  12166. (values (FunRef f) (dict-ref env f))]
  12167. [(Apply e es)
  12168. (define-values (e^ es^ rt) (type-check-apply env e es))
  12169. (values (Apply e^ es^) rt)]
  12170. [(Call e es)
  12171. (define-values (e^ es^ rt) (type-check-apply env e es))
  12172. (values (Call e^ es^) rt)]
  12173. [else ((super type-check-exp env) e)])))
  12174. (define/public (type-check-def env)
  12175. (lambda (e)
  12176. (match e
  12177. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  12178. (define new-env (append (map cons xs ps) env))
  12179. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12180. (check-type-equal? ty^ rt body)
  12181. (Def f p:t* rt info body^)])))
  12182. (define/public (fun-def-type d)
  12183. (match d
  12184. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  12185. (define/override (type-check-program e)
  12186. (match e
  12187. [(ProgramDefsExp info ds body)
  12188. (define env (for/list ([d ds])
  12189. (cons (Def-name d) (fun-def-type d))))
  12190. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  12191. (define-values (body^ ty) ((type-check-exp env) body))
  12192. (check-type-equal? ty 'Integer body)
  12193. (ProgramDefsExp info ds^ body^)]))))
  12194. (define (type-check-Rfun p)
  12195. (send (new type-check-Rfun_class) type-check-program p))
  12196. \end{lstlisting}
  12197. \fi}
  12198. {\if\edition\pythonEd
  12199. \begin{lstlisting}
  12200. class TypeCheckLfun(TypeCheckLtup):
  12201. def type_check_exp(self, e, env):
  12202. match e:
  12203. case Call(Name('input_int'), []):
  12204. return super().type_check_exp(e, env)
  12205. case Call(func, args):
  12206. func_t = self.type_check_exp(func, env)
  12207. args_t = [self.type_check_exp(arg, env) for arg in args]
  12208. match func_t:
  12209. case FunctionType(params_t, return_t):
  12210. for (arg_t, param_t) in zip(args_t, params_t):
  12211. check_type_equal(param_t, arg_t, e)
  12212. return return_t
  12213. case _:
  12214. raise Exception('type_check_exp: in call, unexpected ' + \
  12215. repr(func_t))
  12216. case _:
  12217. return super().type_check_exp(e, env)
  12218. def type_check_stmts(self, ss, env):
  12219. if len(ss) == 0:
  12220. return
  12221. match ss[0]:
  12222. case FunctionDef(name, params, body, dl, returns, comment):
  12223. new_env = {x: t for (x,t) in env.items()}
  12224. for (x,t) in params:
  12225. new_env[x] = t
  12226. rt = self.type_check_stmts(body, new_env)
  12227. check_type_equal(returns, rt, ss[0])
  12228. return self.type_check_stmts(ss[1:], env)
  12229. case Return(value):
  12230. return self.type_check_exp(value, env)
  12231. case _:
  12232. return super().type_check_stmts(ss, env)
  12233. def type_check(self, p):
  12234. match p:
  12235. case Module(body):
  12236. env = {}
  12237. for s in body:
  12238. match s:
  12239. case FunctionDef(name, params, bod, dl, returns, comment):
  12240. params_t = [t for (x,t) in params]
  12241. env[name] = FunctionType(params_t, returns)
  12242. self.type_check_stmts(body, env)
  12243. case _:
  12244. raise Exception('type_check: unexpected ' + repr(p))
  12245. \end{lstlisting}
  12246. \fi}
  12247. \caption{Type checker for the \LangFun{} language.}
  12248. \label{fig:type-check-Rfun}
  12249. \end{figure}
  12250. \clearpage
  12251. \section{Functions in x86}
  12252. \label{sec:fun-x86}
  12253. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  12254. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  12255. %% \margincomment{\tiny Talk about the return address on the
  12256. %% stack and what callq and retq does.\\ --Jeremy }
  12257. The x86 architecture provides a few features to support the
  12258. implementation of functions. We have already seen that x86 provides
  12259. labels so that one can refer to the location of an instruction, as is
  12260. needed for jump instructions. Labels can also be used to mark the
  12261. beginning of the instructions for a function. Going further, we can
  12262. obtain the address of a label by using the \key{leaq} instruction and
  12263. PC-relative addressing. For example, the following puts the
  12264. address of the \code{inc} label into the \code{rbx} register.
  12265. \begin{lstlisting}
  12266. leaq inc(%rip), %rbx
  12267. \end{lstlisting}
  12268. The instruction pointer register \key{rip} (aka. the program counter
  12269. \index{subject}{program counter}) always points to the next
  12270. instruction to be executed. When combined with an label, as in
  12271. \code{inc(\%rip)}, the assembler computes the distance $d$ between the
  12272. address of \code{inc} and where the \code{rip} would be at that moment
  12273. and then changes the \code{inc(\%rip)} argument to \code{$d$(\%rip)},
  12274. which at runtime will compute the address of \code{inc}.
  12275. In Section~\ref{sec:x86} we used the \code{callq} instruction to jump
  12276. to functions whose locations were given by a label, such as
  12277. \code{read\_int}. To support function calls in this chapter we instead
  12278. will be jumping to functions whose location are given by an address in
  12279. a register, that is, we need to make an \emph{indirect function
  12280. call}. The x86 syntax for this is a \code{callq} instruction but with
  12281. an asterisk before the register name.\index{subject}{indirect function
  12282. call}
  12283. \begin{lstlisting}
  12284. callq *%rbx
  12285. \end{lstlisting}
  12286. \subsection{Calling Conventions}
  12287. \index{subject}{calling conventions}
  12288. The \code{callq} instruction provides partial support for implementing
  12289. functions: it pushes the return address on the stack and it jumps to
  12290. the target. However, \code{callq} does not handle
  12291. \begin{enumerate}
  12292. \item parameter passing,
  12293. \item pushing frames on the procedure call stack and popping them off,
  12294. or
  12295. \item determining how registers are shared by different functions.
  12296. \end{enumerate}
  12297. Regarding (1) parameter passing, recall that the following six
  12298. registers are used to pass arguments to a function, in this order.
  12299. \begin{lstlisting}
  12300. rdi rsi rdx rcx r8 r9
  12301. \end{lstlisting}
  12302. If there are
  12303. more than six arguments, then the convention is to use space on the
  12304. frame of the caller for the rest of the arguments. However, to ease
  12305. the implementation of efficient tail calls
  12306. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  12307. arguments.
  12308. %
  12309. Also recall that the register \code{rax} is for the return value of
  12310. the function.
  12311. \index{subject}{prelude}\index{subject}{conclusion}
  12312. Regarding (2) frames \index{subject}{frame} and the procedure call
  12313. stack, \index{subject}{procedure call stack} recall from
  12314. Section~\ref{sec:x86} that the stack grows down and each function call
  12315. uses a chunk of space on the stack called a frame. The caller sets the
  12316. stack pointer, register \code{rsp}, to the last data item in its
  12317. frame. The callee must not change anything in the caller's frame, that
  12318. is, anything that is at or above the stack pointer. The callee is free
  12319. to use locations that are below the stack pointer.
  12320. Recall that we are storing variables of tuple type on the root stack.
  12321. So the prelude needs to move the root stack pointer \code{r15} up and
  12322. the conclusion needs to move the root stack pointer back down. Also,
  12323. the prelude must initialize to \code{0} this frame's slots in the root
  12324. stack to signal to the garbage collector that those slots do not yet
  12325. contain a pointer to a vector. Otherwise the garbage collector will
  12326. interpret the garbage bits in those slots as memory addresses and try
  12327. to traverse them, causing serious mayhem!
  12328. Regarding (3) the sharing of registers between different functions,
  12329. recall from Section~\ref{sec:calling-conventions} that the registers
  12330. are divided into two groups, the caller-saved registers and the
  12331. callee-saved registers. The caller should assume that all the
  12332. caller-saved registers get overwritten with arbitrary values by the
  12333. callee. That is why we recommend in
  12334. Section~\ref{sec:calling-conventions} that variables that are live
  12335. during a function call should not be assigned to caller-saved
  12336. registers.
  12337. On the flip side, if the callee wants to use a callee-saved register,
  12338. the callee must save the contents of those registers on their stack
  12339. frame and then put them back prior to returning to the caller. That
  12340. is why we recommended in Section~\ref{sec:calling-conventions} that if
  12341. the register allocator assigns a variable to a callee-saved register,
  12342. then the prelude of the \code{main} function must save that register
  12343. to the stack and the conclusion of \code{main} must restore it. This
  12344. recommendation now generalizes to all functions.
  12345. Recall that the base pointer, register \code{rbp}, is used as a
  12346. point-of-reference within a frame, so that each local variable can be
  12347. accessed at a fixed offset from the base pointer
  12348. (Section~\ref{sec:x86}).
  12349. %
  12350. Figure~\ref{fig:call-frames} shows the general layout of the caller
  12351. and callee frames.
  12352. \begin{figure}[tbp]
  12353. \centering
  12354. \begin{tabular}{r|r|l|l} \hline
  12355. Caller View & Callee View & Contents & Frame \\ \hline
  12356. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  12357. 0(\key{\%rbp}) & & old \key{rbp} \\
  12358. -8(\key{\%rbp}) & & callee-saved $1$ \\
  12359. \ldots & & \ldots \\
  12360. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  12361. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  12362. \ldots & & \ldots \\
  12363. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  12364. %% & & \\
  12365. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  12366. %% & \ldots & \ldots \\
  12367. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  12368. \hline
  12369. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  12370. & 0(\key{\%rbp}) & old \key{rbp} \\
  12371. & -8(\key{\%rbp}) & callee-saved $1$ \\
  12372. & \ldots & \ldots \\
  12373. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  12374. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  12375. & \ldots & \ldots \\
  12376. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  12377. \end{tabular}
  12378. \caption{Memory layout of caller and callee frames.}
  12379. \label{fig:call-frames}
  12380. \end{figure}
  12381. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  12382. %% local variables and for storing the values of callee-saved registers
  12383. %% (we shall refer to all of these collectively as ``locals''), and that
  12384. %% at the beginning of a function we move the stack pointer \code{rsp}
  12385. %% down to make room for them.
  12386. %% We recommend storing the local variables
  12387. %% first and then the callee-saved registers, so that the local variables
  12388. %% can be accessed using \code{rbp} the same as before the addition of
  12389. %% functions.
  12390. %% To make additional room for passing arguments, we shall
  12391. %% move the stack pointer even further down. We count how many stack
  12392. %% arguments are needed for each function call that occurs inside the
  12393. %% body of the function and find their maximum. Adding this number to the
  12394. %% number of locals gives us how much the \code{rsp} should be moved at
  12395. %% the beginning of the function. In preparation for a function call, we
  12396. %% offset from \code{rsp} to set up the stack arguments. We put the first
  12397. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  12398. %% so on.
  12399. %% Upon calling the function, the stack arguments are retrieved by the
  12400. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  12401. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  12402. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  12403. %% the layout of the caller and callee frames. Notice how important it is
  12404. %% that we correctly compute the maximum number of arguments needed for
  12405. %% function calls; if that number is too small then the arguments and
  12406. %% local variables will smash into each other!
  12407. \subsection{Efficient Tail Calls}
  12408. \label{sec:tail-call}
  12409. In general, the amount of stack space used by a program is determined
  12410. by the longest chain of nested function calls. That is, if function
  12411. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, $f_n$, then the amount
  12412. of stack space is linear in $n$. The depth $n$ can grow quite large
  12413. in the case of recursive or mutually recursive functions. However, in
  12414. some cases we can arrange to use only a constant amount of space for a
  12415. long chain of nested function calls.
  12416. If a function call is the last action in a function body, then that
  12417. call is said to be a \emph{tail call}\index{subject}{tail call}.
  12418. For example, in the following
  12419. program, the recursive call to \code{tail\_sum} is a tail call.
  12420. \begin{center}
  12421. {\if\edition\racketEd
  12422. \begin{lstlisting}
  12423. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  12424. (if (eq? n 0)
  12425. r
  12426. (tail_sum (- n 1) (+ n r))))
  12427. (+ (tail_sum 3 0) 36)
  12428. \end{lstlisting}
  12429. \fi}
  12430. {\if\edition\pythonEd
  12431. \begin{lstlisting}
  12432. def tail_sum(n : int, r : int) -> int:
  12433. if n == 0:
  12434. return r
  12435. else:
  12436. return tail_sum(n - 1, n + r)
  12437. print( tail_sum(3, 0) + 36)
  12438. \end{lstlisting}
  12439. \fi}
  12440. \end{center}
  12441. At a tail call, the frame of the caller is no longer needed, so we can
  12442. pop the caller's frame before making the tail call. With this
  12443. approach, a recursive function that only makes tail calls will only
  12444. use a constant amount of stack space. Functional languages like
  12445. Racket typically rely heavily on recursive functions, so they
  12446. typically guarantee that all tail calls will be optimized in this way.
  12447. \index{subject}{frame}
  12448. Some care is needed with regards to argument passing in tail calls.
  12449. As mentioned above, for arguments beyond the sixth, the convention is
  12450. to use space in the caller's frame for passing arguments. But for a
  12451. tail call we pop the caller's frame and can no longer use it. An
  12452. alternative is to use space in the callee's frame for passing
  12453. arguments. However, this option is also problematic because the caller
  12454. and callee's frames overlap in memory. As we begin to copy the
  12455. arguments from their sources in the caller's frame, the target
  12456. locations in the callee's frame might collide with the sources for
  12457. later arguments! We solve this problem by using the heap instead of
  12458. the stack for passing more than six arguments, which we describe in
  12459. the Section~\ref{sec:limit-functions-r4}.
  12460. As mentioned above, for a tail call we pop the caller's frame prior to
  12461. making the tail call. The instructions for popping a frame are the
  12462. instructions that we usually place in the conclusion of a
  12463. function. Thus, we also need to place such code immediately before
  12464. each tail call. These instructions include restoring the callee-saved
  12465. registers, so it is fortunate that the argument passing registers are
  12466. all caller-saved registers!
  12467. One last note regarding which instruction to use to make the tail
  12468. call. When the callee is finished, it should not return to the current
  12469. function, but it should return to the function that called the current
  12470. one. Thus, the return address that is already on the stack is the
  12471. right one, and we should not use \key{callq} to make the tail call, as
  12472. that would unnecessarily overwrite the return address. Instead we can
  12473. simply use the \key{jmp} instruction. Like the indirect function call,
  12474. we write an \emph{indirect jump}\index{subject}{indirect jump} with a
  12475. register prefixed with an asterisk. We recommend using \code{rax} to
  12476. hold the jump target because the preceding conclusion can overwrite
  12477. just about everything else.
  12478. \begin{lstlisting}
  12479. jmp *%rax
  12480. \end{lstlisting}
  12481. \section{Shrink \LangFun{}}
  12482. \label{sec:shrink-r4}
  12483. The \code{shrink} pass performs a minor modification to ease the
  12484. later passes. This pass introduces an explicit \code{main} function.
  12485. %
  12486. \racket{It also changes the top \code{ProgramDefsExp} form to
  12487. \code{ProgramDefs}.}
  12488. {\if\edition\racketEd
  12489. \begin{lstlisting}
  12490. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  12491. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  12492. \end{lstlisting}
  12493. where $\itm{mainDef}$ is
  12494. \begin{lstlisting}
  12495. (Def 'main '() 'Integer '() |$\Exp'$|)
  12496. \end{lstlisting}
  12497. \fi}
  12498. {\if\edition\pythonEd
  12499. \begin{lstlisting}
  12500. Module(|$\Def\ldots\Stmt\ldots$|)
  12501. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  12502. \end{lstlisting}
  12503. where $\itm{mainDef}$ is
  12504. \begin{lstlisting}
  12505. FunctionDef('main', [], int, None, |$\Stmt'\ldots$|Return(Constant(0)), None)
  12506. \end{lstlisting}
  12507. \fi}
  12508. \section{Reveal Functions and the \LangFunRef{} language}
  12509. \label{sec:reveal-functions-r4}
  12510. The syntax of \LangFun{} is inconvenient for purposes of compilation
  12511. in that it conflates the use of function names and local
  12512. variables. This is a problem because we need to compile the use of a
  12513. function name differently than the use of a local variable; we need to
  12514. use \code{leaq} to convert the function name (a label in x86) to an
  12515. address in a register. Thus, we create a new pass that changes
  12516. function references from $\VAR{f}$ to $\FUNREF{f}$. This pass is named
  12517. \code{reveal\_functions} and the output language, \LangFunRef{}, is
  12518. defined in Figure~\ref{fig:f1-syntax}.
  12519. %% The concrete syntax for a
  12520. %% function reference is $\CFUNREF{f}$.
  12521. \begin{figure}[tp]
  12522. \centering
  12523. \fbox{
  12524. \begin{minipage}{0.96\textwidth}
  12525. {\if\edition\racketEd
  12526. \[
  12527. \begin{array}{lcl}
  12528. \Exp &::=& \ldots \MID \FUNREF{\Var}\\
  12529. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12530. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  12531. \end{array}
  12532. \]
  12533. \fi}
  12534. {\if\edition\pythonEd
  12535. \[
  12536. \begin{array}{lcl}
  12537. \Exp &::=& \FUNREF{\Var}\\
  12538. \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  12539. \end{array}
  12540. \]
  12541. \fi}
  12542. \end{minipage}
  12543. }
  12544. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  12545. (Figure~\ref{fig:Rfun-syntax}).}
  12546. \label{fig:f1-syntax}
  12547. \end{figure}
  12548. %% Distinguishing between calls in tail position and non-tail position
  12549. %% requires the pass to have some notion of context. We recommend using
  12550. %% two mutually recursive functions, one for processing expressions in
  12551. %% tail position and another for the rest.
  12552. \racket{Placing this pass after \code{uniquify} will make sure that
  12553. there are no local variables and functions that share the same
  12554. name.}
  12555. %
  12556. The \code{reveal\_functions} pass should come before the
  12557. \code{remove\_complex\_operands} pass because function references
  12558. should be categorized as complex expressions.
  12559. \section{Limit Functions}
  12560. \label{sec:limit-functions-r4}
  12561. Recall that we wish to limit the number of function parameters to six
  12562. so that we do not need to use the stack for argument passing, which
  12563. makes it easier to implement efficient tail calls. However, because
  12564. the input language \LangFun{} supports arbitrary numbers of function
  12565. arguments, we have some work to do!
  12566. This pass transforms functions and function calls that involve more
  12567. than six arguments to pass the first five arguments as usual, but it
  12568. packs the rest of the arguments into a vector and passes it as the
  12569. sixth argument.
  12570. Each function definition with too many parameters is transformed as
  12571. follows.
  12572. {\if\edition\racketEd
  12573. \begin{lstlisting}
  12574. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  12575. |$\Rightarrow$|
  12576. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  12577. \end{lstlisting}
  12578. \fi}
  12579. {\if\edition\pythonEd
  12580. \begin{lstlisting}
  12581. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  12582. |$\Rightarrow$|
  12583. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  12584. |$T_r$|, None, |$\itm{body}'$|, None)
  12585. \end{lstlisting}
  12586. \fi}
  12587. %
  12588. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  12589. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  12590. the $k$th element of the tuple, where $k = i - 6$.
  12591. %
  12592. {\if\edition\racketEd
  12593. \begin{lstlisting}
  12594. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  12595. \end{lstlisting}
  12596. \fi}
  12597. {\if\edition\pythonEd
  12598. \begin{lstlisting}
  12599. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|))
  12600. \end{lstlisting}
  12601. \fi}
  12602. For function calls with too many arguments, the \code{limit\_functions}
  12603. pass transforms them in the following way.
  12604. \begin{tabular}{lll}
  12605. \begin{minipage}{0.3\textwidth}
  12606. {\if\edition\racketEd
  12607. \begin{lstlisting}
  12608. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  12609. \end{lstlisting}
  12610. \fi}
  12611. {\if\edition\pythonEd
  12612. \begin{lstlisting}
  12613. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  12614. \end{lstlisting}
  12615. \fi}
  12616. \end{minipage}
  12617. &
  12618. $\Rightarrow$
  12619. &
  12620. \begin{minipage}{0.5\textwidth}
  12621. {\if\edition\racketEd
  12622. \begin{lstlisting}
  12623. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  12624. \end{lstlisting}
  12625. \fi}
  12626. {\if\edition\pythonEd
  12627. \begin{lstlisting}
  12628. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  12629. \end{lstlisting}
  12630. \fi}
  12631. \end{minipage}
  12632. \end{tabular}
  12633. \section{Remove Complex Operands}
  12634. \label{sec:rco-r4}
  12635. The primary decisions to make for this pass is whether to classify
  12636. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  12637. atomic or complex expressions. Recall that a simple expression will
  12638. eventually end up as just an immediate argument of an x86
  12639. instruction. Function application will be translated to a sequence of
  12640. instructions, so \racket{\code{Apply}}\python{\code{Call}} must be
  12641. classified as complex expression. On the other hand, the arguments of
  12642. \racket{\code{Apply}}\python{\code{Call}} should be atomic expressions.
  12643. %
  12644. Regarding \code{FunRef}, as discussed above, the function label needs
  12645. to be converted to an address using the \code{leaq} instruction. Thus,
  12646. even though \code{FunRef} seems rather simple, it needs to be
  12647. classified as a complex expression so that we generate an assignment
  12648. statement with a left-hand side that can serve as the target of the
  12649. \code{leaq}.
  12650. The output of this pass, \LangFunANF{}, extends \LangAllocANF{}
  12651. (Figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  12652. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions.
  12653. %
  12654. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  12655. % TODO: Return?
  12656. %% Figure~\ref{fig:Rfun-anf-syntax} defines the output language
  12657. %% \LangFunANF{} of this pass.
  12658. %% \begin{figure}[tp]
  12659. %% \centering
  12660. %% \fbox{
  12661. %% \begin{minipage}{0.96\textwidth}
  12662. %% \small
  12663. %% \[
  12664. %% \begin{array}{rcl}
  12665. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  12666. %% \MID \VOID{} } \\
  12667. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  12668. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  12669. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  12670. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  12671. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  12672. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  12673. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  12674. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  12675. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12676. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  12677. %% \end{array}
  12678. %% \]
  12679. %% \end{minipage}
  12680. %% }
  12681. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  12682. %% \label{fig:Rfun-anf-syntax}
  12683. %% \end{figure}
  12684. \section{Explicate Control and the \LangCFun{} language}
  12685. \label{sec:explicate-control-r4}
  12686. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  12687. output of \code{explicate\_control}.
  12688. %
  12689. \racket{(The concrete syntax is given in
  12690. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  12691. %
  12692. The auxiliary functions for assignment\racket{and tail contexts} should
  12693. be updated with cases for
  12694. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  12695. function for predicate context should be updated for
  12696. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  12697. \code{FunRef} can't be a Boolean.) In assignment and predicate
  12698. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  12699. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  12700. auxiliary function for processing function definitions. This code is
  12701. similar to the case for \code{Program} in \LangVec{}. The top-level
  12702. \code{explicate\_control} function that handles the \code{ProgramDefs}
  12703. form of \LangFun{} can then apply this new function to all the
  12704. function definitions.
  12705. {\if\edition\pythonEd
  12706. The translation of \code{Return} statements requires a new auxiliary
  12707. function to handle expressions in tail context, called
  12708. \code{explicate\_tail}. The function should take an expression and the
  12709. dictionary of basic blocks and produce a list of statements in the
  12710. \LangCFun{} language. The \code{explicate\_tail} function should
  12711. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  12712. and a default case for other kinds of expressions. The default case
  12713. should produce a \code{Return} statement. The case for \code{Call}
  12714. should change it into \code{TailCall}. The other cases should
  12715. recursively process their subexpressions and statements, choosing the
  12716. appropriate explicate functions for the various contexts.
  12717. \fi}
  12718. \newcommand{\CfunASTRacket}{
  12719. \begin{array}{lcl}
  12720. \Exp &::= & \FUNREF{\itm{label}} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  12721. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  12722. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12723. \end{array}
  12724. }
  12725. \newcommand{\CfunASTPython}{
  12726. \begin{array}{lcl}
  12727. \Exp &::= & \FUNREF{\itm{label}} \MID \CALL{\Atm}{\Atm^{*}} \\
  12728. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  12729. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  12730. \Block &::=& \Stmt^{*} \\
  12731. \Blocks &::=& \LC\itm{label}\key{:}\Block\code{,}\ldots\RC \\
  12732. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  12733. \end{array}
  12734. }
  12735. \begin{figure}[tp]
  12736. \fbox{
  12737. \begin{minipage}{0.96\textwidth}
  12738. \small
  12739. {\if\edition\racketEd
  12740. \[
  12741. \begin{array}{l}
  12742. \gray{\CvarASTRacket} \\ \hline
  12743. \gray{\CifASTRacket} \\ \hline
  12744. \gray{\CloopASTRacket} \\ \hline
  12745. \gray{\CtupASTRacket} \\ \hline
  12746. \CfunASTRacket \\
  12747. \begin{array}{lcl}
  12748. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12749. \end{array}
  12750. \end{array}
  12751. \]
  12752. \fi}
  12753. {\if\edition\pythonEd
  12754. \[
  12755. \begin{array}{l}
  12756. \gray{\CifASTPython} \\ \hline
  12757. \gray{\CtupASTPython} \\ \hline
  12758. \CfunASTPython \\
  12759. \begin{array}{lcl}
  12760. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  12761. \end{array}
  12762. \end{array}
  12763. \]
  12764. \fi}
  12765. \end{minipage}
  12766. }
  12767. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  12768. \label{fig:c3-syntax}
  12769. \end{figure}
  12770. \section{Select Instructions and the \LangXIndCall{} Language}
  12771. \label{sec:select-r4}
  12772. \index{subject}{instruction selection}
  12773. The output of select instructions is a program in the \LangXIndCall{}
  12774. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  12775. \index{subject}{x86}
  12776. \begin{figure}[tp]
  12777. \fbox{
  12778. \begin{minipage}{0.96\textwidth}
  12779. \small
  12780. \[
  12781. \begin{array}{lcl}
  12782. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  12783. \itm{cc} & ::= & \gray{ \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  12784. \Instr &::=& \ldots
  12785. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  12786. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  12787. \Block &::= & \Instr^{*} \\
  12788. \Blocks &::=& \LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\\
  12789. \Def &::= & \LP\key{define} \; \LP\itm{label} \RP \; \Blocks \RP\\
  12790. \LangXIndCallM{} &::= & \Def\ldots
  12791. \end{array}
  12792. \]
  12793. \end{minipage}
  12794. }
  12795. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  12796. \label{fig:x86-3-concrete}
  12797. \end{figure}
  12798. \begin{figure}[tp]
  12799. \fbox{
  12800. \begin{minipage}{0.96\textwidth}
  12801. \small
  12802. {\if\edition\racketEd
  12803. \[
  12804. \begin{array}{lcl}
  12805. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  12806. \MID \BYTEREG{\Reg} } \\
  12807. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}} \\
  12808. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  12809. \MID \TAILJMP{\Arg}{\itm{int}}\\
  12810. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  12811. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  12812. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  12813. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12814. \end{array}
  12815. \]
  12816. \fi}
  12817. {\if\edition\pythonEd
  12818. \[
  12819. \begin{array}{lcl}
  12820. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  12821. \MID \BYTEREG{\Reg} } \\
  12822. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}} \\
  12823. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  12824. \MID \TAILJMP{\Arg}{\itm{int}}\\
  12825. &\MID& \BININSTR{\code{leaq}}{\Arg}{\REG{\Reg}}\\
  12826. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\LC\itm{label}\key{:}\,\Instr^{*}\code{,}\ldots\RC}{\_}{\Type}{\_} \\
  12827. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  12828. \end{array}
  12829. \]
  12830. \fi}
  12831. \end{minipage}
  12832. }
  12833. \caption{The abstract syntax of \LangXIndCall{} (extends
  12834. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  12835. \label{fig:x86-3}
  12836. \end{figure}
  12837. An assignment of a function reference to a variable becomes a
  12838. load-effective-address instruction as follows, where $\itm{lhs}'$
  12839. is the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{}
  12840. to \Arg{} in \LangXIndCallVar{}. \\
  12841. \begin{tabular}{lcl}
  12842. \begin{minipage}{0.35\textwidth}
  12843. \begin{lstlisting}
  12844. |$\itm{lhs}$| = (fun-ref |$f$|);
  12845. \end{lstlisting}
  12846. \end{minipage}
  12847. &
  12848. $\Rightarrow$\qquad\qquad
  12849. &
  12850. \begin{minipage}{0.3\textwidth}
  12851. \begin{lstlisting}
  12852. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  12853. \end{lstlisting}
  12854. \end{minipage}
  12855. \end{tabular} \\
  12856. Regarding function definitions, we need to remove the parameters and
  12857. instead perform parameter passing using the conventions discussed in
  12858. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  12859. registers. We recommend turning the parameters into local variables
  12860. and generating instructions at the beginning of the function to move
  12861. from the argument passing registers to these local variables.
  12862. {\if\edition\racketEd
  12863. \begin{lstlisting}
  12864. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  12865. |$\Rightarrow$|
  12866. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  12867. \end{lstlisting}
  12868. \fi}
  12869. {\if\edition\pythonEd
  12870. \begin{lstlisting}
  12871. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  12872. |$\Rightarrow$|
  12873. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  12874. \end{lstlisting}
  12875. \fi}
  12876. The basic blocks $B'$ are the same as $B$ except that the
  12877. \code{start} block is modified to add the instructions for moving from
  12878. the argument registers to the parameter variables. So the \code{start}
  12879. block of $B$ shown on the left is changed to the code on the right.
  12880. \begin{center}
  12881. \begin{minipage}{0.3\textwidth}
  12882. \begin{lstlisting}
  12883. start:
  12884. |$\itm{instr}_1$|
  12885. |$\cdots$|
  12886. |$\itm{instr}_n$|
  12887. \end{lstlisting}
  12888. \end{minipage}
  12889. $\Rightarrow$
  12890. \begin{minipage}{0.3\textwidth}
  12891. \begin{lstlisting}
  12892. start:
  12893. movq %rdi, |$x_1$|
  12894. |$\cdots$|
  12895. |$\itm{instr}_1$|
  12896. |$\cdots$|
  12897. |$\itm{instr}_n$|
  12898. \end{lstlisting}
  12899. \end{minipage}
  12900. \end{center}
  12901. By changing the parameters to local variables, we are giving the
  12902. register allocator control over which registers or stack locations to
  12903. use for them. If you implemented the move-biasing challenge
  12904. (Section~\ref{sec:move-biasing}), the register allocator will try to
  12905. assign the parameter variables to the corresponding argument register,
  12906. in which case the \code{patch\_instructions} pass will remove the
  12907. \code{movq} instruction. This happens in the example translation in
  12908. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  12909. the \code{add} function.
  12910. %
  12911. Also, note that the register allocator will perform liveness analysis
  12912. on this sequence of move instructions and build the interference
  12913. graph. So, for example, $x_1$ will be marked as interfering with
  12914. \code{rsi} and that will prevent the assignment of $x_1$ to
  12915. \code{rsi}, which is good, because that would overwrite the argument
  12916. that needs to move into $x_2$.
  12917. Next, consider the compilation of function calls. In the mirror image
  12918. of handling the parameters of function definitions, the arguments need
  12919. to be moved to the argument passing registers. The function call
  12920. itself is performed with an indirect function call. The return value
  12921. from the function is stored in \code{rax}, so it needs to be moved
  12922. into the \itm{lhs}.
  12923. \begin{lstlisting}
  12924. |\itm{lhs}| = |$\CALL{\itm{fun}}{\itm{arg}_1\ldots}$|
  12925. |$\Rightarrow$|
  12926. movq |$\itm{arg}_1$|, %rdi
  12927. movq |$\itm{arg}_2$|, %rsi
  12928. |$\vdots$|
  12929. callq *|\itm{fun}|
  12930. movq %rax, |\itm{lhs}|
  12931. \end{lstlisting}
  12932. The \code{IndirectCallq} AST node includes an integer for the arity of
  12933. the function, i.e., the number of parameters. That information is
  12934. useful in the \code{uncover\_live} pass for determining which
  12935. argument-passing registers are potentially read during the call.
  12936. For tail calls, the parameter passing is the same as non-tail calls:
  12937. generate instructions to move the arguments into to the argument
  12938. passing registers. After that we need to pop the frame from the
  12939. procedure call stack. However, we do not yet know how big the frame
  12940. is; that gets determined during register allocation. So instead of
  12941. generating those instructions here, we invent a new instruction that
  12942. means ``pop the frame and then do an indirect jump'', which we name
  12943. \code{TailJmp}. The abstract syntax for this instruction includes an
  12944. argument that specifies where to jump and an integer that represents
  12945. the arity of the function being called.
  12946. Recall that we use the label \code{start} for the initial block of a
  12947. program, and in Section~\ref{sec:select-Lvar} we recommended labeling
  12948. the conclusion of the program with \code{conclusion}, so that
  12949. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  12950. by a jump to \code{conclusion}. With the addition of function
  12951. definitions, there is a start block and conclusion for each function,
  12952. but their labels need to be unique. We recommend prepending the
  12953. function's name to \code{start} and \code{conclusion}, respectively,
  12954. to obtain unique labels.
  12955. \section{Register Allocation}
  12956. \label{sec:register-allocation-r4}
  12957. \subsection{Liveness Analysis}
  12958. \label{sec:liveness-analysis-r4}
  12959. \index{subject}{liveness analysis}
  12960. %% The rest of the passes need only minor modifications to handle the new
  12961. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  12962. %% \code{leaq}.
  12963. The \code{IndirectCallq} instruction should be treated like
  12964. \code{Callq} regarding its written locations $W$, in that they should
  12965. include all the caller-saved registers. Recall that the reason for
  12966. that is to force call-live variables to be assigned to callee-saved
  12967. registers or to be spilled to the stack.
  12968. Regarding the set of read locations $R$ the arity field of
  12969. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  12970. argument-passing registers should be considered as read by those
  12971. instructions.
  12972. \subsection{Build Interference Graph}
  12973. \label{sec:build-interference-r4}
  12974. With the addition of function definitions, we compute an interference
  12975. graph for each function (not just one for the whole program).
  12976. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  12977. spill vector-typed variables that are live during a call to the
  12978. \code{collect}. With the addition of functions to our language, we
  12979. need to revisit this issue. Many functions perform allocation and
  12980. therefore have calls to the collector inside of them. Thus, we should
  12981. not only spill a vector-typed variable when it is live during a call
  12982. to \code{collect}, but we should spill the variable if it is live
  12983. during any function call. Thus, in the \code{build\_interference} pass,
  12984. we recommend adding interference edges between call-live vector-typed
  12985. variables and the callee-saved registers (in addition to the usual
  12986. addition of edges between call-live variables and the caller-saved
  12987. registers).
  12988. \subsection{Allocate Registers}
  12989. The primary change to the \code{allocate\_registers} pass is adding an
  12990. auxiliary function for handling definitions (the \Def{} non-terminal
  12991. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  12992. logic is the same as described in
  12993. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  12994. allocation is performed many times, once for each function definition,
  12995. instead of just once for the whole program.
  12996. \section{Patch Instructions}
  12997. In \code{patch\_instructions}, you should deal with the x86
  12998. idiosyncrasy that the destination argument of \code{leaq} must be a
  12999. register. Additionally, you should ensure that the argument of
  13000. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  13001. code generation more convenient, because we trample many registers
  13002. before the tail call (as explained in the next section).
  13003. \section{Prelude and Conclusion}
  13004. %% For the \code{print\_x86} pass, the cases for \code{FunRef} and
  13005. %% \code{IndirectCallq} are straightforward: output their concrete
  13006. %% syntax.
  13007. %% \begin{lstlisting}
  13008. %% (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  13009. %% (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  13010. %% \end{lstlisting}
  13011. Now that register allocation is complete, we can translate the
  13012. \code{TailJmp} into a sequence of instructions. A straightforward
  13013. translation of \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}.
  13014. However, before the jump we need to pop the current frame. This
  13015. sequence of instructions is the same as the code for the conclusion of
  13016. a function, except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  13017. Regarding function definitions, you need to generate a prelude
  13018. and conclusion for each one. This code is similar to the prelude and
  13019. conclusion that you generated for the \code{main} function in
  13020. Chapter~\ref{ch:Lvec}. To review, the prelude of every function
  13021. should carry out the following steps.
  13022. % TODO: .align the functions!
  13023. \begin{enumerate}
  13024. %% \item Start with \code{.global} and \code{.align} directives followed
  13025. %% by the label for the function. (See Figure~\ref{fig:add-fun} for an
  13026. %% example.)
  13027. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  13028. pointer.
  13029. \item Push to the stack all of the callee-saved registers that were
  13030. used for register allocation.
  13031. \item Move the stack pointer \code{rsp} down by the size of the stack
  13032. frame for this function, which depends on the number of regular
  13033. spills. (Aligned to 16 bytes.)
  13034. \item Move the root stack pointer \code{r15} up by the size of the
  13035. root-stack frame for this function, which depends on the number of
  13036. spilled vectors. \label{root-stack-init}
  13037. \item Initialize to zero all of the entries in the root-stack frame.
  13038. \item Jump to the start block.
  13039. \end{enumerate}
  13040. The prelude of the \code{main} function has one additional task: call
  13041. the \code{initialize} function to set up the garbage collector and
  13042. move the value of the global \code{rootstack\_begin} in
  13043. \code{r15}. This should happen before step \ref{root-stack-init}
  13044. above, which depends on \code{r15}.
  13045. The conclusion of every function should do the following.
  13046. \begin{enumerate}
  13047. \item Move the stack pointer back up by the size of the stack frame
  13048. for this function.
  13049. \item Restore the callee-saved registers by popping them from the
  13050. stack.
  13051. \item Move the root stack pointer back down by the size of the
  13052. root-stack frame for this function.
  13053. \item Restore \code{rbp} by popping it from the stack.
  13054. \item Return to the caller with the \code{retq} instruction.
  13055. \end{enumerate}
  13056. \begin{exercise}\normalfont
  13057. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  13058. Create 5 new programs that use functions, including examples that pass
  13059. functions and return functions from other functions, recursive
  13060. functions, functions that create vectors, and functions that make tail
  13061. calls. Test your compiler on these new programs and all of your
  13062. previously created test programs.
  13063. \end{exercise}
  13064. \begin{figure}[tbp]
  13065. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13066. \node (Rfun) at (0,2) {\large \LangFun{}};
  13067. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  13068. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  13069. \node (F1-1) at (9,2) {\large \LangFunRef{}};
  13070. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13071. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  13072. \node (F1-4) at (3,0) {\large \LangFunANF{}};
  13073. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13074. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13075. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13076. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13077. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13078. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13079. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13080. \path[->,bend left=15] (Rfun) edge [above] node
  13081. {\ttfamily\footnotesize shrink} (Rfun-1);
  13082. \path[->,bend left=15] (Rfun-1) edge [above] node
  13083. {\ttfamily\footnotesize uniquify} (Rfun-2);
  13084. \path[->,bend left=15] (Rfun-2) edge [above] node
  13085. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13086. \path[->,bend left=15] (F1-1) edge [right] node
  13087. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13088. \path[->,bend right=15] (F1-2) edge [above] node
  13089. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  13090. \path[->,bend right=15] (F1-3) edge [above] node
  13091. {\ttfamily\footnotesize remove\_complex.} (F1-4);
  13092. \path[->,bend left=15] (F1-4) edge [right] node
  13093. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13094. \path[->,bend right=15] (C3-2) edge [left] node
  13095. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13096. \path[->,bend left=15] (x86-2) edge [left] node
  13097. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13098. \path[->,bend right=15] (x86-2-1) edge [below] node
  13099. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13100. \path[->,bend right=15] (x86-2-2) edge [left] node
  13101. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13102. \path[->,bend left=15] (x86-3) edge [above] node
  13103. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13104. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  13105. \end{tikzpicture}
  13106. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  13107. \label{fig:Rfun-passes}
  13108. \end{figure}
  13109. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  13110. compiling \LangFun{} to x86.
  13111. \section{An Example Translation}
  13112. \label{sec:functions-example}
  13113. Figure~\ref{fig:add-fun} shows an example translation of a simple
  13114. function in \LangFun{} to x86. The figure also includes the results of the
  13115. \code{explicate\_control} and \code{select\_instructions} passes.
  13116. \begin{figure}[htbp]
  13117. \begin{tabular}{ll}
  13118. \begin{minipage}{0.4\textwidth}
  13119. % s3_2.rkt
  13120. {\if\edition\racketEd
  13121. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13122. (define (add [x : Integer] [y : Integer])
  13123. : Integer
  13124. (+ x y))
  13125. (add 40 2)
  13126. \end{lstlisting}
  13127. \fi}
  13128. {\if\edition\pythonEd
  13129. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13130. def add(x:int, y:int) -> int:
  13131. return x + y
  13132. print(add(40, 2))
  13133. \end{lstlisting}
  13134. \fi}
  13135. $\Downarrow$
  13136. {\if\edition\racketEd
  13137. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13138. (define (add86 [x87 : Integer]
  13139. [y88 : Integer]) : Integer
  13140. add86start:
  13141. return (+ x87 y88);
  13142. )
  13143. (define (main) : Integer ()
  13144. mainstart:
  13145. tmp89 = (fun-ref add86);
  13146. (tail-call tmp89 40 2)
  13147. )
  13148. \end{lstlisting}
  13149. \fi}
  13150. {\if\edition\pythonEd
  13151. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13152. def add(x:int, y:int) -> int:
  13153. addstart:
  13154. return x + y
  13155. def main() -> int:
  13156. mainstart:
  13157. fun.0 = add
  13158. tmp.1 = fun.0(40, 2)
  13159. print(tmp.1)
  13160. return 0
  13161. \end{lstlisting}
  13162. \fi}
  13163. \end{minipage}
  13164. &
  13165. $\Rightarrow$
  13166. \begin{minipage}{0.5\textwidth}
  13167. {\if\edition\racketEd
  13168. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13169. (define (add86) : Integer
  13170. add86start:
  13171. movq %rdi, x87
  13172. movq %rsi, y88
  13173. movq x87, %rax
  13174. addq y88, %rax
  13175. jmp inc1389conclusion
  13176. )
  13177. (define (main) : Integer
  13178. mainstart:
  13179. leaq (fun-ref add86), tmp89
  13180. movq $40, %rdi
  13181. movq $2, %rsi
  13182. tail-jmp tmp89
  13183. )
  13184. \end{lstlisting}
  13185. \fi}
  13186. {\if\edition\pythonEd
  13187. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13188. def add() -> int:
  13189. addstart:
  13190. movq %rdi, x
  13191. movq %rsi, y
  13192. movq x, %rax
  13193. addq y, %rax
  13194. jmp addconclusion
  13195. def main() -> int:
  13196. mainstart:
  13197. leaq add, fun.0
  13198. movq $40, %rdi
  13199. movq $2, %rsi
  13200. callq *fun.0
  13201. movq %rax, tmp.1
  13202. movq tmp.1, %rdi
  13203. callq print_int
  13204. movq $0, %rax
  13205. jmp mainconclusion
  13206. \end{lstlisting}
  13207. \fi}
  13208. $\Downarrow$
  13209. \end{minipage}
  13210. \end{tabular}
  13211. \begin{tabular}{ll}
  13212. \begin{minipage}{0.3\textwidth}
  13213. {\if\edition\racketEd
  13214. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13215. .globl add86
  13216. .align 16
  13217. add86:
  13218. pushq %rbp
  13219. movq %rsp, %rbp
  13220. jmp add86start
  13221. add86start:
  13222. movq %rdi, %rax
  13223. addq %rsi, %rax
  13224. jmp add86conclusion
  13225. add86conclusion:
  13226. popq %rbp
  13227. retq
  13228. \end{lstlisting}
  13229. \fi}
  13230. {\if\edition\pythonEd
  13231. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13232. .align 16
  13233. add:
  13234. pushq %rbp
  13235. movq %rsp, %rbp
  13236. subq $0, %rsp
  13237. jmp addstart
  13238. addstart:
  13239. movq %rdi, %rdx
  13240. movq %rsi, %rcx
  13241. movq %rdx, %rax
  13242. addq %rcx, %rax
  13243. jmp addconclusion
  13244. addconclusion:
  13245. subq $0, %r15
  13246. addq $0, %rsp
  13247. popq %rbp
  13248. retq
  13249. \end{lstlisting}
  13250. \fi}
  13251. \end{minipage}
  13252. &
  13253. \begin{minipage}{0.5\textwidth}
  13254. {\if\edition\racketEd
  13255. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13256. .globl main
  13257. .align 16
  13258. main:
  13259. pushq %rbp
  13260. movq %rsp, %rbp
  13261. movq $16384, %rdi
  13262. movq $16384, %rsi
  13263. callq initialize
  13264. movq rootstack_begin(%rip), %r15
  13265. jmp mainstart
  13266. mainstart:
  13267. leaq add86(%rip), %rcx
  13268. movq $40, %rdi
  13269. movq $2, %rsi
  13270. movq %rcx, %rax
  13271. popq %rbp
  13272. jmp *%rax
  13273. mainconclusion:
  13274. popq %rbp
  13275. retq
  13276. \end{lstlisting}
  13277. \fi}
  13278. {\if\edition\pythonEd
  13279. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13280. .globl main
  13281. .align 16
  13282. main:
  13283. pushq %rbp
  13284. movq %rsp, %rbp
  13285. subq $0, %rsp
  13286. movq $65536, %rdi
  13287. movq $65536, %rsi
  13288. callq initialize
  13289. movq rootstack_begin(%rip), %r15
  13290. jmp mainstart
  13291. mainstart:
  13292. leaq add(%rip), %rcx
  13293. movq $40, %rdi
  13294. movq $2, %rsi
  13295. callq *%rcx
  13296. movq %rax, %rcx
  13297. movq %rcx, %rdi
  13298. callq print_int
  13299. movq $0, %rax
  13300. jmp mainconclusion
  13301. mainconclusion:
  13302. subq $0, %r15
  13303. addq $0, %rsp
  13304. popq %rbp
  13305. retq
  13306. \end{lstlisting}
  13307. \fi}
  13308. \end{minipage}
  13309. \end{tabular}
  13310. \caption{Example compilation of a simple function to x86.}
  13311. \label{fig:add-fun}
  13312. \end{figure}
  13313. % Challenge idea: inlining! (simple version)
  13314. % Further Reading
  13315. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13316. \chapter{Lexically Scoped Functions}
  13317. \label{ch:Rlam}
  13318. \index{subject}{lambda}
  13319. \index{subject}{lexical scoping}
  13320. This chapter studies lexically scoped functions, that is, functions
  13321. whose body may refer to variables that are bound outside of the
  13322. function, in an enclosing scope.
  13323. %
  13324. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  13325. \LangLam{}, which extends \LangFun{} with lexically scoped functions
  13326. using the \key{lambda} form. The body of the \key{lambda} refers to
  13327. three variables: \code{x}, \code{y}, and \code{z}. The binding sites
  13328. for \code{x} and \code{y} are outside of the \key{lambda}. Variable
  13329. \code{y} is \racket{bound by the enclosing \key{let}}\python{a local
  13330. variable of function \code{f}} and \code{x} is a parameter of
  13331. function \code{f}. The \key{lambda} is returned from the function
  13332. \code{f}. The main expression of the program includes two calls to
  13333. \code{f} with different arguments for \code{x}, first \code{5} then
  13334. \code{3}. The functions returned from \code{f} are bound to variables
  13335. \code{g} and \code{h}. Even though these two functions were created by
  13336. the same \code{lambda}, they are really different functions because
  13337. they use different values for \code{x}. Applying \code{g} to \code{11}
  13338. produces \code{20} whereas applying \code{h} to \code{15} produces
  13339. \code{22}. The result of this program is \code{42}.
  13340. \begin{figure}[btp]
  13341. {\if\edition\racketEd
  13342. % lambda_test_21.rkt
  13343. \begin{lstlisting}
  13344. (define (f [x : Integer]) : (Integer -> Integer)
  13345. (let ([y 4])
  13346. (lambda: ([z : Integer]) : Integer
  13347. (+ x (+ y z)))))
  13348. (let ([g (f 5)])
  13349. (let ([h (f 3)])
  13350. (+ (g 11) (h 15))))
  13351. \end{lstlisting}
  13352. \fi}
  13353. {\if\edition\pythonEd
  13354. \begin{lstlisting}
  13355. def f(x : int) -> Callable[[int], int]:
  13356. y = 4
  13357. return lambda z: x + y + z
  13358. g = f(5)
  13359. h = f(3)
  13360. print( g(11) + h(15) )
  13361. \end{lstlisting}
  13362. \fi}
  13363. \caption{Example of a lexically scoped function.}
  13364. \label{fig:lexical-scoping}
  13365. \end{figure}
  13366. The approach that we take for implementing lexically scoped functions
  13367. is to compile them into top-level function definitions, translating
  13368. from \LangLam{} into \LangFun{}. However, the compiler must give
  13369. special treatment to variable occurrences such as \code{x} and
  13370. \code{y} in the body of the \code{lambda} of
  13371. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  13372. may not refer to variables defined outside of it. To identify such
  13373. variable occurrences, we review the standard notion of free variable.
  13374. \begin{definition}
  13375. A variable is \textbf{free in expression} $e$ if the variable occurs
  13376. inside $e$ but does not have an enclosing definition that is also in
  13377. $e$.\index{subject}{free variable}
  13378. \end{definition}
  13379. For example, in the expression
  13380. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  13381. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  13382. only \code{x} and \code{y} are free in the following expression
  13383. because \code{z} is defined by the \code{lambda}.
  13384. {\if\edition\racketEd
  13385. \begin{lstlisting}
  13386. (lambda: ([z : Integer]) : Integer
  13387. (+ x (+ y z)))
  13388. \end{lstlisting}
  13389. \fi}
  13390. {\if\edition\pythonEd
  13391. \begin{lstlisting}
  13392. lambda z: x + y + z
  13393. \end{lstlisting}
  13394. \fi}
  13395. %
  13396. So the free variables of a \code{lambda} are the ones that need
  13397. special treatment. We need to transport, at runtime, the values of
  13398. those variables from the point where the \code{lambda} was created to
  13399. the point where the \code{lambda} is applied. An efficient solution to
  13400. the problem, due to \citet{Cardelli:1983aa}, is to bundle the values
  13401. of the free variables together with a function pointer into a tuple,
  13402. an arrangement called a \emph{flat closure} (which we shorten to just
  13403. ``closure''). \index{subject}{closure}\index{subject}{flat closure}
  13404. Fortunately, we have all the ingredients to make closures:
  13405. Chapter~\ref{ch:Lvec} gave us tuples and Chapter~\ref{ch:Rfun} gave us
  13406. function pointers. The function pointer resides at index $0$ and the
  13407. values for the free variables fill in the rest of the tuple.
  13408. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  13409. how closures work. It's a three-step dance. The program calls function
  13410. \code{f}, which creates a closure for the \code{lambda}. The closure
  13411. is a tuple whose first element is a pointer to the top-level function
  13412. that we will generate for the \code{lambda}, the second element is the
  13413. value of \code{x}, which is \code{5}, and the third element is
  13414. \code{4}, the value of \code{y}. The closure does not contain an
  13415. element for \code{z} because \code{z} is not a free variable of the
  13416. \code{lambda}. Creating the closure is step 1 of the dance. The
  13417. closure is returned from \code{f} and bound to \code{g}, as shown in
  13418. Figure~\ref{fig:closures}.
  13419. %
  13420. The second call to \code{f} creates another closure, this time with
  13421. \code{3} in the second slot (for \code{x}). This closure is also
  13422. returned from \code{f} but bound to \code{h}, which is also shown in
  13423. Figure~\ref{fig:closures}.
  13424. \begin{figure}[tbp]
  13425. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  13426. \caption{Flat closure representations for the two functions
  13427. produced by the \key{lambda} in Figure~\ref{fig:lexical-scoping}.}
  13428. \label{fig:closures}
  13429. \end{figure}
  13430. Continuing with the example, consider the application of \code{g} to
  13431. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  13432. obtain the function pointer in the first element of the closure and
  13433. call it, passing in the closure itself and then the regular arguments,
  13434. in this case \code{11}. This technique for applying a closure is step
  13435. 2 of the dance.
  13436. %
  13437. But doesn't this \code{lambda} only take 1 argument, for parameter
  13438. \code{z}? The third and final step of the dance is generating a
  13439. top-level function for a \code{lambda}. We add an additional
  13440. parameter for the closure and we insert an initialization at the beginning
  13441. of the function for each free variable, to bind those variables to the
  13442. appropriate elements from the closure parameter.
  13443. %
  13444. This three-step dance is known as \emph{closure conversion}. We
  13445. discuss the details of closure conversion in
  13446. Section~\ref{sec:closure-conversion} and the code generated from the
  13447. example in Section~\ref{sec:example-lambda}. But first we define the
  13448. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  13449. \section{The \LangLam{} Language}
  13450. \label{sec:r5}
  13451. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  13452. functions and lexical scoping, is defined in
  13453. Figures~\ref{fig:Rlam-concrete-syntax} and \ref{fig:Rlam-syntax}. It adds
  13454. the \key{lambda} form to the grammar for \LangFun{}, which already has
  13455. syntax for function application.
  13456. \python{The syntax also includes an assignment statement that includes
  13457. a type annotation for the variable on the left-hand side.}
  13458. \newcommand{\LlambdaGrammarRacket}{
  13459. \begin{array}{lcl}
  13460. \Exp &::=& \LP \key{procedure-arity}~\Exp\RP \\
  13461. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp}
  13462. \end{array}
  13463. }
  13464. \newcommand{\LlambdaASTRacket}{
  13465. \begin{array}{lcl}
  13466. \itm{op} &::=& \code{procedure-arity} \\
  13467. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}
  13468. \end{array}
  13469. }
  13470. \newcommand{\LlambdaGrammarPython}{
  13471. \begin{array}{lcl}
  13472. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  13473. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  13474. \end{array}
  13475. }
  13476. \newcommand{\LlambdaASTPython}{
  13477. \begin{array}{lcl}
  13478. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \\
  13479. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  13480. \end{array}
  13481. }
  13482. % include AnnAssign in ASTPython
  13483. \begin{figure}[tp]
  13484. \centering
  13485. \fbox{
  13486. \begin{minipage}{0.96\textwidth}
  13487. \small
  13488. {\if\edition\racketEd
  13489. \[
  13490. \begin{array}{l}
  13491. \gray{\LintGrammarRacket{}} \\ \hline
  13492. \gray{\LvarGrammarRacket{}} \\ \hline
  13493. \gray{\LifGrammarRacket{}} \\ \hline
  13494. \gray{\LwhileGrammarRacket} \\ \hline
  13495. \gray{\LtupGrammarRacket} \\ \hline
  13496. \gray{\LfunGrammarRacket} \\ \hline
  13497. \LlambdaGrammarRacket \\
  13498. \begin{array}{lcl}
  13499. \LangLamM{} &::=& \Def\ldots \; \Exp
  13500. \end{array}
  13501. \end{array}
  13502. \]
  13503. \fi}
  13504. {\if\edition\pythonEd
  13505. \[
  13506. \begin{array}{l}
  13507. \gray{\LintGrammarPython{}} \\ \hline
  13508. \gray{\LvarGrammarPython{}} \\ \hline
  13509. \gray{\LifGrammarPython{}} \\ \hline
  13510. \gray{\LwhileGrammarPython} \\ \hline
  13511. \gray{\LtupGrammarPython} \\ \hline
  13512. \gray{\LfunGrammarPython} \\ \hline
  13513. \LlambdaGrammarPython \\
  13514. \begin{array}{rcl}
  13515. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13516. \end{array}
  13517. \end{array}
  13518. \]
  13519. \fi}
  13520. \end{minipage}
  13521. }
  13522. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  13523. with \key{lambda}.}
  13524. \label{fig:Rlam-concrete-syntax}
  13525. \end{figure}
  13526. \begin{figure}[tp]
  13527. \centering
  13528. \fbox{
  13529. \begin{minipage}{0.96\textwidth}
  13530. \small
  13531. {\if\edition\racketEd
  13532. \[
  13533. \begin{array}{l}
  13534. \gray{\LintOpAST} \\ \hline
  13535. \gray{\LvarASTRacket{}} \\ \hline
  13536. \gray{\LifASTRacket{}} \\ \hline
  13537. \gray{\LwhileASTRacket{}} \\ \hline
  13538. \gray{\LtupASTRacket{}} \\ \hline
  13539. \gray{\LfunASTRacket} \\ \hline
  13540. \LlambdaASTRacket \\
  13541. \begin{array}{lcl}
  13542. \LangLamM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  13543. \end{array}
  13544. \end{array}
  13545. \]
  13546. \fi}
  13547. {\if\edition\pythonEd
  13548. \[
  13549. \begin{array}{l}
  13550. \gray{\LintASTPython{}} \\ \hline
  13551. \gray{\LvarASTPython{}} \\ \hline
  13552. \gray{\LifASTPython{}} \\ \hline
  13553. \gray{\LwhileASTPython} \\ \hline
  13554. \gray{\LtupASTPython} \\ \hline
  13555. \gray{\LfunASTPython} \\ \hline
  13556. \LlambdaASTPython \\
  13557. \begin{array}{rcl}
  13558. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13559. \end{array}
  13560. \end{array}
  13561. \]
  13562. \fi}
  13563. \end{minipage}
  13564. }
  13565. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  13566. \label{fig:Rlam-syntax}
  13567. \end{figure}
  13568. \index{subject}{interpreter}
  13569. \label{sec:interp-Rlambda}
  13570. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  13571. \LangLam{}. The case for \key{Lambda} saves the current environment
  13572. inside the returned function value. Recall that during function
  13573. application, the environment stored in the function value, extended
  13574. with the mapping of parameters to argument values, is used to
  13575. interpret the body of the function.
  13576. \begin{figure}[tbp]
  13577. {\if\edition\racketEd
  13578. \begin{lstlisting}
  13579. (define interp-Rlambda_class
  13580. (class interp-Rfun_class
  13581. (super-new)
  13582. (define/override (interp-op op)
  13583. (match op
  13584. ['procedure-arity
  13585. (lambda (v)
  13586. (match v
  13587. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  13588. [else (error 'interp-op "expected a function, not ~a" v)]))]
  13589. [else (super interp-op op)]))
  13590. (define/override ((interp-exp env) e)
  13591. (define recur (interp-exp env))
  13592. (match e
  13593. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  13594. `(function ,xs ,body ,env)]
  13595. [else ((super interp-exp env) e)]))
  13596. ))
  13597. (define (interp-Rlambda p)
  13598. (send (new interp-Rlambda_class) interp-program p))
  13599. \end{lstlisting}
  13600. \fi}
  13601. {\if\edition\pythonEd
  13602. \begin{lstlisting}
  13603. class InterpLlambda(InterpLfun):
  13604. def interp_exp(self, e, env):
  13605. match e:
  13606. case Lambda(params, body):
  13607. return Function('lambda', params, [Return(body)], env)
  13608. case _:
  13609. return super().interp_exp(e, env)
  13610. def interp_stmts(self, ss, env):
  13611. if len(ss) == 0:
  13612. return
  13613. match ss[0]:
  13614. case AnnAssign(lhs, typ, value, simple):
  13615. env[lhs.id] = self.interp_exp(value, env)
  13616. return self.interp_stmts(ss[1:], env)
  13617. case _:
  13618. return super().interp_stmts(ss, env)
  13619. \end{lstlisting}
  13620. \fi}
  13621. \caption{Interpreter for \LangLam{}.}
  13622. \label{fig:interp-Rlambda}
  13623. \end{figure}
  13624. \label{sec:type-check-r5}
  13625. \index{subject}{type checking}
  13626. {\if\edition\racketEd
  13627. %
  13628. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  13629. \key{lambda} form. The body of the \key{lambda} is checked in an
  13630. environment that includes the current environment (because it is
  13631. lexically scoped) and also includes the \key{lambda}'s parameters. We
  13632. require the body's type to match the declared return type.
  13633. %
  13634. \fi}
  13635. {\if\edition\pythonEd
  13636. %
  13637. Figures~\ref{fig:type-check-Llambda} and
  13638. \ref{fig:type-check-Llambda-part2} define the type checker for
  13639. \LangLam{}, which is more complex than one might expect. The reason
  13640. for the added complexity is that the syntax of \key{lambda} does not
  13641. include type annotations for the parameters or return type. Instead
  13642. they must be inferred. There are many approaches of type inference to
  13643. choose from of varying degrees of complexity. We choose one of the
  13644. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  13645. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  13646. this book is compilation, not type inference.
  13647. The main idea of bidirectional type inference is to add an auxilliary
  13648. function, here named \code{check\_exp}, that takes an expected type
  13649. and checks whether the given expression is of that type. Thus, in
  13650. \code{check\_exp}, type information flows in a top-down manner with
  13651. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  13652. function, where type information flows in a primarily bottom-up
  13653. manner.
  13654. %
  13655. The idea then is to use \code{check\_exp} in all the places where we
  13656. already know what the type of an expression should be, such as in the
  13657. \code{return} statement of a top-level function definition, or on the
  13658. right-hand side of an annotated assignment statement.
  13659. Getting back to \code{lambda}, it is straightforward to check a
  13660. \code{lambda} inside \code{check\_exp} because the expected type
  13661. provides the parameter types and the return type. On the other hand,
  13662. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  13663. that we do not allow \code{lambda} in contexts where we don't already
  13664. know its type. This restriction does not incur a loss of
  13665. expressiveness for \LangLam{} because it is straightforward to modify
  13666. a program to sidestep the restriction, for example, by using an
  13667. annotated assignment statement to assign the \code{lambda} to a
  13668. temporary variable.
  13669. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  13670. checker records their type in a \code{has\_type} field. This type
  13671. information is used later in this chapter.
  13672. %
  13673. \fi}
  13674. \begin{figure}[tbp]
  13675. {\if\edition\racketEd
  13676. \begin{lstlisting}
  13677. (define (type-check-Rlambda env)
  13678. (lambda (e)
  13679. (match e
  13680. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  13681. (define-values (new-body bodyT)
  13682. ((type-check-exp (append (map cons xs Ts) env)) body))
  13683. (define ty `(,@Ts -> ,rT))
  13684. (cond
  13685. [(equal? rT bodyT)
  13686. (values (HasType (Lambda params rT new-body) ty) ty)]
  13687. [else
  13688. (error "mismatch in return type" bodyT rT)])]
  13689. ...
  13690. )))
  13691. \end{lstlisting}
  13692. \fi}
  13693. {\if\edition\pythonEd
  13694. \begin{lstlisting}
  13695. class TypeCheckLlambda(TypeCheckLfun):
  13696. def type_check_exp(self, e, env):
  13697. match e:
  13698. case Name(id):
  13699. e.has_type = env[id]
  13700. return env[id]
  13701. case Lambda(params, body):
  13702. raise Exception('cannot synthesize a type for a lambda')
  13703. case _:
  13704. return super().type_check_exp(e, env)
  13705. def check_exp(self, e, ty, env):
  13706. match e:
  13707. case Lambda(params, body):
  13708. e.has_type = ty
  13709. match ty:
  13710. case FunctionType(params_t, return_t):
  13711. new_env = {x:t for (x,t) in env.items()}
  13712. for (p,t) in zip(params, params_t):
  13713. new_env[p] = t
  13714. self.check_exp(body, return_t, new_env)
  13715. case _:
  13716. raise Exception('lambda does not have type ' + str(ty))
  13717. case Call(func, args):
  13718. func_t = self.type_check_exp(func, env)
  13719. match func_t:
  13720. case FunctionType(params_t, return_t):
  13721. for (arg, param_t) in zip(args, params_t):
  13722. self.check_exp(arg, param_t, env)
  13723. self.check_type_equal(return_t, ty, e)
  13724. case _:
  13725. raise Exception('type_check_exp: in call, unexpected ' + \
  13726. repr(func_t))
  13727. case _:
  13728. t = self.type_check_exp(e, env)
  13729. self.check_type_equal(t, ty, e)
  13730. \end{lstlisting}
  13731. \fi}
  13732. \caption{Type checking \LangLam{}\python{, part 1}.}
  13733. \label{fig:type-check-Llambda}
  13734. \end{figure}
  13735. {\if\edition\pythonEd
  13736. \begin{figure}[tbp]
  13737. \begin{lstlisting}
  13738. def check_stmts(self, ss, return_ty, env):
  13739. if len(ss) == 0:
  13740. return
  13741. match ss[0]:
  13742. case FunctionDef(name, params, body, dl, returns, comment):
  13743. new_env = {x: t for (x,t) in env.items()}
  13744. for (x,t) in params:
  13745. new_env[x] = t
  13746. rt = self.check_stmts(body, returns, new_env)
  13747. self.check_stmts(ss[1:], return_ty, env)
  13748. case Return(value):
  13749. self.check_exp(value, return_ty, env)
  13750. case Assign([Name(id)], value):
  13751. if id in env:
  13752. self.check_exp(value, env[id], env)
  13753. else:
  13754. env[id] = self.type_check_exp(value, env)
  13755. self.check_stmts(ss[1:], return_ty, env)
  13756. case Assign([Subscript(tup, Constant(index), Store())], value):
  13757. tup_t = self.type_check_exp(tup, env)
  13758. match tup_t:
  13759. case TupleType(ts):
  13760. self.check_exp(value, ts[index], env)
  13761. case _:
  13762. raise Exception('expected a tuple, not ' + repr(tup_t))
  13763. self.check_stmts(ss[1:], return_ty, env)
  13764. case AnnAssign(Name(id), ty, value, simple):
  13765. ss[0].annotation = ty_annot
  13766. if id in env:
  13767. self.check_type_equal(env[id], ty)
  13768. else:
  13769. env[id] = ty_annot
  13770. self.check_exp(value, ty_annot, env)
  13771. case _:
  13772. self.type_check_stmts(ss, env)
  13773. def type_check(self, p):
  13774. match p:
  13775. case Module(body):
  13776. env = {}
  13777. for s in body:
  13778. match s:
  13779. case FunctionDef(name, params, bod, dl, returns, comment):
  13780. params_t = [t for (x,t) in params]
  13781. env[name] = FunctionType(params_t, returns)
  13782. self.check_stmts(body, int, env)
  13783. \end{lstlisting}
  13784. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  13785. \label{fig:type-check-Llambda-part2}
  13786. \end{figure}
  13787. \clearpage
  13788. \section{Assignment and Lexically Scoped Functions}
  13789. \label{sec:assignment-scoping}
  13790. The combination of lexically-scoped functions and assignment to
  13791. variables raises a challenge with our approach to implementing
  13792. lexically-scoped functions. Consider the following example in which
  13793. function \code{f} has a free variable \code{x} that is changed after
  13794. \code{f} is created but before the call to \code{f}.
  13795. % loop_test_11.rkt
  13796. {\if\edition\racketEd
  13797. \begin{lstlisting}
  13798. (let ([x 0])
  13799. (let ([y 0])
  13800. (let ([z 20])
  13801. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  13802. (begin
  13803. (set! x 10)
  13804. (set! y 12)
  13805. (f y))))))
  13806. \end{lstlisting}
  13807. \fi}
  13808. {\if\edition\pythonEd
  13809. % box_free_assign.py
  13810. \begin{lstlisting}
  13811. def g(z : int) -> int:
  13812. x = 0
  13813. y = 0
  13814. f : Callable[[int],int] = lambda a: a + x + z
  13815. x = 10
  13816. y = 12
  13817. return f(y)
  13818. print( g(20) )
  13819. \end{lstlisting}
  13820. \fi}
  13821. The correct output for this example is \code{42} because the call to
  13822. \code{f} is required to use the current value of \code{x} (which is
  13823. \code{10}). Unfortunately, the closure conversion pass
  13824. (Section~\ref{sec:closure-conversion}) generates code for the
  13825. \code{lambda} that copies the old value of \code{x} into a
  13826. closure. Thus, if we naively add support for assignment to our current
  13827. compiler, the output of this program would be \code{32}.
  13828. A first attempt at solving this problem would be to save a pointer to
  13829. \code{x} in the closure and change the occurrences of \code{x} inside
  13830. the lambda to dereference the pointer. Of course, this would require
  13831. assigning \code{x} to the stack and not to a register. However, the
  13832. problem goes a bit deeper.
  13833. %% Consider the following example in which we
  13834. %% create a counter abstraction by creating a pair of functions that
  13835. %% share the free variable \code{x}.
  13836. Consider the following example that returns a function that refers to
  13837. a local variable of the enclosing function.
  13838. \begin{center}
  13839. \begin{minipage}{\textwidth}
  13840. {\if\edition\racketEd
  13841. % similar to loop_test_10.rkt
  13842. %% \begin{lstlisting}
  13843. %% (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  13844. %% (vector
  13845. %% (lambda: () : Integer x)
  13846. %% (lambda: () : Void (set! x (+ 1 x)))))
  13847. %% (let ([counter (f 0)])
  13848. %% (let ([get (vector-ref counter 0)])
  13849. %% (let ([inc (vector-ref counter 1)])
  13850. %% (begin
  13851. %% (inc)
  13852. %% (get)))))
  13853. %% \end{lstlisting}
  13854. \begin{lstlisting}
  13855. (define (f []) : Integer
  13856. (let ([x 0])
  13857. (let ([g (lambda: () : Integer x)])
  13858. (begin
  13859. (set! x 42)
  13860. g))))
  13861. ((f))
  13862. \end{lstlisting}
  13863. \fi}
  13864. {\if\edition\pythonEd
  13865. % counter.py
  13866. \begin{lstlisting}
  13867. def f():
  13868. x = 0
  13869. g = lambda: x
  13870. x = 42
  13871. return g
  13872. print( f()() )
  13873. \end{lstlisting}
  13874. \fi}
  13875. \end{minipage}
  13876. \end{center}
  13877. In this example, the lifetime of \code{x} extends beyond the lifetime
  13878. of the call to \code{f}. Thus, if we were to store \code{x} on the
  13879. stack frame for the call to \code{f}, it would be gone by the time we
  13880. call \code{g}, leaving us with dangling pointers for
  13881. \code{x}. This example demonstrates that when a variable occurs free
  13882. inside a function, its lifetime becomes indefinite. Thus, the value of
  13883. the variable needs to live on the heap. The verb
  13884. \emph{box}\index{subject}{box} is often used for allocating a single
  13885. value on the heap, producing a pointer, and
  13886. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  13887. %% {\if\edition\racketEd
  13888. %% We recommend solving these problems by boxing the local variables that
  13889. %% are in the intersection of 1) variables that appear on the
  13890. %% left-hand-side of a \code{set!} and 2) variables that occur free
  13891. %% inside a \code{lambda}.
  13892. %% \fi}
  13893. %% {\if\edition\pythonEd
  13894. %% We recommend solving these problems by boxing the local variables that
  13895. %% are in the intersection of 1) variables whose values may change and 2)
  13896. %% variables that occur free inside a \code{lambda}.
  13897. %% \fi}
  13898. We shall introduce a new pass named
  13899. \code{convert\_assignments} in Section~\ref{sec:convert-assignments}
  13900. to address this challenge.
  13901. %
  13902. \racket{But before diving into the compiler passes, we have one more
  13903. problem to discuss.}
  13904. \if\edition\pythonEd
  13905. \section{Uniquify Variables}
  13906. \label{sec:uniquify-lambda}
  13907. With the addition of \code{lambda} we have a complication to deal
  13908. with: name shadowing. Consider the following program with a function
  13909. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  13910. \code{lambda} expressions. The first \code{lambda} has a parameter
  13911. that is also named \code{x}.
  13912. \begin{lstlisting}
  13913. def f(x:int, y:int) -> Callable[[int], int]:
  13914. g : Callable[[int],int] = (lambda x: x + y)
  13915. h : Callable[[int],int] = (lambda y: x + y)
  13916. x = input_int()
  13917. return g
  13918. print(f(0, 10)(32))
  13919. \end{lstlisting}
  13920. Many of our compiler passes rely on being able to connect variable
  13921. uses with their definitions using just the name of the variable,
  13922. including new passes in this chapter. However, in the above example
  13923. the name of the variable does not uniquely determine its
  13924. definition. To solve this problem we recommend implementing a pass
  13925. named \code{uniquify} that renames every variable in the program to
  13926. make sure they are all unique.
  13927. The following shows the result of \code{uniquify} for the above
  13928. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  13929. and the \code{x} parameter of the \code{lambda} is renamed to
  13930. \code{x\_4}.
  13931. \begin{lstlisting}
  13932. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  13933. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  13934. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  13935. x_0 = input_int()
  13936. return g_2
  13937. def main() -> int :
  13938. print(f(0, 10)(32))
  13939. return 0
  13940. \end{lstlisting}
  13941. \fi
  13942. \if\edition\racketEd
  13943. \section{Reveal Functions and the $F_2$ language}
  13944. \label{sec:reveal-functions-r5}
  13945. To support the \code{procedure-arity} operator we need to communicate
  13946. the arity of a function to the point of closure creation. We can
  13947. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  13948. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  13949. output of this pass is the language $F_2$, whose syntax is defined in
  13950. Figure~\ref{fig:f2-syntax}.
  13951. \begin{figure}[tp]
  13952. \centering
  13953. \fbox{
  13954. \begin{minipage}{0.96\textwidth}
  13955. \[
  13956. \begin{array}{lcl}
  13957. \Exp &::=& \ldots \MID \FUNREFARITY{\Var}{\Int}\\
  13958. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13959. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  13960. \end{array}
  13961. \]
  13962. \end{minipage}
  13963. }
  13964. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  13965. (Figure~\ref{fig:Rlam-syntax}).}
  13966. \label{fig:f2-syntax}
  13967. \end{figure}
  13968. \fi
  13969. \section{Assignment Conversion}
  13970. \label{sec:convert-assignments}
  13971. The purpose of the \code{convert\_assignments} pass is address the
  13972. challenge posed in Section~\ref{sec:assignment-scoping} regarding the
  13973. interaction between variable assignments and closure conversion.
  13974. First we identify which variables need to be boxed, then we transform
  13975. the program to box those variables. In general, boxing introduces
  13976. runtime overhead that we would like to avoid, so we should box as few
  13977. variables as possible. We recommend boxing the variables in the
  13978. intersection of the following two sets of variables:
  13979. \begin{enumerate}
  13980. \item The variables that are free in a \code{lambda}.
  13981. \item The variables that appear on the left-hand side of an
  13982. assignment.
  13983. \end{enumerate}
  13984. Consider again the first example from
  13985. Section~\ref{sec:assignment-scoping}:
  13986. %
  13987. {\if\edition\racketEd
  13988. \begin{lstlisting}
  13989. (let ([x 0])
  13990. (let ([y 0])
  13991. (let ([z 20])
  13992. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  13993. (begin
  13994. (set! x 10)
  13995. (set! y 12)
  13996. (f y))))))
  13997. \end{lstlisting}
  13998. \fi}
  13999. {\if\edition\pythonEd
  14000. \begin{lstlisting}
  14001. def g(z : int) -> int:
  14002. x = 0
  14003. y = 0
  14004. f : Callable[[int],int] = lambda a: a + x + z
  14005. x = 10
  14006. y = 12
  14007. return f(y)
  14008. print( g(20) )
  14009. \end{lstlisting}
  14010. \fi}
  14011. %
  14012. \noindent The variables \code{x} and \code{y} are assigned-to. The
  14013. variables \code{x} and \code{z} occur free inside the
  14014. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  14015. \code{y} or \code{z}. The boxing of \code{x} consists of three
  14016. transformations: initialize \code{x} with a tuple, replace reads from
  14017. \code{x} with tuple reads, and replace each assignment to \code{x}
  14018. with a tuple writes. The output of \code{convert\_assignments} for
  14019. this example is as follows.
  14020. %
  14021. {\if\edition\racketEd
  14022. \begin{lstlisting}
  14023. (define (main) : Integer
  14024. (let ([x0 (vector 0)])
  14025. (let ([y1 0])
  14026. (let ([z2 20])
  14027. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  14028. (+ a3 (+ (vector-ref x0 0) z2)))])
  14029. (begin
  14030. (vector-set! x0 0 10)
  14031. (set! y1 12)
  14032. (f4 y1)))))))
  14033. \end{lstlisting}
  14034. \fi}
  14035. %
  14036. {\if\edition\pythonEd
  14037. \begin{lstlisting}
  14038. def g(z : int)-> int:
  14039. x = (0,)
  14040. x[0] = 0
  14041. y = 0
  14042. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  14043. x[0] = 10
  14044. y = 12
  14045. return f(y)
  14046. def main() -> int:
  14047. print(g(20))
  14048. return 0
  14049. \end{lstlisting}
  14050. \fi}
  14051. To compute the free variables of all the \code{lambda} expressions, we
  14052. recommend defining two auxiliary functions:
  14053. \begin{enumerate}
  14054. \item \code{free\_variables} computes the free variables of an expression, and
  14055. \item \code{free\_in\_lambda} collects all of the variables that are
  14056. free in any of the \code{lambda} expressions, using
  14057. \code{free\_variables} in the case for each \code{lambda}.
  14058. \end{enumerate}
  14059. {\if\edition\racketEd
  14060. %
  14061. To compute the variables that are assigned-to, we recommend using the
  14062. \code{collect-set!} function that we introduced in
  14063. Section~\ref{sec:uncover-get-bang}, but updated to include the new AST
  14064. forms such as \code{Lambda}.
  14065. %
  14066. \fi}
  14067. {\if\edition\pythonEd
  14068. %
  14069. To compute the variables that are assigned-to, we recommend defining
  14070. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  14071. the set of variables that occur in the left-hand side of an assignment
  14072. statement, and otherwise returns the empty set.
  14073. %
  14074. \fi}
  14075. Let $\mathit{AF}$ be the intersection of the set of variables that are
  14076. free in a \code{lambda} and that are assigned-to in the enclosing
  14077. function definition.
  14078. Next we discuss the \code{convert\_assignments} pass. In the case for
  14079. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  14080. $\VAR{x}$ to a tuple read.
  14081. %
  14082. {\if\edition\racketEd
  14083. \begin{lstlisting}
  14084. (Var |$x$|)
  14085. |$\Rightarrow$|
  14086. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  14087. \end{lstlisting}
  14088. \fi}
  14089. %
  14090. {\if\edition\pythonEd
  14091. \begin{lstlisting}
  14092. Name(|$x$|)
  14093. |$\Rightarrow$|
  14094. Subscript(Name(|$x$|), Constant(0), Load())
  14095. \end{lstlisting}
  14096. \fi}
  14097. %
  14098. %
  14099. In the case for assignment, recursively process the right-hand side
  14100. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in $\mathit{AF}$, translate
  14101. the assignment into a tuple-write as follows.
  14102. %
  14103. {\if\edition\racketEd
  14104. \begin{lstlisting}
  14105. (SetBang |$x$| |$\itm{rhs}$|)
  14106. |$\Rightarrow$|
  14107. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  14108. \end{lstlisting}
  14109. \fi}
  14110. {\if\edition\pythonEd
  14111. \begin{lstlisting}
  14112. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  14113. |$\Rightarrow$|
  14114. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  14115. \end{lstlisting}
  14116. \fi}
  14117. %
  14118. {\if\edition\racketEd
  14119. The case for \code{Lambda} is non-trivial, but it is similar to the
  14120. case for function definitions, which we discuss next.
  14121. \fi}
  14122. To translate a function definition, we first compute $\mathit{AF}$,
  14123. the intersection of the variables that are free in a \code{lambda} and
  14124. that are assigned-to. We then apply assignment conversion to the body
  14125. of the function definition. Finally, we box the parameters of this
  14126. function definition that are in $\mathit{AF}$. For example,
  14127. the parameter \code{x} of the follow function \code{g}
  14128. needs to be boxed.
  14129. {\if\edition\racketEd
  14130. \begin{lstlisting}
  14131. (define (g [x : Integer]) : Integer
  14132. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  14133. (begin
  14134. (set! x 10)
  14135. (f 32))))
  14136. \end{lstlisting}
  14137. \fi}
  14138. %
  14139. {\if\edition\pythonEd
  14140. \begin{lstlisting}
  14141. def g(x : int) -> int:
  14142. f : Callable[[int],int] = lambda a: a + x
  14143. x = 10
  14144. return f(32)
  14145. \end{lstlisting}
  14146. \fi}
  14147. %
  14148. \noindent We box parameter \code{x} by creating a local variable named
  14149. \code{x} that is initialized to a tuple whose contents is the value of
  14150. the parameter, which we has been renamed.
  14151. %
  14152. {\if\edition\racketEd
  14153. \begin{lstlisting}
  14154. (define (g [x_0 : Integer]) : Integer
  14155. (let ([x (vector x_0)])
  14156. (let ([f (lambda: ([a : Integer]) : Integer
  14157. (+ a (vector-ref x 0)))])
  14158. (begin
  14159. (vector-set! x 0 10)
  14160. (f 32)))))
  14161. \end{lstlisting}
  14162. \fi}
  14163. %
  14164. {\if\edition\pythonEd
  14165. \begin{lstlisting}
  14166. def g(x_0 : int)-> int:
  14167. x = (x_0,)
  14168. f : Callable[[int], int] = (lambda a: a + x[0])
  14169. x[0] = 10
  14170. return f(32)
  14171. \end{lstlisting}
  14172. \fi}
  14173. %% Recall the second example in Section~\ref{sec:assignment-scoping}
  14174. %% involving a counter abstraction. The following is the output of
  14175. %% assignment version for function \code{f}.
  14176. %% \begin{lstlisting}
  14177. %% (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  14178. %% (vector
  14179. %% (lambda: () : Integer x1)
  14180. %% (lambda: () : Void (set! x1 (+ 1 x1)))))
  14181. %% |$\Rightarrow$|
  14182. %% (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  14183. %% (let ([x1 (vector param_x1)])
  14184. %% (vector (lambda: () : Integer (vector-ref x1 0))
  14185. %% (lambda: () : Void
  14186. %% (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  14187. %% \end{lstlisting}
  14188. \section{Closure Conversion}
  14189. \label{sec:closure-conversion}
  14190. \index{subject}{closure conversion}
  14191. The compiling of lexically-scoped functions into top-level function
  14192. definitions is accomplished in the pass \code{convert\_to\_closures}
  14193. that comes after \code{reveal\_functions} and before
  14194. \code{limit\_functions}.
  14195. As usual, we implement the pass as a recursive function over the
  14196. AST. The interesting cases are the ones for \key{lambda} and function
  14197. application. We transform a \key{lambda} expression into an expression
  14198. that creates a closure, that is, a tuple whose first element is a
  14199. function pointer and the rest of the elements are the values of the
  14200. free variables of the \key{lambda}.
  14201. %
  14202. \racket{However, we use the \code{Closure}
  14203. AST node instead of using a tuple so that we can record the arity
  14204. which is needed for \code{procedure-arity} and
  14205. to distinguish closures from tuples in
  14206. Section~\ref{sec:optimize-closures}.}
  14207. %
  14208. In the generated code below, \itm{fvs} is the free variables of the
  14209. lambda and \itm{name} is a unique symbol generated to identify the lambda.
  14210. %
  14211. \racket{The \itm{arity} is the number of parameters (the length of
  14212. \itm{ps}).}
  14213. %
  14214. {\if\edition\racketEd
  14215. \begin{lstlisting}
  14216. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  14217. |$\Rightarrow$|
  14218. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  14219. \end{lstlisting}
  14220. \fi}
  14221. %
  14222. {\if\edition\pythonEd
  14223. \begin{lstlisting}
  14224. Lambda(|\itm{ps}|, |\itm{body}|)
  14225. |$\Rightarrow$|
  14226. Tuple([FunRef(|\itm{name}|), |\itm{fvs}, \ldots|])
  14227. \end{lstlisting}
  14228. \fi}
  14229. %
  14230. In addition to transforming each \key{Lambda} AST node into a
  14231. tuple, we create a top-level function definition for each
  14232. \key{Lambda}, as shown below.\\
  14233. \begin{minipage}{0.8\textwidth}
  14234. {\if\edition\racketEd
  14235. \begin{lstlisting}
  14236. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  14237. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  14238. ...
  14239. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  14240. |\itm{body'}|)...))
  14241. \end{lstlisting}
  14242. \fi}
  14243. {\if\edition\pythonEd
  14244. \begin{lstlisting}
  14245. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  14246. |$\itm{fvs}_1$| = clos[1]
  14247. |$\ldots$|
  14248. |$\itm{fvs}_n$| = clos[|$n$|]
  14249. |\itm{body'}|
  14250. \end{lstlisting}
  14251. \fi}
  14252. \end{minipage}\\
  14253. The \code{clos} parameter refers to the closure. Translate the type
  14254. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  14255. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  14256. \itm{closTy} is a tuple type whose first element type is
  14257. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  14258. the element types are the types of the free variables in the
  14259. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  14260. is non-trivial to give a type to the function in the closure's type.%
  14261. %
  14262. \footnote{To give an accurate type to a closure, we would need to add
  14263. existential types to the type checker~\citep{Minamide:1996ys}.}
  14264. %
  14265. %% The dummy type is considered to be equal to any other type during type
  14266. %% checking.
  14267. The free variables become local variables that are initialized with
  14268. their values in the closure.
  14269. Closure conversion turns every function into a tuple, so the type
  14270. annotations in the program must also be translated. We recommend
  14271. defining an auxiliary recursive function for this purpose. Function
  14272. types should be translated as follows.
  14273. %
  14274. {\if\edition\racketEd
  14275. \begin{lstlisting}
  14276. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  14277. |$\Rightarrow$|
  14278. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  14279. \end{lstlisting}
  14280. \fi}
  14281. {\if\edition\pythonEd
  14282. \begin{lstlisting}
  14283. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  14284. |$\Rightarrow$|
  14285. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  14286. \end{lstlisting}
  14287. \fi}
  14288. %
  14289. The above type says that the first thing in the tuple is a
  14290. function. The first parameter of the function is a tuple (a closure)
  14291. and the rest of the parameters are the ones from the original
  14292. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  14293. omits the types of the free variables because 1) those types are not
  14294. available in this context and 2) we do not need them in the code that
  14295. is generated for function application.
  14296. We transform function application into code that retrieves the
  14297. function from the closure and then calls the function, passing in the
  14298. closure as the first argument. We place $e'$ in a temporary variable
  14299. to avoid code duplication.
  14300. \begin{center}
  14301. \begin{minipage}{\textwidth}
  14302. {\if\edition\racketEd
  14303. \begin{lstlisting}
  14304. (Apply |$e$| |$\itm{es}$|)
  14305. |$\Rightarrow$|
  14306. (Let |$\itm{tmp}$| |$e'$|
  14307. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons |$\itm{tmp}$| |$\itm{es'}$|)))
  14308. \end{lstlisting}
  14309. \fi}
  14310. %
  14311. {\if\edition\pythonEd
  14312. \begin{lstlisting}
  14313. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  14314. |$\Rightarrow$|
  14315. Let(|$\itm{tmp}$|, |$e'$|,
  14316. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  14317. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  14318. \end{lstlisting}
  14319. \fi}
  14320. \end{minipage}
  14321. \end{center}
  14322. There is also the question of what to do with references to top-level
  14323. function definitions. To maintain a uniform translation of function
  14324. application, we turn function references into closures.
  14325. \begin{tabular}{lll}
  14326. \begin{minipage}{0.3\textwidth}
  14327. {\if\edition\racketEd
  14328. \begin{lstlisting}
  14329. (FunRefArity |$f$| |$n$|)
  14330. \end{lstlisting}
  14331. \fi}
  14332. {\if\edition\pythonEd
  14333. \begin{lstlisting}
  14334. FunRefArity(|$f$|, |$n$|)
  14335. \end{lstlisting}
  14336. \fi}
  14337. \end{minipage}
  14338. &
  14339. $\Rightarrow$
  14340. &
  14341. \begin{minipage}{0.5\textwidth}
  14342. {\if\edition\racketEd
  14343. \begin{lstlisting}
  14344. (Closure |$n$| (FunRef |$f$|) '())
  14345. \end{lstlisting}
  14346. \fi}
  14347. {\if\edition\pythonEd
  14348. \begin{lstlisting}
  14349. Tuple([FunRef(|$f$|)])
  14350. \end{lstlisting}
  14351. \fi}
  14352. \end{minipage}
  14353. \end{tabular} \\
  14354. %
  14355. The top-level function definitions need to be updated as well to take
  14356. an extra closure parameter.
  14357. \section{An Example Translation}
  14358. \label{sec:example-lambda}
  14359. Figure~\ref{fig:lexical-functions-example} shows the result of
  14360. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  14361. program demonstrating lexical scoping that we discussed at the
  14362. beginning of this chapter.
  14363. \begin{figure}[tbp]
  14364. \begin{minipage}{0.8\textwidth}
  14365. {\if\edition\racketEd
  14366. % tests/lambda_test_6.rkt
  14367. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14368. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  14369. (let ([y8 4])
  14370. (lambda: ([z9 : Integer]) : Integer
  14371. (+ x7 (+ y8 z9)))))
  14372. (define (main) : Integer
  14373. (let ([g0 ((fun-ref-arity f6 1) 5)])
  14374. (let ([h1 ((fun-ref-arity f6 1) 3)])
  14375. (+ (g0 11) (h1 15)))))
  14376. \end{lstlisting}
  14377. $\Rightarrow$
  14378. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14379. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  14380. (let ([y8 4])
  14381. (closure 1 (list (fun-ref lambda2) x7 y8))))
  14382. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  14383. (let ([x7 (vector-ref fvs3 1)])
  14384. (let ([y8 (vector-ref fvs3 2)])
  14385. (+ x7 (+ y8 z9)))))
  14386. (define (main) : Integer
  14387. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  14388. ((vector-ref clos5 0) clos5 5))])
  14389. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  14390. ((vector-ref clos6 0) clos6 3))])
  14391. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  14392. \end{lstlisting}
  14393. \fi}
  14394. %
  14395. {\if\edition\pythonEd
  14396. % free_var.py
  14397. \begin{lstlisting}
  14398. def f(x : int) -> Callable[[int], int]:
  14399. y = 4
  14400. return lambda z: x + y + z
  14401. g = f(5)
  14402. h = f(3)
  14403. print( g(11) + h(15) )
  14404. \end{lstlisting}
  14405. $\Rightarrow$
  14406. \begin{lstlisting}
  14407. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  14408. x = fvs_1[1]
  14409. y = fvs_1[2]
  14410. return x + y[0] + z
  14411. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  14412. y = (777,)
  14413. y[0] = 4
  14414. return (lambda_0, y, x)
  14415. def main() -> int:
  14416. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  14417. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  14418. print((let clos_5 = g in clos_5[0](clos_5, 11))
  14419. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  14420. return 0
  14421. \end{lstlisting}
  14422. \fi}
  14423. \end{minipage}
  14424. \caption{Example of closure conversion.}
  14425. \label{fig:lexical-functions-example}
  14426. \end{figure}
  14427. \begin{exercise}\normalfont
  14428. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  14429. Create 5 new programs that use \key{lambda} functions and make use of
  14430. lexical scoping. Test your compiler on these new programs and all of
  14431. your previously created test programs.
  14432. \end{exercise}
  14433. \if\edition\racketEd
  14434. \section{Expose Allocation}
  14435. \label{sec:expose-allocation-r5}
  14436. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  14437. that allocates and initializes a vector, similar to the translation of
  14438. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  14439. The only difference is replacing the use of
  14440. \ALLOC{\itm{len}}{\itm{type}} with
  14441. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  14442. \section{Explicate Control and \LangCLam{}}
  14443. \label{sec:explicate-r5}
  14444. The output language of \code{explicate\_control} is \LangCLam{} whose
  14445. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  14446. difference with respect to \LangCFun{} is the addition of the
  14447. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  14448. of \code{AllocateClosure} in the \code{explicate\_control} pass is
  14449. similar to the handling of other expressions such as primitive
  14450. operators.
  14451. \begin{figure}[tp]
  14452. \fbox{
  14453. \begin{minipage}{0.96\textwidth}
  14454. \small
  14455. {\if\edition\racketEd
  14456. \[
  14457. \begin{array}{lcl}
  14458. \Exp &::= & \ldots
  14459. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  14460. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  14461. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  14462. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  14463. \MID \GOTO{\itm{label}} } \\
  14464. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  14465. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  14466. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  14467. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  14468. \end{array}
  14469. \]
  14470. \fi}
  14471. \end{minipage}
  14472. }
  14473. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  14474. \label{fig:c4-syntax}
  14475. \end{figure}
  14476. \section{Select Instructions}
  14477. \label{sec:select-instructions-Rlambda}
  14478. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  14479. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  14480. (Section~\ref{sec:select-instructions-gc}). The only difference is
  14481. that you should place the \itm{arity} in the tag that is stored at
  14482. position $0$ of the vector. Recall that in
  14483. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  14484. was not used. We store the arity in the $5$ bits starting at position
  14485. $58$.
  14486. Compile the \code{procedure-arity} operator into a sequence of
  14487. instructions that access the tag from position $0$ of the vector and
  14488. extract the $5$-bits starting at position $58$ from the tag.
  14489. \fi
  14490. \begin{figure}[p]
  14491. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14492. \node (Rfun) at (0,2) {\large \LangLam{}};
  14493. \node (Rfun-2) at (3,2) {\large \LangLam{}};
  14494. \node (Rfun-3) at (6,2) {\large \LangLam{}};
  14495. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  14496. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  14497. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  14498. \node (F1-3) at (6,0) {\large \LangFunRef{}};
  14499. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  14500. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14501. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  14502. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14503. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14504. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14505. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14506. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14507. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14508. \path[->,bend left=15] (Rfun) edge [above] node
  14509. {\ttfamily\footnotesize shrink} (Rfun-2);
  14510. \path[->,bend left=15] (Rfun-2) edge [above] node
  14511. {\ttfamily\footnotesize uniquify} (Rfun-3);
  14512. \path[->,bend left=15] (Rfun-3) edge [above] node
  14513. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  14514. \path[->,bend left=15] (F1-0) edge [right] node
  14515. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  14516. \path[->,bend left=15] (F1-1) edge [below] node
  14517. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  14518. \path[->,bend right=15] (F1-2) edge [above] node
  14519. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  14520. \path[->,bend right=15] (F1-3) edge [above] node
  14521. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  14522. \path[->,bend right=15] (F1-4) edge [above] node
  14523. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  14524. \path[->,bend right=15] (F1-5) edge [right] node
  14525. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14526. \path[->,bend left=15] (C3-2) edge [left] node
  14527. {\ttfamily\footnotesize select\_instr.} (x86-2);
  14528. \path[->,bend right=15] (x86-2) edge [left] node
  14529. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14530. \path[->,bend right=15] (x86-2-1) edge [below] node
  14531. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  14532. \path[->,bend right=15] (x86-2-2) edge [left] node
  14533. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  14534. \path[->,bend left=15] (x86-3) edge [above] node
  14535. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  14536. \path[->,bend left=15] (x86-4) edge [right] node
  14537. {\ttfamily\footnotesize print\_x86} (x86-5);
  14538. \end{tikzpicture}
  14539. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  14540. functions.}
  14541. \label{fig:Rlambda-passes}
  14542. \end{figure}
  14543. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  14544. for the compilation of \LangLam{}.
  14545. \clearpage
  14546. \section{Challenge: Optimize Closures}
  14547. \label{sec:optimize-closures}
  14548. In this chapter we compiled lexically-scoped functions into a
  14549. relatively efficient representation: flat closures. However, even this
  14550. representation comes with some overhead. For example, consider the
  14551. following program with a function \code{tail\_sum} that does not have
  14552. any free variables and where all the uses of \code{tail\_sum} are in
  14553. applications where we know that only \code{tail\_sum} is being applied
  14554. (and not any other functions).
  14555. \begin{center}
  14556. \begin{minipage}{0.95\textwidth}
  14557. \begin{lstlisting}
  14558. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  14559. (if (eq? n 0)
  14560. r
  14561. (tail_sum (- n 1) (+ n r))))
  14562. (+ (tail_sum 5 0) 27)
  14563. \end{lstlisting}
  14564. \end{minipage}
  14565. \end{center}
  14566. As described in this chapter, we uniformly apply closure conversion to
  14567. all functions, obtaining the following output for this program.
  14568. \begin{center}
  14569. \begin{minipage}{0.95\textwidth}
  14570. \begin{lstlisting}
  14571. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  14572. (if (eq? n2 0)
  14573. r3
  14574. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  14575. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  14576. (define (main) : Integer
  14577. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  14578. ((vector-ref clos6 0) clos6 5 0)) 27))
  14579. \end{lstlisting}
  14580. \end{minipage}
  14581. \end{center}
  14582. In the previous Chapter, there would be no allocation in the program
  14583. and the calls to \code{tail\_sum} would be direct calls. In contrast,
  14584. the above program allocates memory for each \code{closure} and the
  14585. calls to \code{tail\_sum} are indirect. These two differences incur
  14586. considerable overhead in a program such as this one, where the
  14587. allocations and indirect calls occur inside a tight loop.
  14588. One might think that this problem is trivial to solve: can't we just
  14589. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  14590. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  14591. e'_n$)} instead of treating it like a call to a closure? We would
  14592. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  14593. %
  14594. However, this problem is not so trivial because a global function may
  14595. ``escape'' and become involved in applications that also involve
  14596. closures. Consider the following example in which the application
  14597. \code{(f 41)} needs to be compiled into a closure application, because
  14598. the \code{lambda} may get bound to \code{f}, but the \code{inc}
  14599. function might also get bound to \code{f}.
  14600. \begin{lstlisting}
  14601. (define (inc [x : Integer]) : Integer
  14602. (+ x 1))
  14603. (let ([y (read)])
  14604. (let ([f (if (eq? (read) 0)
  14605. inc
  14606. (lambda: ([x : Integer]) : Integer (- x y)))])
  14607. (f 41)))
  14608. \end{lstlisting}
  14609. If a global function name is used in any way other than as the
  14610. operator in a direct call, then we say that the function
  14611. \emph{escapes}. If a global function does not escape, then we do not
  14612. need to perform closure conversion on the function.
  14613. \begin{exercise}\normalfont
  14614. Implement an auxiliary function for detecting which global
  14615. functions escape. Using that function, implement an improved version
  14616. of closure conversion that does not apply closure conversion to
  14617. global functions that do not escape but instead compiles them as
  14618. regular functions. Create several new test cases that check whether
  14619. you properly detect whether global functions escape or not.
  14620. \end{exercise}
  14621. So far we have reduced the overhead of calling global functions, but
  14622. it would also be nice to reduce the overhead of calling a
  14623. \code{lambda} when we can determine at compile time which
  14624. \code{lambda} will be called. We refer to such calls as \emph{known
  14625. calls}. Consider the following example in which a \code{lambda} is
  14626. bound to \code{f} and then applied.
  14627. \begin{lstlisting}
  14628. (let ([y (read)])
  14629. (let ([f (lambda: ([x : Integer]) : Integer
  14630. (+ x y))])
  14631. (f 21)))
  14632. \end{lstlisting}
  14633. Closure conversion compiles \code{(f 21)} into an indirect call:
  14634. \begin{lstlisting}
  14635. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  14636. (let ([y2 (vector-ref fvs6 1)])
  14637. (+ x3 y2)))
  14638. (define (main) : Integer
  14639. (let ([y2 (read)])
  14640. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  14641. ((vector-ref f4 0) f4 21))))
  14642. \end{lstlisting}
  14643. but we can instead compile the application \code{(f 21)} into a direct call
  14644. to \code{lambda5}:
  14645. \begin{lstlisting}
  14646. (define (main) : Integer
  14647. (let ([y2 (read)])
  14648. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  14649. ((fun-ref lambda5) f4 21))))
  14650. \end{lstlisting}
  14651. The problem of determining which lambda will be called from a
  14652. particular application is quite challenging in general and the topic
  14653. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  14654. following exercise we recommend that you compile an application to a
  14655. direct call when the operator is a variable and the variable is
  14656. \code{let}-bound to a closure. This can be accomplished by maintaining
  14657. an environment mapping \code{let}-bound variables to function names.
  14658. Extend the environment whenever you encounter a closure on the
  14659. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  14660. to the name of the global function for the closure. This pass should
  14661. come after closure conversion.
  14662. \begin{exercise}\normalfont
  14663. Implement a compiler pass, named \code{optimize-known-calls}, that
  14664. compiles known calls into direct calls. Verify that your compiler is
  14665. successful in this regard on several example programs.
  14666. \end{exercise}
  14667. These exercises only scratches the surface of optimizing of
  14668. closures. A good next step for the interested reader is to look at the
  14669. work of \citet{Keep:2012ab}.
  14670. \section{Further Reading}
  14671. The notion of lexically scoped anonymous functions predates modern
  14672. computers by about a decade. They were invented by
  14673. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  14674. foundation for logic. Anonymous functions were included in the
  14675. LISP~\citep{McCarthy:1960dz} programming language but were initially
  14676. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  14677. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  14678. compile Scheme programs. However, environments were represented as
  14679. linked lists, so variable lookup was linear in the size of the
  14680. environment. In this chapter we represent environments using flat
  14681. closures, which were invented by
  14682. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  14683. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  14684. closures, variable lookup is constant time but the time to create a
  14685. closure is proportional to the number of its free variables. Flat
  14686. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  14687. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  14688. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14689. \chapter{Dynamic Typing}
  14690. \label{ch:Rdyn}
  14691. \index{subject}{dynamic typing}
  14692. \if\edition\racketEd
  14693. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  14694. typed language that is a subset of Racket. This is in contrast to the
  14695. previous chapters, which have studied the compilation of Typed
  14696. Racket. In dynamically typed languages such as \LangDyn{}, a given
  14697. expression may produce a value of a different type each time it is
  14698. executed. Consider the following example with a conditional \code{if}
  14699. expression that may return a Boolean or an integer depending on the
  14700. input to the program.
  14701. % part of dynamic_test_25.rkt
  14702. \begin{lstlisting}
  14703. (not (if (eq? (read) 1) #f 0))
  14704. \end{lstlisting}
  14705. Languages that allow expressions to produce different kinds of values
  14706. are called \emph{polymorphic}, a word composed of the Greek roots
  14707. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  14708. are several kinds of polymorphism in programming languages, such as
  14709. subtype polymorphism and parametric
  14710. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  14711. study in this chapter does not have a special name but it is the kind
  14712. that arises in dynamically typed languages.
  14713. Another characteristic of dynamically typed languages is that
  14714. primitive operations, such as \code{not}, are often defined to operate
  14715. on many different types of values. In fact, in Racket, the \code{not}
  14716. operator produces a result for any kind of value: given \code{\#f} it
  14717. returns \code{\#t} and given anything else it returns \code{\#f}.
  14718. Furthermore, even when primitive operations restrict their inputs to
  14719. values of a certain type, this restriction is enforced at runtime
  14720. instead of during compilation. For example, the following vector
  14721. reference results in a run-time contract violation because the index
  14722. must be in integer, not a Boolean such as \code{\#t}.
  14723. \begin{lstlisting}
  14724. (vector-ref (vector 42) #t)
  14725. \end{lstlisting}
  14726. \begin{figure}[tp]
  14727. \centering
  14728. \fbox{
  14729. \begin{minipage}{0.97\textwidth}
  14730. \[
  14731. \begin{array}{rcl}
  14732. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  14733. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  14734. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  14735. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  14736. &\MID& \key{\#t} \MID \key{\#f}
  14737. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  14738. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  14739. \MID \CUNIOP{\key{not}}{\Exp} \\
  14740. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  14741. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  14742. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  14743. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  14744. &\MID& \LP\Exp \; \Exp\ldots\RP
  14745. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  14746. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  14747. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  14748. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  14749. \LangDynM{} &::=& \Def\ldots\; \Exp
  14750. \end{array}
  14751. \]
  14752. \end{minipage}
  14753. }
  14754. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  14755. \label{fig:r7-concrete-syntax}
  14756. \end{figure}
  14757. \begin{figure}[tp]
  14758. \centering
  14759. \fbox{
  14760. \begin{minipage}{0.96\textwidth}
  14761. \small
  14762. \[
  14763. \begin{array}{lcl}
  14764. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  14765. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  14766. &\MID& \BOOL{\itm{bool}}
  14767. \MID \IF{\Exp}{\Exp}{\Exp} \\
  14768. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  14769. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  14770. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  14771. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  14772. \end{array}
  14773. \]
  14774. \end{minipage}
  14775. }
  14776. \caption{The abstract syntax of \LangDyn{}.}
  14777. \label{fig:r7-syntax}
  14778. \end{figure}
  14779. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  14780. defined in Figures~\ref{fig:r7-concrete-syntax} and
  14781. \ref{fig:r7-syntax}.
  14782. %
  14783. There is no type checker for \LangDyn{} because it is not a statically
  14784. typed language (it's dynamically typed!).
  14785. The definitional interpreter for \LangDyn{} is presented in
  14786. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  14787. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  14788. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  14789. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  14790. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  14791. value} that combines an underlying value with a tag that identifies
  14792. what kind of value it is. We define the following struct
  14793. to represented tagged values.
  14794. \begin{lstlisting}
  14795. (struct Tagged (value tag) #:transparent)
  14796. \end{lstlisting}
  14797. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  14798. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  14799. but don't always capture all the information that a type does. For
  14800. example, a vector of type \code{(Vector Any Any)} is tagged with
  14801. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  14802. is tagged with \code{Procedure}.
  14803. Next consider the match case for \code{vector-ref}. The
  14804. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  14805. is used to ensure that the first argument is a vector and the second
  14806. is an integer. If they are not, a \code{trapped-error} is raised.
  14807. Recall from Section~\ref{sec:interp_Lint} that when a definition
  14808. interpreter raises a \code{trapped-error} error, the compiled code
  14809. must also signal an error by exiting with return code \code{255}. A
  14810. \code{trapped-error} is also raised if the index is not less than
  14811. length of the vector.
  14812. \begin{figure}[tbp]
  14813. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14814. (define ((interp-Rdyn-exp env) ast)
  14815. (define recur (interp-Rdyn-exp env))
  14816. (match ast
  14817. [(Var x) (lookup x env)]
  14818. [(Int n) (Tagged n 'Integer)]
  14819. [(Bool b) (Tagged b 'Boolean)]
  14820. [(Lambda xs rt body)
  14821. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  14822. [(Prim 'vector es)
  14823. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  14824. [(Prim 'vector-ref (list e1 e2))
  14825. (define vec (recur e1)) (define i (recur e2))
  14826. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  14827. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  14828. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  14829. (vector-ref (Tagged-value vec) (Tagged-value i))]
  14830. [(Prim 'vector-set! (list e1 e2 e3))
  14831. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  14832. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  14833. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  14834. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  14835. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  14836. (Tagged (void) 'Void)]
  14837. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  14838. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  14839. [(Prim 'or (list e1 e2))
  14840. (define v1 (recur e1))
  14841. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  14842. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  14843. [(Prim op (list e1))
  14844. #:when (set-member? type-predicates op)
  14845. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  14846. [(Prim op es)
  14847. (define args (map recur es))
  14848. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  14849. (unless (for/or ([expected-tags (op-tags op)])
  14850. (equal? expected-tags tags))
  14851. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  14852. (tag-value
  14853. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  14854. [(If q t f)
  14855. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  14856. [(Apply f es)
  14857. (define new-f (recur f)) (define args (map recur es))
  14858. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  14859. (match f-val
  14860. [`(function ,xs ,body ,lam-env)
  14861. (unless (eq? (length xs) (length args))
  14862. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  14863. (define new-env (append (map cons xs args) lam-env))
  14864. ((interp-Rdyn-exp new-env) body)]
  14865. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  14866. \end{lstlisting}
  14867. \caption{Interpreter for the \LangDyn{} language.}
  14868. \label{fig:interp-Rdyn}
  14869. \end{figure}
  14870. \begin{figure}[tbp]
  14871. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14872. (define (interp-op op)
  14873. (match op
  14874. ['+ fx+]
  14875. ['- fx-]
  14876. ['read read-fixnum]
  14877. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  14878. ['< (lambda (v1 v2)
  14879. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  14880. ['<= (lambda (v1 v2)
  14881. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  14882. ['> (lambda (v1 v2)
  14883. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  14884. ['>= (lambda (v1 v2)
  14885. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  14886. ['boolean? boolean?]
  14887. ['integer? fixnum?]
  14888. ['void? void?]
  14889. ['vector? vector?]
  14890. ['vector-length vector-length]
  14891. ['procedure? (match-lambda
  14892. [`(functions ,xs ,body ,env) #t] [else #f])]
  14893. [else (error 'interp-op "unknown operator" op)]))
  14894. (define (op-tags op)
  14895. (match op
  14896. ['+ '((Integer Integer))]
  14897. ['- '((Integer Integer) (Integer))]
  14898. ['read '(())]
  14899. ['not '((Boolean))]
  14900. ['< '((Integer Integer))]
  14901. ['<= '((Integer Integer))]
  14902. ['> '((Integer Integer))]
  14903. ['>= '((Integer Integer))]
  14904. ['vector-length '((Vector))]))
  14905. (define type-predicates
  14906. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  14907. (define (tag-value v)
  14908. (cond [(boolean? v) (Tagged v 'Boolean)]
  14909. [(fixnum? v) (Tagged v 'Integer)]
  14910. [(procedure? v) (Tagged v 'Procedure)]
  14911. [(vector? v) (Tagged v 'Vector)]
  14912. [(void? v) (Tagged v 'Void)]
  14913. [else (error 'tag-value "unidentified value ~a" v)]))
  14914. (define (check-tag val expected ast)
  14915. (define tag (Tagged-tag val))
  14916. (unless (eq? tag expected)
  14917. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  14918. \end{lstlisting}
  14919. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  14920. \label{fig:interp-Rdyn-aux}
  14921. \end{figure}
  14922. \clearpage
  14923. \section{Representation of Tagged Values}
  14924. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  14925. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  14926. values at the bit level. Because almost every operation in \LangDyn{}
  14927. involves manipulating tagged values, the representation must be
  14928. efficient. Recall that all of our values are 64 bits. We shall steal
  14929. the 3 right-most bits to encode the tag. We use $001$ to identify
  14930. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  14931. and $101$ for the void value. We define the following auxiliary
  14932. function for mapping types to tag codes.
  14933. \begin{align*}
  14934. \itm{tagof}(\key{Integer}) &= 001 \\
  14935. \itm{tagof}(\key{Boolean}) &= 100 \\
  14936. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  14937. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  14938. \itm{tagof}(\key{Void}) &= 101
  14939. \end{align*}
  14940. This stealing of 3 bits comes at some price: our integers are reduced
  14941. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  14942. affect vectors and procedures because those values are addresses, and
  14943. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  14944. they are always $000$. Thus, we do not lose information by overwriting
  14945. the rightmost 3 bits with the tag and we can simply zero-out the tag
  14946. to recover the original address.
  14947. To make tagged values into first-class entities, we can give them a
  14948. type, called \code{Any}, and define operations such as \code{Inject}
  14949. and \code{Project} for creating and using them, yielding the \LangAny{}
  14950. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  14951. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  14952. in greater detail.
  14953. \section{The \LangAny{} Language}
  14954. \label{sec:Rany-lang}
  14955. \newcommand{\LAnyAST}{
  14956. \begin{array}{lcl}
  14957. \Type &::= & \key{Any} \\
  14958. \itm{op} &::= & \code{any-vector-length}
  14959. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  14960. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  14961. \MID \code{procedure?} \MID \code{void?} \\
  14962. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  14963. \end{array}
  14964. }
  14965. \begin{figure}[tp]
  14966. \centering
  14967. \fbox{
  14968. \begin{minipage}{0.96\textwidth}
  14969. \small
  14970. \[
  14971. \begin{array}{l}
  14972. \gray{\LintOpAST} \\ \hline
  14973. \gray{\LvarASTRacket{}} \\ \hline
  14974. \gray{\LifASTRacket{}} \\ \hline
  14975. \gray{\LwhileASTRacket{}} \\ \hline
  14976. \gray{\LtupASTRacket{}} \\ \hline
  14977. \gray{\LfunASTRacket} \\ \hline
  14978. \gray{\LlambdaASTRacket} \\ \hline
  14979. \LAnyAST \\
  14980. \begin{array}{lcl}
  14981. %% \Type &::= & \ldots \MID \key{Any} \\
  14982. %% \itm{op} &::= & \ldots \MID \code{any-vector-length}
  14983. %% \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  14984. %% &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  14985. %% \MID \code{procedure?} \MID \code{void?} \\
  14986. %% \Exp &::=& \ldots
  14987. %% \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  14988. %% &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  14989. %% \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  14990. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  14991. \end{array}
  14992. \end{array}
  14993. \]
  14994. \end{minipage}
  14995. }
  14996. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  14997. \label{fig:Rany-syntax}
  14998. \end{figure}
  14999. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  15000. (The concrete syntax of \LangAny{} is in the Appendix,
  15001. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  15002. converts the value produced by expression $e$ of type $T$ into a
  15003. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  15004. produced by expression $e$ into a value of type $T$ or else halts the
  15005. program if the type tag is not equivalent to $T$.
  15006. %
  15007. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  15008. restricted to a flat type $\FType$, which simplifies the
  15009. implementation and corresponds with what is needed for compiling \LangDyn{}.
  15010. The \code{any-vector} operators adapt the vector operations so that
  15011. they can be applied to a value of type \code{Any}. They also
  15012. generalize the vector operations in that the index is not restricted
  15013. to be a literal integer in the grammar but is allowed to be any
  15014. expression.
  15015. The type predicates such as \key{boolean?} expect their argument to
  15016. produce a tagged value; they return \key{\#t} if the tag corresponds
  15017. to the predicate and they return \key{\#f} otherwise.
  15018. The type checker for \LangAny{} is shown in
  15019. Figures~\ref{fig:type-check-Rany-part-1} and
  15020. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  15021. Figure~\ref{fig:type-check-Rany-aux}.
  15022. %
  15023. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  15024. auxiliary functions \code{apply-inject} and \code{apply-project} are
  15025. in Figure~\ref{fig:apply-project}.
  15026. \begin{figure}[btp]
  15027. \begin{lstlisting}[basicstyle=\ttfamily\small]
  15028. (define type-check-Rany_class
  15029. (class type-check-Rlambda_class
  15030. (super-new)
  15031. (inherit check-type-equal?)
  15032. (define/override (type-check-exp env)
  15033. (lambda (e)
  15034. (define recur (type-check-exp env))
  15035. (match e
  15036. [(Inject e1 ty)
  15037. (unless (flat-ty? ty)
  15038. (error 'type-check "may only inject from flat type, not ~a" ty))
  15039. (define-values (new-e1 e-ty) (recur e1))
  15040. (check-type-equal? e-ty ty e)
  15041. (values (Inject new-e1 ty) 'Any)]
  15042. [(Project e1 ty)
  15043. (unless (flat-ty? ty)
  15044. (error 'type-check "may only project to flat type, not ~a" ty))
  15045. (define-values (new-e1 e-ty) (recur e1))
  15046. (check-type-equal? e-ty 'Any e)
  15047. (values (Project new-e1 ty) ty)]
  15048. [(Prim 'any-vector-length (list e1))
  15049. (define-values (e1^ t1) (recur e1))
  15050. (check-type-equal? t1 'Any e)
  15051. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  15052. [(Prim 'any-vector-ref (list e1 e2))
  15053. (define-values (e1^ t1) (recur e1))
  15054. (define-values (e2^ t2) (recur e2))
  15055. (check-type-equal? t1 'Any e)
  15056. (check-type-equal? t2 'Integer e)
  15057. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  15058. [(Prim 'any-vector-set! (list e1 e2 e3))
  15059. (define-values (e1^ t1) (recur e1))
  15060. (define-values (e2^ t2) (recur e2))
  15061. (define-values (e3^ t3) (recur e3))
  15062. (check-type-equal? t1 'Any e)
  15063. (check-type-equal? t2 'Integer e)
  15064. (check-type-equal? t3 'Any e)
  15065. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  15066. \end{lstlisting}
  15067. \caption{Type checker for the \LangAny{} language, part 1.}
  15068. \label{fig:type-check-Rany-part-1}
  15069. \end{figure}
  15070. \begin{figure}[btp]
  15071. \begin{lstlisting}[basicstyle=\ttfamily\small]
  15072. [(ValueOf e ty)
  15073. (define-values (new-e e-ty) (recur e))
  15074. (values (ValueOf new-e ty) ty)]
  15075. [(Prim pred (list e1))
  15076. #:when (set-member? (type-predicates) pred)
  15077. (define-values (new-e1 e-ty) (recur e1))
  15078. (check-type-equal? e-ty 'Any e)
  15079. (values (Prim pred (list new-e1)) 'Boolean)]
  15080. [(If cnd thn els)
  15081. (define-values (cnd^ Tc) (recur cnd))
  15082. (define-values (thn^ Tt) (recur thn))
  15083. (define-values (els^ Te) (recur els))
  15084. (check-type-equal? Tc 'Boolean cnd)
  15085. (check-type-equal? Tt Te e)
  15086. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  15087. [(Exit) (values (Exit) '_)]
  15088. [(Prim 'eq? (list arg1 arg2))
  15089. (define-values (e1 t1) (recur arg1))
  15090. (define-values (e2 t2) (recur arg2))
  15091. (match* (t1 t2)
  15092. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  15093. [(other wise) (check-type-equal? t1 t2 e)])
  15094. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  15095. [else ((super type-check-exp env) e)])))
  15096. ))
  15097. \end{lstlisting}
  15098. \caption{Type checker for the \LangAny{} language, part 2.}
  15099. \label{fig:type-check-Rany-part-2}
  15100. \end{figure}
  15101. \begin{figure}[tbp]
  15102. \begin{lstlisting}
  15103. (define/override (operator-types)
  15104. (append
  15105. '((integer? . ((Any) . Boolean))
  15106. (vector? . ((Any) . Boolean))
  15107. (procedure? . ((Any) . Boolean))
  15108. (void? . ((Any) . Boolean))
  15109. (tag-of-any . ((Any) . Integer))
  15110. (make-any . ((_ Integer) . Any))
  15111. )
  15112. (super operator-types)))
  15113. (define/public (type-predicates)
  15114. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15115. (define/public (combine-types t1 t2)
  15116. (match (list t1 t2)
  15117. [(list '_ t2) t2]
  15118. [(list t1 '_) t1]
  15119. [(list `(Vector ,ts1 ...)
  15120. `(Vector ,ts2 ...))
  15121. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  15122. (combine-types t1 t2)))]
  15123. [(list `(,ts1 ... -> ,rt1)
  15124. `(,ts2 ... -> ,rt2))
  15125. `(,@(for/list ([t1 ts1] [t2 ts2])
  15126. (combine-types t1 t2))
  15127. -> ,(combine-types rt1 rt2))]
  15128. [else t1]))
  15129. (define/public (flat-ty? ty)
  15130. (match ty
  15131. [(or `Integer `Boolean '_ `Void) #t]
  15132. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  15133. [`(,ts ... -> ,rt)
  15134. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  15135. [else #f]))
  15136. \end{lstlisting}
  15137. \caption{Auxiliary methods for type checking \LangAny{}.}
  15138. \label{fig:type-check-Rany-aux}
  15139. \end{figure}
  15140. \begin{figure}[btp]
  15141. \begin{lstlisting}
  15142. (define interp-Rany_class
  15143. (class interp-Rlambda_class
  15144. (super-new)
  15145. (define/override (interp-op op)
  15146. (match op
  15147. ['boolean? (match-lambda
  15148. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  15149. [else #f])]
  15150. ['integer? (match-lambda
  15151. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  15152. [else #f])]
  15153. ['vector? (match-lambda
  15154. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  15155. [else #f])]
  15156. ['procedure? (match-lambda
  15157. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  15158. [else #f])]
  15159. ['eq? (match-lambda*
  15160. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  15161. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  15162. [ls (apply (super interp-op op) ls)])]
  15163. ['any-vector-ref (lambda (v i)
  15164. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  15165. ['any-vector-set! (lambda (v i a)
  15166. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  15167. ['any-vector-length (lambda (v)
  15168. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  15169. [else (super interp-op op)]))
  15170. (define/override ((interp-exp env) e)
  15171. (define recur (interp-exp env))
  15172. (match e
  15173. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  15174. [(Project e ty2) (apply-project (recur e) ty2)]
  15175. [else ((super interp-exp env) e)]))
  15176. ))
  15177. (define (interp-Rany p)
  15178. (send (new interp-Rany_class) interp-program p))
  15179. \end{lstlisting}
  15180. \caption{Interpreter for \LangAny{}.}
  15181. \label{fig:interp-Rany}
  15182. \end{figure}
  15183. \begin{figure}[tbp]
  15184. \begin{lstlisting}
  15185. (define/public (apply-inject v tg) (Tagged v tg))
  15186. (define/public (apply-project v ty2)
  15187. (define tag2 (any-tag ty2))
  15188. (match v
  15189. [(Tagged v1 tag1)
  15190. (cond
  15191. [(eq? tag1 tag2)
  15192. (match ty2
  15193. [`(Vector ,ts ...)
  15194. (define l1 ((interp-op 'vector-length) v1))
  15195. (cond
  15196. [(eq? l1 (length ts)) v1]
  15197. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  15198. l1 (length ts))])]
  15199. [`(,ts ... -> ,rt)
  15200. (match v1
  15201. [`(function ,xs ,body ,env)
  15202. (cond [(eq? (length xs) (length ts)) v1]
  15203. [else
  15204. (error 'apply-project "arity mismatch ~a != ~a"
  15205. (length xs) (length ts))])]
  15206. [else (error 'apply-project "expected function not ~a" v1)])]
  15207. [else v1])]
  15208. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  15209. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  15210. \end{lstlisting}
  15211. \caption{Auxiliary functions for injection and projection.}
  15212. \label{fig:apply-project}
  15213. \end{figure}
  15214. \clearpage
  15215. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  15216. \label{sec:compile-r7}
  15217. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  15218. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  15219. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  15220. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  15221. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  15222. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  15223. the Boolean \code{\#t}, which must be injected to produce an
  15224. expression of type \key{Any}.
  15225. %
  15226. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  15227. addition, is representative of compilation for many primitive
  15228. operations: the arguments have type \key{Any} and must be projected to
  15229. \key{Integer} before the addition can be performed.
  15230. The compilation of \key{lambda} (third row of
  15231. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  15232. produce type annotations: we simply use \key{Any}.
  15233. %
  15234. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  15235. has to account for some differences in behavior between \LangDyn{} and
  15236. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  15237. kind of values can be used in various places. For example, the
  15238. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  15239. the arguments need not be of the same type (in that case the
  15240. result is \code{\#f}).
  15241. \begin{figure}[btp]
  15242. \centering
  15243. \begin{tabular}{|lll|} \hline
  15244. \begin{minipage}{0.27\textwidth}
  15245. \begin{lstlisting}
  15246. #t
  15247. \end{lstlisting}
  15248. \end{minipage}
  15249. &
  15250. $\Rightarrow$
  15251. &
  15252. \begin{minipage}{0.65\textwidth}
  15253. \begin{lstlisting}
  15254. (inject #t Boolean)
  15255. \end{lstlisting}
  15256. \end{minipage}
  15257. \\[2ex]\hline
  15258. \begin{minipage}{0.27\textwidth}
  15259. \begin{lstlisting}
  15260. (+ |$e_1$| |$e_2$|)
  15261. \end{lstlisting}
  15262. \end{minipage}
  15263. &
  15264. $\Rightarrow$
  15265. &
  15266. \begin{minipage}{0.65\textwidth}
  15267. \begin{lstlisting}
  15268. (inject
  15269. (+ (project |$e'_1$| Integer)
  15270. (project |$e'_2$| Integer))
  15271. Integer)
  15272. \end{lstlisting}
  15273. \end{minipage}
  15274. \\[2ex]\hline
  15275. \begin{minipage}{0.27\textwidth}
  15276. \begin{lstlisting}
  15277. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  15278. \end{lstlisting}
  15279. \end{minipage}
  15280. &
  15281. $\Rightarrow$
  15282. &
  15283. \begin{minipage}{0.65\textwidth}
  15284. \begin{lstlisting}
  15285. (inject
  15286. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  15287. (Any|$\ldots$|Any -> Any))
  15288. \end{lstlisting}
  15289. \end{minipage}
  15290. \\[2ex]\hline
  15291. \begin{minipage}{0.27\textwidth}
  15292. \begin{lstlisting}
  15293. (|$e_0$| |$e_1 \ldots e_n$|)
  15294. \end{lstlisting}
  15295. \end{minipage}
  15296. &
  15297. $\Rightarrow$
  15298. &
  15299. \begin{minipage}{0.65\textwidth}
  15300. \begin{lstlisting}
  15301. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  15302. \end{lstlisting}
  15303. \end{minipage}
  15304. \\[2ex]\hline
  15305. \begin{minipage}{0.27\textwidth}
  15306. \begin{lstlisting}
  15307. (vector-ref |$e_1$| |$e_2$|)
  15308. \end{lstlisting}
  15309. \end{minipage}
  15310. &
  15311. $\Rightarrow$
  15312. &
  15313. \begin{minipage}{0.65\textwidth}
  15314. \begin{lstlisting}
  15315. (any-vector-ref |$e_1'$| |$e_2'$|)
  15316. \end{lstlisting}
  15317. \end{minipage}
  15318. \\[2ex]\hline
  15319. \begin{minipage}{0.27\textwidth}
  15320. \begin{lstlisting}
  15321. (if |$e_1$| |$e_2$| |$e_3$|)
  15322. \end{lstlisting}
  15323. \end{minipage}
  15324. &
  15325. $\Rightarrow$
  15326. &
  15327. \begin{minipage}{0.65\textwidth}
  15328. \begin{lstlisting}
  15329. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  15330. \end{lstlisting}
  15331. \end{minipage}
  15332. \\[2ex]\hline
  15333. \begin{minipage}{0.27\textwidth}
  15334. \begin{lstlisting}
  15335. (eq? |$e_1$| |$e_2$|)
  15336. \end{lstlisting}
  15337. \end{minipage}
  15338. &
  15339. $\Rightarrow$
  15340. &
  15341. \begin{minipage}{0.65\textwidth}
  15342. \begin{lstlisting}
  15343. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  15344. \end{lstlisting}
  15345. \end{minipage}
  15346. \\[2ex]\hline
  15347. \begin{minipage}{0.27\textwidth}
  15348. \begin{lstlisting}
  15349. (not |$e_1$|)
  15350. \end{lstlisting}
  15351. \end{minipage}
  15352. &
  15353. $\Rightarrow$
  15354. &
  15355. \begin{minipage}{0.65\textwidth}
  15356. \begin{lstlisting}
  15357. (if (eq? |$e'_1$| (inject #f Boolean))
  15358. (inject #t Boolean) (inject #f Boolean))
  15359. \end{lstlisting}
  15360. \end{minipage}
  15361. \\[2ex]\hline
  15362. \end{tabular}
  15363. \caption{Cast Insertion}
  15364. \label{fig:compile-r7-Rany}
  15365. \end{figure}
  15366. \section{Reveal Casts}
  15367. \label{sec:reveal-casts-Rany}
  15368. % TODO: define R'_6
  15369. In the \code{reveal-casts} pass we recommend compiling \code{project}
  15370. into an \code{if} expression that checks whether the value's tag
  15371. matches the target type; if it does, the value is converted to a value
  15372. of the target type by removing the tag; if it does not, the program
  15373. exits. To perform these actions we need a new primitive operation,
  15374. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  15375. The \code{tag-of-any} operation retrieves the type tag from a tagged
  15376. value of type \code{Any}. The \code{ValueOf} form retrieves the
  15377. underlying value from a tagged value. The \code{ValueOf} form
  15378. includes the type for the underlying value which is used by the type
  15379. checker. Finally, the \code{Exit} form ends the execution of the
  15380. program.
  15381. If the target type of the projection is \code{Boolean} or
  15382. \code{Integer}, then \code{Project} can be translated as follows.
  15383. \begin{center}
  15384. \begin{minipage}{1.0\textwidth}
  15385. \begin{lstlisting}
  15386. (Project |$e$| |$\FType$|)
  15387. |$\Rightarrow$|
  15388. (Let |$\itm{tmp}$| |$e'$|
  15389. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  15390. (Int |$\itm{tagof}(\FType)$|)))
  15391. (ValueOf |$\itm{tmp}$| |$\FType$|)
  15392. (Exit)))
  15393. \end{lstlisting}
  15394. \end{minipage}
  15395. \end{center}
  15396. If the target type of the projection is a vector or function type,
  15397. then there is a bit more work to do. For vectors, check that the
  15398. length of the vector type matches the length of the vector (using the
  15399. \code{vector-length} primitive). For functions, check that the number
  15400. of parameters in the function type matches the function's arity (using
  15401. \code{procedure-arity}).
  15402. Regarding \code{inject}, we recommend compiling it to a slightly
  15403. lower-level primitive operation named \code{make-any}. This operation
  15404. takes a tag instead of a type.
  15405. \begin{center}
  15406. \begin{minipage}{1.0\textwidth}
  15407. \begin{lstlisting}
  15408. (Inject |$e$| |$\FType$|)
  15409. |$\Rightarrow$|
  15410. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  15411. \end{lstlisting}
  15412. \end{minipage}
  15413. \end{center}
  15414. The type predicates (\code{boolean?}, etc.) can be translated into
  15415. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  15416. translation of \code{Project}.
  15417. The \code{any-vector-ref} and \code{any-vector-set!} operations
  15418. combine the projection action with the vector operation. Also, the
  15419. read and write operations allow arbitrary expressions for the index so
  15420. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  15421. cannot guarantee that the index is within bounds. Thus, we insert code
  15422. to perform bounds checking at runtime. The translation for
  15423. \code{any-vector-ref} is as follows and the other two operations are
  15424. translated in a similar way.
  15425. \begin{lstlisting}
  15426. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  15427. |$\Rightarrow$|
  15428. (Let |$v$| |$e'_1$|
  15429. (Let |$i$| |$e'_2$|
  15430. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  15431. (If (Prim '< (list (Var |$i$|)
  15432. (Prim 'any-vector-length (list (Var |$v$|)))))
  15433. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  15434. (Exit))))
  15435. \end{lstlisting}
  15436. \section{Remove Complex Operands}
  15437. \label{sec:rco-Rany}
  15438. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  15439. The subexpression of \code{ValueOf} must be atomic.
  15440. \section{Explicate Control and \LangCAny{}}
  15441. \label{sec:explicate-Rany}
  15442. The output of \code{explicate\_control} is the \LangCAny{} language whose
  15443. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  15444. form that we added to \LangAny{} remains an expression and the \code{Exit}
  15445. expression becomes a $\Tail$. Also, note that the index argument of
  15446. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  15447. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  15448. \begin{figure}[tp]
  15449. \fbox{
  15450. \begin{minipage}{0.96\textwidth}
  15451. \small
  15452. \[
  15453. \begin{array}{lcl}
  15454. \Exp &::= & \ldots
  15455. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  15456. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  15457. &\MID& \VALUEOF{\Exp}{\FType} \\
  15458. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  15459. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  15460. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  15461. \MID \GOTO{\itm{label}} } \\
  15462. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  15463. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  15464. \MID \LP\key{Exit}\RP \\
  15465. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  15466. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  15467. \end{array}
  15468. \]
  15469. \end{minipage}
  15470. }
  15471. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  15472. \label{fig:c5-syntax}
  15473. \end{figure}
  15474. \section{Select Instructions}
  15475. \label{sec:select-Rany}
  15476. In the \code{select\_instructions} pass we translate the primitive
  15477. operations on the \code{Any} type to x86 instructions that involve
  15478. manipulating the 3 tag bits of the tagged value.
  15479. \paragraph{Make-any}
  15480. We recommend compiling the \key{make-any} primitive as follows if the
  15481. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  15482. shifts the destination to the left by the number of bits specified its
  15483. source argument (in this case $3$, the length of the tag) and it
  15484. preserves the sign of the integer. We use the \key{orq} instruction to
  15485. combine the tag and the value to form the tagged value. \\
  15486. \begin{lstlisting}
  15487. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  15488. |$\Rightarrow$|
  15489. movq |$e'$|, |\itm{lhs'}|
  15490. salq $3, |\itm{lhs'}|
  15491. orq $|$\itm{tag}$|, |\itm{lhs'}|
  15492. \end{lstlisting}
  15493. The instruction selection for vectors and procedures is different
  15494. because their is no need to shift them to the left. The rightmost 3
  15495. bits are already zeros as described at the beginning of this
  15496. chapter. So we just combine the value and the tag using \key{orq}. \\
  15497. \begin{lstlisting}
  15498. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  15499. |$\Rightarrow$|
  15500. movq |$e'$|, |\itm{lhs'}|
  15501. orq $|$\itm{tag}$|, |\itm{lhs'}|
  15502. \end{lstlisting}
  15503. \paragraph{Tag-of-any}
  15504. Recall that the \code{tag-of-any} operation extracts the type tag from
  15505. a value of type \code{Any}. The type tag is the bottom three bits, so
  15506. we obtain the tag by taking the bitwise-and of the value with $111$
  15507. ($7$ in decimal).
  15508. \begin{lstlisting}
  15509. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  15510. |$\Rightarrow$|
  15511. movq |$e'$|, |\itm{lhs'}|
  15512. andq $7, |\itm{lhs'}|
  15513. \end{lstlisting}
  15514. \paragraph{ValueOf}
  15515. Like \key{make-any}, the instructions for \key{ValueOf} are different
  15516. depending on whether the type $T$ is a pointer (vector or procedure)
  15517. or not (Integer or Boolean). The following shows the instruction
  15518. selection for Integer and Boolean. We produce an untagged value by
  15519. shifting it to the right by 3 bits.
  15520. \begin{lstlisting}
  15521. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  15522. |$\Rightarrow$|
  15523. movq |$e'$|, |\itm{lhs'}|
  15524. sarq $3, |\itm{lhs'}|
  15525. \end{lstlisting}
  15526. %
  15527. In the case for vectors and procedures, there is no need to
  15528. shift. Instead we just need to zero-out the rightmost 3 bits. We
  15529. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  15530. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  15531. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  15532. then apply \code{andq} with the tagged value to get the desired
  15533. result. \\
  15534. \begin{lstlisting}
  15535. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  15536. |$\Rightarrow$|
  15537. movq $|$-8$|, |\itm{lhs'}|
  15538. andq |$e'$|, |\itm{lhs'}|
  15539. \end{lstlisting}
  15540. %% \paragraph{Type Predicates} We leave it to the reader to
  15541. %% devise a sequence of instructions to implement the type predicates
  15542. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  15543. \paragraph{Any-vector-length}
  15544. \begin{lstlisting}
  15545. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  15546. |$\Longrightarrow$|
  15547. movq |$\neg 111$|, %r11
  15548. andq |$a_1'$|, %r11
  15549. movq 0(%r11), %r11
  15550. andq $126, %r11
  15551. sarq $1, %r11
  15552. movq %r11, |$\itm{lhs'}$|
  15553. \end{lstlisting}
  15554. \paragraph{Any-vector-ref}
  15555. The index may be an arbitrary atom so instead of computing the offset
  15556. at compile time, instructions need to be generated to compute the
  15557. offset at runtime as follows. Note the use of the new instruction
  15558. \code{imulq}.
  15559. \begin{center}
  15560. \begin{minipage}{0.96\textwidth}
  15561. \begin{lstlisting}
  15562. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  15563. |$\Longrightarrow$|
  15564. movq |$\neg 111$|, %r11
  15565. andq |$a_1'$|, %r11
  15566. movq |$a_2'$|, %rax
  15567. addq $1, %rax
  15568. imulq $8, %rax
  15569. addq %rax, %r11
  15570. movq 0(%r11) |$\itm{lhs'}$|
  15571. \end{lstlisting}
  15572. \end{minipage}
  15573. \end{center}
  15574. \paragraph{Any-vector-set!}
  15575. The code generation for \code{any-vector-set!} is similar to the other
  15576. \code{any-vector} operations.
  15577. \section{Register Allocation for \LangAny{}}
  15578. \label{sec:register-allocation-Rany}
  15579. \index{subject}{register allocation}
  15580. There is an interesting interaction between tagged values and garbage
  15581. collection that has an impact on register allocation. A variable of
  15582. type \code{Any} might refer to a vector and therefore it might be a
  15583. root that needs to be inspected and copied during garbage
  15584. collection. Thus, we need to treat variables of type \code{Any} in a
  15585. similar way to variables of type \code{Vector} for purposes of
  15586. register allocation. In particular,
  15587. \begin{itemize}
  15588. \item If a variable of type \code{Any} is live during a function call,
  15589. then it must be spilled. This can be accomplished by changing
  15590. \code{build\_interference} to mark all variables of type \code{Any}
  15591. that are live after a \code{callq} as interfering with all the
  15592. registers.
  15593. \item If a variable of type \code{Any} is spilled, it must be spilled
  15594. to the root stack instead of the normal procedure call stack.
  15595. \end{itemize}
  15596. Another concern regarding the root stack is that the garbage collector
  15597. needs to differentiate between (1) plain old pointers to tuples, (2) a
  15598. tagged value that points to a tuple, and (3) a tagged value that is
  15599. not a tuple. We enable this differentiation by choosing not to use the
  15600. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  15601. reserved for identifying plain old pointers to tuples. That way, if
  15602. one of the first three bits is set, then we have a tagged value and
  15603. inspecting the tag can differentiation between vectors ($010$) and the
  15604. other kinds of values.
  15605. \begin{exercise}\normalfont
  15606. Expand your compiler to handle \LangAny{} as discussed in the last few
  15607. sections. Create 5 new programs that use the \code{Any} type and the
  15608. new operations (\code{inject}, \code{project}, \code{boolean?},
  15609. etc.). Test your compiler on these new programs and all of your
  15610. previously created test programs.
  15611. \end{exercise}
  15612. \begin{exercise}\normalfont
  15613. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  15614. Create tests for \LangDyn{} by adapting ten of your previous test programs
  15615. by removing type annotations. Add 5 more tests programs that
  15616. specifically rely on the language being dynamically typed. That is,
  15617. they should not be legal programs in a statically typed language, but
  15618. nevertheless, they should be valid \LangDyn{} programs that run to
  15619. completion without error.
  15620. \end{exercise}
  15621. \begin{figure}[p]
  15622. \begin{tikzpicture}[baseline=(current bounding box.center)]
  15623. \node (Rfun) at (0,4) {\large \LangDyn{}};
  15624. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  15625. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  15626. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  15627. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  15628. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  15629. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  15630. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  15631. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  15632. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  15633. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  15634. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  15635. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  15636. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  15637. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  15638. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  15639. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  15640. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  15641. \path[->,bend left=15] (Rfun) edge [above] node
  15642. {\ttfamily\footnotesize shrink} (Rfun-2);
  15643. \path[->,bend left=15] (Rfun-2) edge [above] node
  15644. {\ttfamily\footnotesize uniquify} (Rfun-3);
  15645. \path[->,bend left=15] (Rfun-3) edge [above] node
  15646. {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  15647. \path[->,bend right=15] (Rfun-4) edge [left] node
  15648. {\ttfamily\footnotesize cast\_insert} (Rfun-5);
  15649. \path[->,bend left=15] (Rfun-5) edge [above] node
  15650. {\ttfamily\footnotesize check\_bounds} (Rfun-6);
  15651. \path[->,bend left=15] (Rfun-6) edge [left] node
  15652. {\ttfamily\footnotesize reveal\_casts} (Rfun-7);
  15653. \path[->,bend left=15] (Rfun-7) edge [below] node
  15654. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15655. \path[->,bend right=15] (F1-2) edge [above] node
  15656. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15657. \path[->,bend right=15] (F1-3) edge [above] node
  15658. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  15659. \path[->,bend right=15] (F1-4) edge [above] node
  15660. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  15661. \path[->,bend right=15] (F1-5) edge [right] node
  15662. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15663. \path[->,bend left=15] (C3-2) edge [left] node
  15664. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15665. \path[->,bend right=15] (x86-2) edge [left] node
  15666. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15667. \path[->,bend right=15] (x86-2-1) edge [below] node
  15668. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15669. \path[->,bend right=15] (x86-2-2) edge [left] node
  15670. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15671. \path[->,bend left=15] (x86-3) edge [above] node
  15672. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15673. \path[->,bend left=15] (x86-4) edge [right] node
  15674. {\ttfamily\footnotesize print\_x86} (x86-5);
  15675. \end{tikzpicture}
  15676. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  15677. \label{fig:Rdyn-passes}
  15678. \end{figure}
  15679. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  15680. for the compilation of \LangDyn{}.
  15681. % Further Reading
  15682. \fi % racketEd
  15683. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15684. {\if\edition\pythonEd
  15685. \chapter{Objects}
  15686. \label{ch:Robject}
  15687. \index{subject}{objects}
  15688. \index{subject}{classes}
  15689. \fi}
  15690. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15691. \chapter{Gradual Typing}
  15692. \label{ch:Rgrad}
  15693. \index{subject}{gradual typing}
  15694. \if\edition\racketEd
  15695. This chapter studies a language, \LangGrad{}, in which the programmer
  15696. can choose between static and dynamic type checking in different parts
  15697. of a program, thereby mixing the statically typed \LangLoop{} language
  15698. with the dynamically typed \LangDyn{}. There are several approaches to
  15699. mixing static and dynamic typing, including multi-language
  15700. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  15701. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  15702. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  15703. programmer controls the amount of static versus dynamic checking by
  15704. adding or removing type annotations on parameters and
  15705. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  15706. %
  15707. The concrete syntax of \LangGrad{} is defined in
  15708. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  15709. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  15710. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  15711. non-terminals that make type annotations optional. The return types
  15712. are not optional in the abstract syntax; the parser fills in
  15713. \code{Any} when the return type is not specified in the concrete
  15714. syntax.
  15715. \begin{figure}[tp]
  15716. \centering
  15717. \fbox{
  15718. \begin{minipage}{0.96\textwidth}
  15719. \small
  15720. \[
  15721. \begin{array}{lcl}
  15722. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  15723. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  15724. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  15725. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  15726. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  15727. &\MID& \gray{\key{\#t} \MID \key{\#f}
  15728. \MID (\key{and}\;\Exp\;\Exp)
  15729. \MID (\key{or}\;\Exp\;\Exp)
  15730. \MID (\key{not}\;\Exp) } \\
  15731. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  15732. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  15733. (\key{vector-ref}\;\Exp\;\Int)} \\
  15734. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  15735. \MID (\Exp \; \Exp\ldots) } \\
  15736. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  15737. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  15738. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  15739. \MID \CBEGIN{\Exp\ldots}{\Exp}
  15740. \MID \CWHILE{\Exp}{\Exp} } \\
  15741. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  15742. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  15743. \end{array}
  15744. \]
  15745. \end{minipage}
  15746. }
  15747. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  15748. \label{fig:Rgrad-concrete-syntax}
  15749. \end{figure}
  15750. \begin{figure}[tp]
  15751. \centering
  15752. \fbox{
  15753. \begin{minipage}{0.96\textwidth}
  15754. \small
  15755. \[
  15756. \begin{array}{lcl}
  15757. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  15758. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  15759. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  15760. &\MID& \gray{ \BOOL{\itm{bool}}
  15761. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  15762. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  15763. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  15764. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  15765. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  15766. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  15767. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  15768. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  15769. \end{array}
  15770. \]
  15771. \end{minipage}
  15772. }
  15773. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  15774. \label{fig:Rgrad-syntax}
  15775. \end{figure}
  15776. Both the type checker and the interpreter for \LangGrad{} require some
  15777. interesting changes to enable gradual typing, which we discuss in the
  15778. next two sections in the context of the \code{map} example from
  15779. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map} we
  15780. revised the \code{map} example, omitting the type annotations from
  15781. the \code{inc} function.
  15782. \begin{figure}[btp]
  15783. % gradual_test_9.rkt
  15784. \begin{lstlisting}
  15785. (define (map [f : (Integer -> Integer)]
  15786. [v : (Vector Integer Integer)])
  15787. : (Vector Integer Integer)
  15788. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  15789. (define (inc x) (+ x 1))
  15790. (vector-ref (map inc (vector 0 41)) 1)
  15791. \end{lstlisting}
  15792. \caption{A partially-typed version of the \code{map} example.}
  15793. \label{fig:gradual-map}
  15794. \end{figure}
  15795. \section{Type Checking \LangGrad{} and \LangCast{}}
  15796. \label{sec:gradual-type-check}
  15797. The type checker for \LangGrad{} uses the \code{Any} type for missing
  15798. parameter and return types. For example, the \code{x} parameter of
  15799. \code{inc} in Figure~\ref{fig:gradual-map} is given the type
  15800. \code{Any} and the return type of \code{inc} is \code{Any}. Next
  15801. consider the \code{+} operator inside \code{inc}. It expects both
  15802. arguments to have type \code{Integer}, but its first argument \code{x}
  15803. has type \code{Any}. In a gradually typed language, such differences
  15804. are allowed so long as the types are \emph{consistent}, that is, they
  15805. are equal except in places where there is an \code{Any} type. The type
  15806. \code{Any} is consistent with every other type.
  15807. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  15808. \begin{figure}[tbp]
  15809. \begin{lstlisting}
  15810. (define/public (consistent? t1 t2)
  15811. (match* (t1 t2)
  15812. [('Integer 'Integer) #t]
  15813. [('Boolean 'Boolean) #t]
  15814. [('Void 'Void) #t]
  15815. [('Any t2) #t]
  15816. [(t1 'Any) #t]
  15817. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  15818. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  15819. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  15820. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  15821. (consistent? rt1 rt2))]
  15822. [(other wise) #f]))
  15823. \end{lstlisting}
  15824. \caption{The consistency predicate on types.}
  15825. \label{fig:consistent}
  15826. \end{figure}
  15827. Returning to the \code{map} example of
  15828. Figure~\ref{fig:gradual-map}, the \code{inc} function has type
  15829. \code{(Any -> Any)} but parameter \code{f} of \code{map} has type
  15830. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  15831. because the two types are consistent. In particular, \code{->} is
  15832. equal to \code{->} and because \code{Any} is consistent with
  15833. \code{Integer}.
  15834. Next consider a program with an error, such as applying the
  15835. \code{map} to a function that sometimes returns a Boolean, as
  15836. shown in Figure~\ref{fig:map-maybe-inc}. The type checker for
  15837. \LangGrad{} accepts this program because the type of \code{maybe-inc} is
  15838. consistent with the type of parameter \code{f} of \code{map}, that
  15839. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  15840. Integer)}. One might say that a gradual type checker is optimistic
  15841. in that it accepts programs that might execute without a runtime type
  15842. error.
  15843. %
  15844. Unfortunately, running this program with input \code{1} triggers an
  15845. error when the \code{maybe-inc} function returns \code{\#t}. \LangGrad{}
  15846. performs checking at runtime to ensure the integrity of the static
  15847. types, such as the \code{(Integer -> Integer)} annotation on parameter
  15848. \code{f} of \code{map}. This runtime checking is carried out by a
  15849. new \code{Cast} form that is inserted by the type checker. Thus, the
  15850. output of the type checker is a program in the \LangCast{} language, which
  15851. adds \code{Cast} to \LangLoop{}, as shown in
  15852. Figure~\ref{fig:Rgrad-prime-syntax}.
  15853. \begin{figure}[tp]
  15854. \centering
  15855. \fbox{
  15856. \begin{minipage}{0.96\textwidth}
  15857. \small
  15858. \[
  15859. \begin{array}{lcl}
  15860. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  15861. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  15862. \end{array}
  15863. \]
  15864. \end{minipage}
  15865. }
  15866. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  15867. \label{fig:Rgrad-prime-syntax}
  15868. \end{figure}
  15869. \begin{figure}[tbp]
  15870. \begin{lstlisting}
  15871. (define (map [f : (Integer -> Integer)]
  15872. [v : (Vector Integer Integer)])
  15873. : (Vector Integer Integer)
  15874. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  15875. (define (inc x) (+ x 1))
  15876. (define (true) #t)
  15877. (define (maybe-inc x) (if (eq? 0 (read)) (inc x) (true)))
  15878. (vector-ref (map maybe-inc (vector 0 41)) 0)
  15879. \end{lstlisting}
  15880. \caption{A variant of the \code{map} example with an error.}
  15881. \label{fig:map-maybe-inc}
  15882. \end{figure}
  15883. Figure~\ref{fig:map-cast} shows the output of the type checker for
  15884. \code{map} and \code{maybe-inc}. The idea is that \code{Cast} is
  15885. inserted every time the type checker sees two types that are
  15886. consistent but not equal. In the \code{inc} function, \code{x} is
  15887. cast to \code{Integer} and the result of the \code{+} is cast to
  15888. \code{Any}. In the call to \code{map}, the \code{inc} argument
  15889. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  15890. \begin{figure}[btp]
  15891. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15892. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  15893. : (Vector Integer Integer)
  15894. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  15895. (define (inc [x : Any]) : Any
  15896. (cast (+ (cast x Any Integer) 1) Integer Any))
  15897. (define (true) : Any (cast #t Boolean Any))
  15898. (define (maybe-inc [x : Any]) : Any
  15899. (if (eq? 0 (read)) (inc x) (true)))
  15900. (vector-ref (map (cast maybe-inc (Any -> Any) (Integer -> Integer))
  15901. (vector 0 41)) 0)
  15902. \end{lstlisting}
  15903. \caption{Output of type checking \code{map}
  15904. and \code{maybe-inc}.}
  15905. \label{fig:map-cast}
  15906. \end{figure}
  15907. The type checker for \LangGrad{} is defined in
  15908. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  15909. and \ref{fig:type-check-Rgradual-3}.
  15910. \begin{figure}[tbp]
  15911. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15912. (define type-check-gradual_class
  15913. (class type-check-Rwhile_class
  15914. (super-new)
  15915. (inherit operator-types type-predicates)
  15916. (define/override (type-check-exp env)
  15917. (lambda (e)
  15918. (define recur (type-check-exp env))
  15919. (match e
  15920. [(Prim 'vector-length (list e1))
  15921. (define-values (e1^ t) (recur e1))
  15922. (match t
  15923. [`(Vector ,ts ...)
  15924. (values (Prim 'vector-length (list e1^)) 'Integer)]
  15925. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  15926. [(Prim 'vector-ref (list e1 e2))
  15927. (define-values (e1^ t1) (recur e1))
  15928. (define-values (e2^ t2) (recur e2))
  15929. (check-consistent? t2 'Integer e)
  15930. (match t1
  15931. [`(Vector ,ts ...)
  15932. (match e2^
  15933. [(Int i)
  15934. (unless (and (0 . <= . i) (i . < . (length ts)))
  15935. (error 'type-check "invalid index ~a in ~a" i e))
  15936. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  15937. [else (define e1^^ (make-cast e1^ t1 'Any))
  15938. (define e2^^ (make-cast e2^ t2 'Integer))
  15939. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  15940. ['Any
  15941. (define e2^^ (make-cast e2^ t2 'Integer))
  15942. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  15943. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  15944. [(Prim 'vector-set! (list e1 e2 e3) )
  15945. (define-values (e1^ t1) (recur e1))
  15946. (define-values (e2^ t2) (recur e2))
  15947. (define-values (e3^ t3) (recur e3))
  15948. (check-consistent? t2 'Integer e)
  15949. (match t1
  15950. [`(Vector ,ts ...)
  15951. (match e2^
  15952. [(Int i)
  15953. (unless (and (0 . <= . i) (i . < . (length ts)))
  15954. (error 'type-check "invalid index ~a in ~a" i e))
  15955. (check-consistent? (list-ref ts i) t3 e)
  15956. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  15957. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  15958. [else
  15959. (define e1^^ (make-cast e1^ t1 'Any))
  15960. (define e2^^ (make-cast e2^ t2 'Integer))
  15961. (define e3^^ (make-cast e3^ t3 'Any))
  15962. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  15963. ['Any
  15964. (define e2^^ (make-cast e2^ t2 'Integer))
  15965. (define e3^^ (make-cast e3^ t3 'Any))
  15966. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  15967. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  15968. \end{lstlisting}
  15969. \caption{Type checker for the \LangGrad{} language, part 1.}
  15970. \label{fig:type-check-Rgradual-1}
  15971. \end{figure}
  15972. \begin{figure}[tbp]
  15973. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15974. [(Prim 'eq? (list e1 e2))
  15975. (define-values (e1^ t1) (recur e1))
  15976. (define-values (e2^ t2) (recur e2))
  15977. (check-consistent? t1 t2 e)
  15978. (define T (meet t1 t2))
  15979. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  15980. 'Boolean)]
  15981. [(Prim 'not (list e1))
  15982. (define-values (e1^ t1) (recur e1))
  15983. (match t1
  15984. ['Any
  15985. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  15986. (Bool #t) (Bool #f)))]
  15987. [else
  15988. (define-values (t-ret new-es^)
  15989. (type-check-op 'not (list t1) (list e1^) e))
  15990. (values (Prim 'not new-es^) t-ret)])]
  15991. [(Prim 'and (list e1 e2))
  15992. (recur (If e1 e2 (Bool #f)))]
  15993. [(Prim 'or (list e1 e2))
  15994. (define tmp (gensym 'tmp))
  15995. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  15996. [(Prim op es)
  15997. #:when (not (set-member? explicit-prim-ops op))
  15998. (define-values (new-es ts)
  15999. (for/lists (exprs types) ([e es])
  16000. (recur e)))
  16001. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  16002. (values (Prim op new-es^) t-ret)]
  16003. [(If e1 e2 e3)
  16004. (define-values (e1^ T1) (recur e1))
  16005. (define-values (e2^ T2) (recur e2))
  16006. (define-values (e3^ T3) (recur e3))
  16007. (check-consistent? T2 T3 e)
  16008. (match T1
  16009. ['Boolean
  16010. (define Tif (join T2 T3))
  16011. (values (If e1^ (make-cast e2^ T2 Tif)
  16012. (make-cast e3^ T3 Tif)) Tif)]
  16013. ['Any
  16014. (define Tif (meet T2 T3))
  16015. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  16016. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  16017. Tif)]
  16018. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  16019. [(HasType e1 T)
  16020. (define-values (e1^ T1) (recur e1))
  16021. (check-consistent? T1 T)
  16022. (values (make-cast e1^ T1 T) T)]
  16023. [(SetBang x e1)
  16024. (define-values (e1^ T1) (recur e1))
  16025. (define varT (dict-ref env x))
  16026. (check-consistent? T1 varT e)
  16027. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  16028. [(WhileLoop e1 e2)
  16029. (define-values (e1^ T1) (recur e1))
  16030. (check-consistent? T1 'Boolean e)
  16031. (define-values (e2^ T2) ((type-check-exp env) e2))
  16032. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  16033. \end{lstlisting}
  16034. \caption{Type checker for the \LangGrad{} language, part 2.}
  16035. \label{fig:type-check-Rgradual-2}
  16036. \end{figure}
  16037. \begin{figure}[tbp]
  16038. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  16039. [(Apply e1 e2s)
  16040. (define-values (e1^ T1) (recur e1))
  16041. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  16042. (match T1
  16043. [`(,T1ps ... -> ,T1rt)
  16044. (for ([T2 T2s] [Tp T1ps])
  16045. (check-consistent? T2 Tp e))
  16046. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  16047. (make-cast e2 src tgt)))
  16048. (values (Apply e1^ e2s^^) T1rt)]
  16049. [`Any
  16050. (define e1^^ (make-cast e1^ 'Any
  16051. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  16052. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  16053. (make-cast e2 src 'Any)))
  16054. (values (Apply e1^^ e2s^^) 'Any)]
  16055. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  16056. [(Lambda params Tr e1)
  16057. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  16058. (match p
  16059. [`[,x : ,T] (values x T)]
  16060. [(? symbol? x) (values x 'Any)])))
  16061. (define-values (e1^ T1)
  16062. ((type-check-exp (append (map cons xs Ts) env)) e1))
  16063. (check-consistent? Tr T1 e)
  16064. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  16065. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  16066. [else ((super type-check-exp env) e)]
  16067. )))
  16068. \end{lstlisting}
  16069. \caption{Type checker for the \LangGrad{} language, part 3.}
  16070. \label{fig:type-check-Rgradual-3}
  16071. \end{figure}
  16072. \begin{figure}[tbp]
  16073. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  16074. (define/public (join t1 t2)
  16075. (match* (t1 t2)
  16076. [('Integer 'Integer) 'Integer]
  16077. [('Boolean 'Boolean) 'Boolean]
  16078. [('Void 'Void) 'Void]
  16079. [('Any t2) t2]
  16080. [(t1 'Any) t1]
  16081. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  16082. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  16083. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  16084. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  16085. -> ,(join rt1 rt2))]))
  16086. (define/public (meet t1 t2)
  16087. (match* (t1 t2)
  16088. [('Integer 'Integer) 'Integer]
  16089. [('Boolean 'Boolean) 'Boolean]
  16090. [('Void 'Void) 'Void]
  16091. [('Any t2) 'Any]
  16092. [(t1 'Any) 'Any]
  16093. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  16094. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  16095. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  16096. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  16097. -> ,(meet rt1 rt2))]))
  16098. (define/public (make-cast e src tgt)
  16099. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  16100. (define/public (check-consistent? t1 t2 e)
  16101. (unless (consistent? t1 t2)
  16102. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  16103. (define/override (type-check-op op arg-types args e)
  16104. (match (dict-ref (operator-types) op)
  16105. [`(,param-types . ,return-type)
  16106. (for ([at arg-types] [pt param-types])
  16107. (check-consistent? at pt e))
  16108. (values return-type
  16109. (for/list ([e args] [s arg-types] [t param-types])
  16110. (make-cast e s t)))]
  16111. [else (error 'type-check-op "unrecognized ~a" op)]))
  16112. (define explicit-prim-ops
  16113. (set-union
  16114. (type-predicates)
  16115. (set 'procedure-arity 'eq?
  16116. 'vector 'vector-length 'vector-ref 'vector-set!
  16117. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  16118. (define/override (fun-def-type d)
  16119. (match d
  16120. [(Def f params rt info body)
  16121. (define ps
  16122. (for/list ([p params])
  16123. (match p
  16124. [`[,x : ,T] T]
  16125. [(? symbol?) 'Any]
  16126. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  16127. `(,@ps -> ,rt)]
  16128. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  16129. \end{lstlisting}
  16130. \caption{Auxiliary functions for type checking \LangGrad{}.}
  16131. \label{fig:type-check-Rgradual-aux}
  16132. \end{figure}
  16133. \clearpage
  16134. \section{Interpreting \LangCast{}}
  16135. \label{sec:interp-casts}
  16136. The runtime behavior of first-order casts is straightforward, that is,
  16137. casts involving simple types such as \code{Integer} and
  16138. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  16139. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  16140. puts the integer into a tagged value
  16141. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  16142. \code{Integer} is accomplished with the \code{Project} operator, that
  16143. is, by checking the value's tag and either retrieving the underlying
  16144. integer or signaling an error if it the tag is not the one for
  16145. integers (Figure~\ref{fig:apply-project}).
  16146. %
  16147. Things get more interesting for higher-order casts, that is, casts
  16148. involving function or vector types.
  16149. Consider the cast of the function \code{maybe-inc} from \code{(Any ->
  16150. Any)} to \code{(Integer -> Integer)}. When a function flows through
  16151. this cast at runtime, we can't know in general whether the function
  16152. will always return an integer.\footnote{Predicting the return value of
  16153. a function is equivalent to the halting problem, which is
  16154. undecidable.} The \LangCast{} interpreter therefore delays the checking
  16155. of the cast until the function is applied. This is accomplished by
  16156. wrapping \code{maybe-inc} in a new function that casts its parameter
  16157. from \code{Integer} to \code{Any}, applies \code{maybe-inc}, and then
  16158. casts the return value from \code{Any} to \code{Integer}.
  16159. Turning our attention to casts involving vector types, we consider the
  16160. example in Figure~\ref{fig:map-bang} that defines a
  16161. partially-typed version of \code{map} whose parameter \code{v} has
  16162. type \code{(Vector Any Any)} and that updates \code{v} in place
  16163. instead of returning a new vector. So we name this function
  16164. \code{map!}. We apply \code{map!} to a vector of integers, so
  16165. the type checker inserts a cast from \code{(Vector Integer Integer)}
  16166. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  16167. cast between vector types would be a build a new vector whose elements
  16168. are the result of casting each of the original elements to the
  16169. appropriate target type. However, this approach is only valid for
  16170. immutable vectors; and our vectors are mutable. In the example of
  16171. Figure~\ref{fig:map-bang}, if the cast created a new vector, then
  16172. the updates inside of \code{map!} would happen to the new vector
  16173. and not the original one.
  16174. \begin{figure}[tbp]
  16175. % gradual_test_11.rkt
  16176. \begin{lstlisting}
  16177. (define (map! [f : (Any -> Any)]
  16178. [v : (Vector Any Any)]) : Void
  16179. (begin
  16180. (vector-set! v 0 (f (vector-ref v 0)))
  16181. (vector-set! v 1 (f (vector-ref v 1)))))
  16182. (define (inc x) (+ x 1))
  16183. (let ([v (vector 0 41)])
  16184. (begin (map! inc v) (vector-ref v 1)))
  16185. \end{lstlisting}
  16186. \caption{An example involving casts on vectors.}
  16187. \label{fig:map-bang}
  16188. \end{figure}
  16189. Instead the interpreter needs to create a new kind of value, a
  16190. \emph{vector proxy}, that intercepts every vector operation. On a
  16191. read, the proxy reads from the underlying vector and then applies a
  16192. cast to the resulting value. On a write, the proxy casts the argument
  16193. value and then performs the write to the underlying vector. For the
  16194. first \code{(vector-ref v 0)} in \code{map!}, the proxy casts
  16195. \code{0} from \code{Integer} to \code{Any}. For the first
  16196. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  16197. to \code{Integer}.
  16198. The final category of cast that we need to consider are casts between
  16199. the \code{Any} type and either a function or a vector
  16200. type. Figure~\ref{fig:map-any} shows a variant of \code{map!}
  16201. in which parameter \code{v} does not have a type annotation, so it is
  16202. given type \code{Any}. In the call to \code{map!}, the vector has
  16203. type \code{(Vector Integer Integer)} so the type checker inserts a
  16204. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  16205. thought is to use \code{Inject}, but that doesn't work because
  16206. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  16207. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  16208. to \code{Any}.
  16209. \begin{figure}[tbp]
  16210. \begin{lstlisting}
  16211. (define (map! [f : (Any -> Any)] v) : Void
  16212. (begin
  16213. (vector-set! v 0 (f (vector-ref v 0)))
  16214. (vector-set! v 1 (f (vector-ref v 1)))))
  16215. (define (inc x) (+ x 1))
  16216. (let ([v (vector 0 41)])
  16217. (begin (map! inc v) (vector-ref v 1)))
  16218. \end{lstlisting}
  16219. \caption{Casting a vector to \code{Any}.}
  16220. \label{fig:map-any}
  16221. \end{figure}
  16222. The \LangCast{} interpreter uses an auxiliary function named
  16223. \code{apply-cast} to cast a value from a source type to a target type,
  16224. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  16225. of the kinds of casts that we've discussed in this section.
  16226. \begin{figure}[tbp]
  16227. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16228. (define/public (apply-cast v s t)
  16229. (match* (s t)
  16230. [(t1 t2) #:when (equal? t1 t2) v]
  16231. [('Any t2)
  16232. (match t2
  16233. [`(,ts ... -> ,rt)
  16234. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  16235. (define v^ (apply-project v any->any))
  16236. (apply-cast v^ any->any `(,@ts -> ,rt))]
  16237. [`(Vector ,ts ...)
  16238. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  16239. (define v^ (apply-project v vec-any))
  16240. (apply-cast v^ vec-any `(Vector ,@ts))]
  16241. [else (apply-project v t2)])]
  16242. [(t1 'Any)
  16243. (match t1
  16244. [`(,ts ... -> ,rt)
  16245. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  16246. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  16247. (apply-inject v^ (any-tag any->any))]
  16248. [`(Vector ,ts ...)
  16249. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  16250. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  16251. (apply-inject v^ (any-tag vec-any))]
  16252. [else (apply-inject v (any-tag t1))])]
  16253. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  16254. (define x (gensym 'x))
  16255. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  16256. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  16257. (define cast-writes
  16258. (for/list ([t1 ts1] [t2 ts2])
  16259. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  16260. `(vector-proxy ,(vector v (apply vector cast-reads)
  16261. (apply vector cast-writes)))]
  16262. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  16263. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  16264. `(function ,xs ,(Cast
  16265. (Apply (Value v)
  16266. (for/list ([x xs][t1 ts1][t2 ts2])
  16267. (Cast (Var x) t2 t1)))
  16268. rt1 rt2) ())]
  16269. ))
  16270. \end{lstlisting}
  16271. \caption{The \code{apply-cast} auxiliary method.}
  16272. \label{fig:apply-cast}
  16273. \end{figure}
  16274. The interpreter for \LangCast{} is defined in
  16275. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  16276. dispatching to \code{apply-cast}. To handle the addition of vector
  16277. proxies, we update the vector primitives in \code{interp-op} using the
  16278. functions in Figure~\ref{fig:guarded-vector}.
  16279. \begin{figure}[tbp]
  16280. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16281. (define interp-Rcast_class
  16282. (class interp-Rwhile_class
  16283. (super-new)
  16284. (inherit apply-fun apply-inject apply-project)
  16285. (define/override (interp-op op)
  16286. (match op
  16287. ['vector-length guarded-vector-length]
  16288. ['vector-ref guarded-vector-ref]
  16289. ['vector-set! guarded-vector-set!]
  16290. ['any-vector-ref (lambda (v i)
  16291. (match v [`(tagged ,v^ ,tg)
  16292. (guarded-vector-ref v^ i)]))]
  16293. ['any-vector-set! (lambda (v i a)
  16294. (match v [`(tagged ,v^ ,tg)
  16295. (guarded-vector-set! v^ i a)]))]
  16296. ['any-vector-length (lambda (v)
  16297. (match v [`(tagged ,v^ ,tg)
  16298. (guarded-vector-length v^)]))]
  16299. [else (super interp-op op)]
  16300. ))
  16301. (define/override ((interp-exp env) e)
  16302. (define (recur e) ((interp-exp env) e))
  16303. (match e
  16304. [(Value v) v]
  16305. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  16306. [else ((super interp-exp env) e)]))
  16307. ))
  16308. (define (interp-Rcast p)
  16309. (send (new interp-Rcast_class) interp-program p))
  16310. \end{lstlisting}
  16311. \caption{The interpreter for \LangCast{}.}
  16312. \label{fig:interp-Rcast}
  16313. \end{figure}
  16314. \begin{figure}[tbp]
  16315. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16316. (define (guarded-vector-ref vec i)
  16317. (match vec
  16318. [`(vector-proxy ,proxy)
  16319. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  16320. (define rd (vector-ref (vector-ref proxy 1) i))
  16321. (apply-fun rd (list val) 'guarded-vector-ref)]
  16322. [else (vector-ref vec i)]))
  16323. (define (guarded-vector-set! vec i arg)
  16324. (match vec
  16325. [`(vector-proxy ,proxy)
  16326. (define wr (vector-ref (vector-ref proxy 2) i))
  16327. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  16328. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  16329. [else (vector-set! vec i arg)]))
  16330. (define (guarded-vector-length vec)
  16331. (match vec
  16332. [`(vector-proxy ,proxy)
  16333. (guarded-vector-length (vector-ref proxy 0))]
  16334. [else (vector-length vec)]))
  16335. \end{lstlisting}
  16336. \caption{The guarded-vector auxiliary functions.}
  16337. \label{fig:guarded-vector}
  16338. \end{figure}
  16339. \section{Lower Casts}
  16340. \label{sec:lower-casts}
  16341. The next step in the journey towards x86 is the \code{lower-casts}
  16342. pass that translates the casts in \LangCast{} to the lower-level
  16343. \code{Inject} and \code{Project} operators and a new operator for
  16344. creating vector proxies, extending the \LangLoop{} language to create
  16345. \LangProxy{}. We recommend creating an auxiliary function named
  16346. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  16347. and a target type, and translates it to expression in \LangProxy{} that has
  16348. the same behavior as casting the expression from the source to the
  16349. target type in the interpreter.
  16350. The \code{lower-cast} function can follow a code structure similar to
  16351. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  16352. the interpreter for \LangCast{} because it must handle the same cases as
  16353. \code{apply-cast} and it needs to mimic the behavior of
  16354. \code{apply-cast}. The most interesting cases are those concerning the
  16355. casts between two vector types and between two function types.
  16356. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  16357. type to another vector type is accomplished by creating a proxy that
  16358. intercepts the operations on the underlying vector. Here we make the
  16359. creation of the proxy explicit with the \code{vector-proxy} primitive
  16360. operation. It takes three arguments, the first is an expression for
  16361. the vector, the second is a vector of functions for casting an element
  16362. that is being read from the vector, and the third is a vector of
  16363. functions for casting an element that is being written to the vector.
  16364. You can create the functions using \code{Lambda}. Also, as we shall
  16365. see in the next section, we need to differentiate these vectors from
  16366. the user-created ones, so we recommend using a new primitive operator
  16367. named \code{raw-vector} instead of \code{vector} to create these
  16368. vectors of functions. Figure~\ref{fig:map-bang-lower-cast} shows
  16369. the output of \code{lower-casts} on the example in
  16370. Figure~\ref{fig:map-bang} that involved casting a vector of
  16371. integers to a vector of \code{Any}.
  16372. \begin{figure}[tbp]
  16373. \begin{lstlisting}
  16374. (define (map! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  16375. (begin
  16376. (vector-set! v 0 (f (vector-ref v 0)))
  16377. (vector-set! v 1 (f (vector-ref v 1)))))
  16378. (define (inc [x : Any]) : Any
  16379. (inject (+ (project x Integer) 1) Integer))
  16380. (let ([v (vector 0 41)])
  16381. (begin
  16382. (map! inc (vector-proxy v
  16383. (raw-vector (lambda: ([x9 : Integer]) : Any
  16384. (inject x9 Integer))
  16385. (lambda: ([x9 : Integer]) : Any
  16386. (inject x9 Integer)))
  16387. (raw-vector (lambda: ([x9 : Any]) : Integer
  16388. (project x9 Integer))
  16389. (lambda: ([x9 : Any]) : Integer
  16390. (project x9 Integer)))))
  16391. (vector-ref v 1)))
  16392. \end{lstlisting}
  16393. \caption{Output of \code{lower-casts} on the example in
  16394. Figure~\ref{fig:map-bang}.}
  16395. \label{fig:map-bang-lower-cast}
  16396. \end{figure}
  16397. A cast from one function type to another function type is accomplished
  16398. by generating a \code{Lambda} whose parameter and return types match
  16399. the target function type. The body of the \code{Lambda} should cast
  16400. the parameters from the target type to the source type (yes,
  16401. backwards! functions are contravariant\index{subject}{contravariant} in the
  16402. parameters), then call the underlying function, and finally cast the
  16403. result from the source return type to the target return type.
  16404. Figure~\ref{fig:map-lower-cast} shows the output of the
  16405. \code{lower-casts} pass on the \code{map} example in
  16406. Figure~\ref{fig:gradual-map}. Note that the \code{inc} argument
  16407. in the call to \code{map} is wrapped in a \code{lambda}.
  16408. \begin{figure}[tbp]
  16409. \begin{lstlisting}
  16410. (define (map [f : (Integer -> Integer)]
  16411. [v : (Vector Integer Integer)])
  16412. : (Vector Integer Integer)
  16413. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16414. (define (inc [x : Any]) : Any
  16415. (inject (+ (project x Integer) 1) Integer))
  16416. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  16417. (project (inc (inject x9 Integer)) Integer))
  16418. (vector 0 41)) 1)
  16419. \end{lstlisting}
  16420. \caption{Output of \code{lower-casts} on the example in
  16421. Figure~\ref{fig:gradual-map}.}
  16422. \label{fig:map-lower-cast}
  16423. \end{figure}
  16424. \section{Differentiate Proxies}
  16425. \label{sec:differentiate-proxies}
  16426. So far the job of differentiating vectors and vector proxies has been
  16427. the job of the interpreter. For example, the interpreter for \LangCast{}
  16428. implements \code{vector-ref} using the \code{guarded-vector-ref}
  16429. function in Figure~\ref{fig:guarded-vector}. In the
  16430. \code{differentiate-proxies} pass we shift this responsibility to the
  16431. generated code.
  16432. We begin by designing the output language $R^p_8$. In
  16433. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  16434. proxies. In $R^p_8$ we return the \code{Vector} type to
  16435. its original meaning, as the type of real vectors, and we introduce a
  16436. new type, \code{PVector}, whose values can be either real vectors or
  16437. vector proxies. This new type comes with a suite of new primitive
  16438. operations for creating and using values of type \code{PVector}. We
  16439. don't need to introduce a new type to represent vector proxies. A
  16440. proxy is represented by a vector containing three things: 1) the
  16441. underlying vector, 2) a vector of functions for casting elements that
  16442. are read from the vector, and 3) a vector of functions for casting
  16443. values to be written to the vector. So we define the following
  16444. abbreviation for the type of a vector proxy:
  16445. \[
  16446. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  16447. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  16448. \to (\key{PVector}~ T' \ldots)
  16449. \]
  16450. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  16451. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  16452. %
  16453. Next we describe each of the new primitive operations.
  16454. \begin{description}
  16455. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  16456. (\key{PVector} $T \ldots$)]\ \\
  16457. %
  16458. This operation brands a vector as a value of the \code{PVector} type.
  16459. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  16460. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  16461. %
  16462. This operation brands a vector proxy as value of the \code{PVector} type.
  16463. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  16464. \code{Boolean}] \ \\
  16465. %
  16466. returns true if the value is a vector proxy and false if it is a
  16467. real vector.
  16468. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  16469. (\key{Vector} $T \ldots$)]\ \\
  16470. %
  16471. Assuming that the input is a vector (and not a proxy), this
  16472. operation returns the vector.
  16473. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  16474. $\to$ \code{Boolean}]\ \\
  16475. %
  16476. Given a vector proxy, this operation returns the length of the
  16477. underlying vector.
  16478. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  16479. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  16480. %
  16481. Given a vector proxy, this operation returns the $i$th element of
  16482. the underlying vector.
  16483. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  16484. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  16485. proxy, this operation writes a value to the $i$th element of the
  16486. underlying vector.
  16487. \end{description}
  16488. Now to discuss the translation that differentiates vectors from
  16489. proxies. First, every type annotation in the program must be
  16490. translated (recursively) to replace \code{Vector} with \code{PVector}.
  16491. Next, we must insert uses of \code{PVector} operations in the
  16492. appropriate places. For example, we wrap every vector creation with an
  16493. \code{inject-vector}.
  16494. \begin{lstlisting}
  16495. (vector |$e_1 \ldots e_n$|)
  16496. |$\Rightarrow$|
  16497. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  16498. \end{lstlisting}
  16499. The \code{raw-vector} operator that we introduced in the previous
  16500. section does not get injected.
  16501. \begin{lstlisting}
  16502. (raw-vector |$e_1 \ldots e_n$|)
  16503. |$\Rightarrow$|
  16504. (vector |$e'_1 \ldots e'_n$|)
  16505. \end{lstlisting}
  16506. The \code{vector-proxy} primitive translates as follows.
  16507. \begin{lstlisting}
  16508. (vector-proxy |$e_1~e_2~e_3$|)
  16509. |$\Rightarrow$|
  16510. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  16511. \end{lstlisting}
  16512. We translate the vector operations into conditional expressions that
  16513. check whether the value is a proxy and then dispatch to either the
  16514. appropriate proxy vector operation or the regular vector operation.
  16515. For example, the following is the translation for \code{vector-ref}.
  16516. \begin{lstlisting}
  16517. (vector-ref |$e_1$| |$i$|)
  16518. |$\Rightarrow$|
  16519. (let ([|$v~e_1$|])
  16520. (if (proxy? |$v$|)
  16521. (proxy-vector-ref |$v$| |$i$|)
  16522. (vector-ref (project-vector |$v$|) |$i$|)
  16523. \end{lstlisting}
  16524. Note in the case of a real vector, we must apply \code{project-vector}
  16525. before the \code{vector-ref}.
  16526. \section{Reveal Casts}
  16527. \label{sec:reveal-casts-gradual}
  16528. Recall that the \code{reveal-casts} pass
  16529. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  16530. \code{Inject} and \code{Project} into lower-level operations. In
  16531. particular, \code{Project} turns into a conditional expression that
  16532. inspects the tag and retrieves the underlying value. Here we need to
  16533. augment the translation of \code{Project} to handle the situation when
  16534. the target type is \code{PVector}. Instead of using
  16535. \code{vector-length} we need to use \code{proxy-vector-length}.
  16536. \begin{lstlisting}
  16537. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  16538. |$\Rightarrow$|
  16539. (let |$\itm{tmp}$| |$e'$|
  16540. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  16541. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  16542. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  16543. (exit)))
  16544. \end{lstlisting}
  16545. \section{Closure Conversion}
  16546. \label{sec:closure-conversion-gradual}
  16547. The closure conversion pass only requires one minor adjustment. The
  16548. auxiliary function that translates type annotations needs to be
  16549. updated to handle the \code{PVector} type.
  16550. \section{Explicate Control}
  16551. \label{sec:explicate-control-gradual}
  16552. Update the \code{explicate\_control} pass to handle the new primitive
  16553. operations on the \code{PVector} type.
  16554. \section{Select Instructions}
  16555. \label{sec:select-instructions-gradual}
  16556. Recall that the \code{select\_instructions} pass is responsible for
  16557. lowering the primitive operations into x86 instructions. So we need
  16558. to translate the new \code{PVector} operations to x86. To do so, the
  16559. first question we need to answer is how will we differentiate the two
  16560. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  16561. We need just one bit to accomplish this, and use the bit in position
  16562. $57$ of the 64-bit tag at the front of every vector (see
  16563. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  16564. for \code{inject-vector} we leave it that way.
  16565. \begin{lstlisting}
  16566. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  16567. |$\Rightarrow$|
  16568. movq |$e'_1$|, |$\itm{lhs'}$|
  16569. \end{lstlisting}
  16570. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  16571. \begin{lstlisting}
  16572. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  16573. |$\Rightarrow$|
  16574. movq |$e'_1$|, %r11
  16575. movq |$(1 << 57)$|, %rax
  16576. orq 0(%r11), %rax
  16577. movq %rax, 0(%r11)
  16578. movq %r11, |$\itm{lhs'}$|
  16579. \end{lstlisting}
  16580. The \code{proxy?} operation consumes the information so carefully
  16581. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  16582. isolates the $57$th bit to tell whether the value is a real vector or
  16583. a proxy.
  16584. \begin{lstlisting}
  16585. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  16586. |$\Rightarrow$|
  16587. movq |$e_1'$|, %r11
  16588. movq 0(%r11), %rax
  16589. sarq $57, %rax
  16590. andq $1, %rax
  16591. movq %rax, |$\itm{lhs'}$|
  16592. \end{lstlisting}
  16593. The \code{project-vector} operation is straightforward to translate,
  16594. so we leave it up to the reader.
  16595. Regarding the \code{proxy-vector} operations, the runtime provides
  16596. procedures that implement them (they are recursive functions!) so
  16597. here we simply need to translate these vector operations into the
  16598. appropriate function call. For example, here is the translation for
  16599. \code{proxy-vector-ref}.
  16600. \begin{lstlisting}
  16601. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  16602. |$\Rightarrow$|
  16603. movq |$e_1'$|, %rdi
  16604. movq |$e_2'$|, %rsi
  16605. callq proxy_vector_ref
  16606. movq %rax, |$\itm{lhs'}$|
  16607. \end{lstlisting}
  16608. We have another batch of vector operations to deal with, those for the
  16609. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  16610. \code{any-vector-ref} when there is a \code{vector-ref} on something
  16611. of type \code{Any}, and similarly for \code{any-vector-set!} and
  16612. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  16613. Section~\ref{sec:select-Rany} we selected instructions for these
  16614. operations based on the idea that the underlying value was a real
  16615. vector. But in the current setting, the underlying value is of type
  16616. \code{PVector}. So \code{any-vector-ref} can be translates to
  16617. pseudo-x86 as follows. We begin by projecting the underlying value out
  16618. of the tagged value and then call the \code{proxy\_vector\_ref}
  16619. procedure in the runtime.
  16620. \begin{lstlisting}
  16621. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  16622. movq |$\neg 111$|, %rdi
  16623. andq |$e_1'$|, %rdi
  16624. movq |$e_2'$|, %rsi
  16625. callq proxy_vector_ref
  16626. movq %rax, |$\itm{lhs'}$|
  16627. \end{lstlisting}
  16628. The \code{any-vector-set!} and \code{any-vector-length} operators can
  16629. be translated in a similar way.
  16630. \begin{exercise}\normalfont
  16631. Implement a compiler for the gradually-typed \LangGrad{} language by
  16632. extending and adapting your compiler for \LangLoop{}. Create 10 new
  16633. partially-typed test programs. In addition to testing with these
  16634. new programs, also test your compiler on all the tests for \LangLoop{}
  16635. and tests for \LangDyn{}. Sometimes you may get a type checking error
  16636. on the \LangDyn{} programs but you can adapt them by inserting
  16637. a cast to the \code{Any} type around each subexpression
  16638. causing a type error. While \LangDyn{} doesn't have explicit casts,
  16639. you can induce one by wrapping the subexpression \code{e}
  16640. with a call to an un-annotated identity function, like this:
  16641. \code{((lambda (x) x) e)}.
  16642. \end{exercise}
  16643. \begin{figure}[p]
  16644. \begin{tikzpicture}[baseline=(current bounding box.center)]
  16645. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  16646. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  16647. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  16648. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  16649. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  16650. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  16651. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  16652. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  16653. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  16654. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  16655. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  16656. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  16657. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  16658. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  16659. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  16660. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  16661. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  16662. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  16663. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  16664. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  16665. \path[->,bend right=15] (Rgradual) edge [above] node
  16666. {\ttfamily\footnotesize type\_check} (Rgradualp);
  16667. \path[->,bend right=15] (Rgradualp) edge [above] node
  16668. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  16669. \path[->,bend right=15] (Rwhilepp) edge [right] node
  16670. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  16671. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  16672. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  16673. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  16674. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  16675. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  16676. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  16677. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  16678. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  16679. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  16680. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16681. \path[->,bend left=15] (F1-1) edge [below] node
  16682. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  16683. \path[->,bend right=15] (F1-2) edge [above] node
  16684. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  16685. \path[->,bend right=15] (F1-3) edge [above] node
  16686. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  16687. \path[->,bend right=15] (F1-4) edge [above] node
  16688. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  16689. \path[->,bend right=15] (F1-5) edge [right] node
  16690. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16691. \path[->,bend left=15] (C3-2) edge [left] node
  16692. {\ttfamily\footnotesize select\_instr.} (x86-2);
  16693. \path[->,bend right=15] (x86-2) edge [left] node
  16694. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16695. \path[->,bend right=15] (x86-2-1) edge [below] node
  16696. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  16697. \path[->,bend right=15] (x86-2-2) edge [left] node
  16698. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  16699. \path[->,bend left=15] (x86-3) edge [above] node
  16700. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  16701. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  16702. \end{tikzpicture}
  16703. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  16704. \label{fig:Rgradual-passes}
  16705. \end{figure}
  16706. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  16707. for the compilation of \LangGrad{}.
  16708. \section{Further Reading}
  16709. This chapter just scratches the surface of gradual typing. The basic
  16710. approach described here is missing two key ingredients that one would
  16711. want in a implementation of gradual typing: blame
  16712. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  16713. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  16714. problem addressed by blame tracking is that when a cast on a
  16715. higher-order value fails, it often does so at a point in the program
  16716. that is far removed from the original cast. Blame tracking is a
  16717. technique for propagating extra information through casts and proxies
  16718. so that when a cast fails, the error message can point back to the
  16719. original location of the cast in the source program.
  16720. The problem addressed by space-efficient casts also relates to
  16721. higher-order casts. It turns out that in partially typed programs, a
  16722. function or vector can flow through very-many casts at runtime. With
  16723. the approach described in this chapter, each cast adds another
  16724. \code{lambda} wrapper or a vector proxy. Not only does this take up
  16725. considerable space, but it also makes the function calls and vector
  16726. operations slow. For example, a partially-typed version of quicksort
  16727. could, in the worst case, build a chain of proxies of length $O(n)$
  16728. around the vector, changing the overall time complexity of the
  16729. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  16730. solution to this problem by representing casts using the coercion
  16731. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  16732. long chains of proxies by compressing them into a concise normal
  16733. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  16734. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  16735. the Grift compiler.
  16736. \begin{center}
  16737. \url{https://github.com/Gradual-Typing/Grift}
  16738. \end{center}
  16739. There are also interesting interactions between gradual typing and
  16740. other language features, such as parametetric polymorphism,
  16741. information-flow types, and type inference, to name a few. We
  16742. recommend the reader to the online gradual typing bibliography:
  16743. \begin{center}
  16744. \url{http://samth.github.io/gradual-typing-bib/}
  16745. \end{center}
  16746. % TODO: challenge problem:
  16747. % type analysis and type specialization?
  16748. % coercions?
  16749. \fi
  16750. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16751. \chapter{Parametric Polymorphism}
  16752. \label{ch:Rpoly}
  16753. \index{subject}{parametric polymorphism}
  16754. \index{subject}{generics}
  16755. \if\edition\racketEd
  16756. This chapter studies the compilation of parametric
  16757. polymorphism\index{subject}{parametric polymorphism}
  16758. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  16759. Racket. Parametric polymorphism enables improved code reuse by
  16760. parameterizing functions and data structures with respect to the types
  16761. that they operate on. For example, Figure~\ref{fig:map-poly}
  16762. revisits the \code{map} example but this time gives it a more
  16763. fitting type. This \code{map} function is parameterized with
  16764. respect to the element type of the vector. The type of \code{map}
  16765. is the following polymorphic type as specified by the \code{All} and
  16766. the type parameter \code{a}.
  16767. \begin{lstlisting}
  16768. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  16769. \end{lstlisting}
  16770. The idea is that \code{map} can be used at \emph{all} choices of a
  16771. type for parameter \code{a}. In Figure~\ref{fig:map-poly} we apply
  16772. \code{map} to a vector of integers, a choice of \code{Integer} for
  16773. \code{a}, but we could have just as well applied \code{map} to a
  16774. vector of Booleans (and a function on Booleans).
  16775. \begin{figure}[tbp]
  16776. % poly_test_2.rkt
  16777. \begin{lstlisting}
  16778. (: map (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  16779. (define (map f v)
  16780. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16781. (define (inc [x : Integer]) : Integer (+ x 1))
  16782. (vector-ref (map inc (vector 0 41)) 1)
  16783. \end{lstlisting}
  16784. \caption{The \code{map} example using parametric polymorphism.}
  16785. \label{fig:map-poly}
  16786. \end{figure}
  16787. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  16788. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  16789. syntax. We add a second form for function definitions in which a type
  16790. declaration comes before the \code{define}. In the abstract syntax,
  16791. the return type in the \code{Def} is \code{Any}, but that should be
  16792. ignored in favor of the return type in the type declaration. (The
  16793. \code{Any} comes from using the same parser as in
  16794. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  16795. enables the use of an \code{All} type for a function, thereby making
  16796. it polymorphic. The grammar for types is extended to include
  16797. polymorphic types and type variables.
  16798. \begin{figure}[tp]
  16799. \centering
  16800. \fbox{
  16801. \begin{minipage}{0.96\textwidth}
  16802. \small
  16803. \[
  16804. \begin{array}{lcl}
  16805. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  16806. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  16807. &\MID& \LP\key{:}~\Var~\Type\RP \\
  16808. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  16809. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  16810. \end{array}
  16811. \]
  16812. \end{minipage}
  16813. }
  16814. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  16815. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  16816. \label{fig:Rpoly-concrete-syntax}
  16817. \end{figure}
  16818. \begin{figure}[tp]
  16819. \centering
  16820. \fbox{
  16821. \begin{minipage}{0.96\textwidth}
  16822. \small
  16823. \[
  16824. \begin{array}{lcl}
  16825. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  16826. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  16827. &\MID& \DECL{\Var}{\Type} \\
  16828. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  16829. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  16830. \end{array}
  16831. \]
  16832. \end{minipage}
  16833. }
  16834. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  16835. (Figure~\ref{fig:Lwhile-syntax}).}
  16836. \label{fig:Rpoly-syntax}
  16837. \end{figure}
  16838. By including polymorphic types in the $\Type$ non-terminal we choose
  16839. to make them first-class which has interesting repercussions on the
  16840. compiler. Many languages with polymorphism, such as
  16841. C++~\citep{stroustrup88:_param_types} and Standard
  16842. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  16843. it is useful to see an example of first-class polymorphism. In
  16844. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  16845. whose parameter is a polymorphic function. The occurrence of a
  16846. polymorphic type underneath a function type is enabled by the normal
  16847. recursive structure of the grammar for $\Type$ and the categorization
  16848. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  16849. applies the polymorphic function to a Boolean and to an integer.
  16850. \begin{figure}[tbp]
  16851. \begin{lstlisting}
  16852. (: apply-twice ((All (b) (b -> b)) -> Integer))
  16853. (define (apply-twice f)
  16854. (if (f #t) (f 42) (f 777)))
  16855. (: id (All (a) (a -> a)))
  16856. (define (id x) x)
  16857. (apply-twice id)
  16858. \end{lstlisting}
  16859. \caption{An example illustrating first-class polymorphism.}
  16860. \label{fig:apply-twice}
  16861. \end{figure}
  16862. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  16863. three new responsibilities (compared to \LangLoop{}). The type checking of
  16864. function application is extended to handle the case where the operator
  16865. expression is a polymorphic function. In that case the type arguments
  16866. are deduced by matching the type of the parameters with the types of
  16867. the arguments.
  16868. %
  16869. The \code{match-types} auxiliary function carries out this deduction
  16870. by recursively descending through a parameter type \code{pt} and the
  16871. corresponding argument type \code{at}, making sure that they are equal
  16872. except when there is a type parameter on the left (in the parameter
  16873. type). If it's the first time that the type parameter has been
  16874. encountered, then the algorithm deduces an association of the type
  16875. parameter to the corresponding type on the right (in the argument
  16876. type). If it's not the first time that the type parameter has been
  16877. encountered, the algorithm looks up its deduced type and makes sure
  16878. that it is equal to the type on the right.
  16879. %
  16880. Once the type arguments are deduced, the operator expression is
  16881. wrapped in an \code{Inst} AST node (for instantiate) that records the
  16882. type of the operator, but more importantly, records the deduced type
  16883. arguments. The return type of the application is the return type of
  16884. the polymorphic function, but with the type parameters replaced by the
  16885. deduced type arguments, using the \code{subst-type} function.
  16886. The second responsibility of the type checker is extending the
  16887. function \code{type-equal?} to handle the \code{All} type. This is
  16888. not quite a simple as equal on other types, such as function and
  16889. vector types, because two polymorphic types can be syntactically
  16890. different even though they are equivalent types. For example,
  16891. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  16892. Two polymorphic types should be considered equal if they differ only
  16893. in the choice of the names of the type parameters. The
  16894. \code{type-equal?} function in Figure~\ref{fig:type-check-Lvar0-aux}
  16895. renames the type parameters of the first type to match the type
  16896. parameters of the second type.
  16897. The third responsibility of the type checker is making sure that only
  16898. defined type variables appear in type annotations. The
  16899. \code{check-well-formed} function defined in
  16900. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  16901. sure that each type variable has been defined.
  16902. The output language of the type checker is \LangInst{}, defined in
  16903. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  16904. declaration and polymorphic function into a single definition, using
  16905. the \code{Poly} form, to make polymorphic functions more convenient to
  16906. process in next pass of the compiler.
  16907. \begin{figure}[tp]
  16908. \centering
  16909. \fbox{
  16910. \begin{minipage}{0.96\textwidth}
  16911. \small
  16912. \[
  16913. \begin{array}{lcl}
  16914. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  16915. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  16916. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  16917. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  16918. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  16919. \end{array}
  16920. \]
  16921. \end{minipage}
  16922. }
  16923. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  16924. (Figure~\ref{fig:Lwhile-syntax}).}
  16925. \label{fig:Rpoly-prime-syntax}
  16926. \end{figure}
  16927. The output of the type checker on the polymorphic \code{map}
  16928. example is listed in Figure~\ref{fig:map-type-check}.
  16929. \begin{figure}[tbp]
  16930. % poly_test_2.rkt
  16931. \begin{lstlisting}
  16932. (poly (a) (define (map [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  16933. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  16934. (define (inc [x : Integer]) : Integer (+ x 1))
  16935. (vector-ref ((inst map (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  16936. (Integer))
  16937. inc (vector 0 41)) 1)
  16938. \end{lstlisting}
  16939. \caption{Output of the type checker on the \code{map} example.}
  16940. \label{fig:map-type-check}
  16941. \end{figure}
  16942. \begin{figure}[tbp]
  16943. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  16944. (define type-check-poly-class
  16945. (class type-check-Rwhile-class
  16946. (super-new)
  16947. (inherit check-type-equal?)
  16948. (define/override (type-check-apply env e1 es)
  16949. (define-values (e^ ty) ((type-check-exp env) e1))
  16950. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  16951. ((type-check-exp env) e)))
  16952. (match ty
  16953. [`(,ty^* ... -> ,rt)
  16954. (for ([arg-ty ty*] [param-ty ty^*])
  16955. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  16956. (values e^ es^ rt)]
  16957. [`(All ,xs (,tys ... -> ,rt))
  16958. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  16959. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  16960. (match-types env^^ param-ty arg-ty)))
  16961. (define targs
  16962. (for/list ([x xs])
  16963. (match (dict-ref env^^ x (lambda () #f))
  16964. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  16965. x (Apply e1 es))]
  16966. [ty ty])))
  16967. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  16968. [else (error 'type-check "expected a function, not ~a" ty)]))
  16969. (define/override ((type-check-exp env) e)
  16970. (match e
  16971. [(Lambda `([,xs : ,Ts] ...) rT body)
  16972. (for ([T Ts]) ((check-well-formed env) T))
  16973. ((check-well-formed env) rT)
  16974. ((super type-check-exp env) e)]
  16975. [(HasType e1 ty)
  16976. ((check-well-formed env) ty)
  16977. ((super type-check-exp env) e)]
  16978. [else ((super type-check-exp env) e)]))
  16979. (define/override ((type-check-def env) d)
  16980. (verbose 'type-check "poly/def" d)
  16981. (match d
  16982. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  16983. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  16984. (for ([p ps]) ((check-well-formed ts-env) p))
  16985. ((check-well-formed ts-env) rt)
  16986. (define new-env (append ts-env (map cons xs ps) env))
  16987. (define-values (body^ ty^) ((type-check-exp new-env) body))
  16988. (check-type-equal? ty^ rt body)
  16989. (Generic ts (Def f p:t* rt info body^))]
  16990. [else ((super type-check-def env) d)]))
  16991. (define/override (type-check-program p)
  16992. (match p
  16993. [(Program info body)
  16994. (type-check-program (ProgramDefsExp info '() body))]
  16995. [(ProgramDefsExp info ds body)
  16996. (define ds^ (combine-decls-defs ds))
  16997. (define new-env (for/list ([d ds^])
  16998. (cons (def-name d) (fun-def-type d))))
  16999. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  17000. (define-values (body^ ty) ((type-check-exp new-env) body))
  17001. (check-type-equal? ty 'Integer body)
  17002. (ProgramDefsExp info ds^^ body^)]))
  17003. ))
  17004. \end{lstlisting}
  17005. \caption{Type checker for the \LangPoly{} language.}
  17006. \label{fig:type-check-Lvar0}
  17007. \end{figure}
  17008. \begin{figure}[tbp]
  17009. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17010. (define/override (type-equal? t1 t2)
  17011. (match* (t1 t2)
  17012. [(`(All ,xs ,T1) `(All ,ys ,T2))
  17013. (define env (map cons xs ys))
  17014. (type-equal? (subst-type env T1) T2)]
  17015. [(other wise)
  17016. (super type-equal? t1 t2)]))
  17017. (define/public (match-types env pt at)
  17018. (match* (pt at)
  17019. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  17020. [('Void 'Void) env] [('Any 'Any) env]
  17021. [(`(Vector ,pts ...) `(Vector ,ats ...))
  17022. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  17023. (match-types env^ pt1 at1))]
  17024. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  17025. (define env^ (match-types env prt art))
  17026. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  17027. (match-types env^^ pt1 at1))]
  17028. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  17029. (define env^ (append (map cons pxs axs) env))
  17030. (match-types env^ pt1 at1)]
  17031. [((? symbol? x) at)
  17032. (match (dict-ref env x (lambda () #f))
  17033. [#f (error 'type-check "undefined type variable ~a" x)]
  17034. ['Type (cons (cons x at) env)]
  17035. [t^ (check-type-equal? at t^ 'matching) env])]
  17036. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  17037. (define/public (subst-type env pt)
  17038. (match pt
  17039. ['Integer 'Integer] ['Boolean 'Boolean]
  17040. ['Void 'Void] ['Any 'Any]
  17041. [`(Vector ,ts ...)
  17042. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  17043. [`(,ts ... -> ,rt)
  17044. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  17045. [`(All ,xs ,t)
  17046. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  17047. [(? symbol? x) (dict-ref env x)]
  17048. [else (error 'type-check "expected a type not ~a" pt)]))
  17049. (define/public (combine-decls-defs ds)
  17050. (match ds
  17051. ['() '()]
  17052. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  17053. (unless (equal? name f)
  17054. (error 'type-check "name mismatch, ~a != ~a" name f))
  17055. (match type
  17056. [`(All ,xs (,ps ... -> ,rt))
  17057. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  17058. (cons (Generic xs (Def name params^ rt info body))
  17059. (combine-decls-defs ds^))]
  17060. [`(,ps ... -> ,rt)
  17061. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  17062. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  17063. [else (error 'type-check "expected a function type, not ~a" type) ])]
  17064. [`(,(Def f params rt info body) . ,ds^)
  17065. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  17066. \end{lstlisting}
  17067. \caption{Auxiliary functions for type checking \LangPoly{}.}
  17068. \label{fig:type-check-Lvar0-aux}
  17069. \end{figure}
  17070. \begin{figure}[tbp]
  17071. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  17072. (define/public ((check-well-formed env) ty)
  17073. (match ty
  17074. ['Integer (void)]
  17075. ['Boolean (void)]
  17076. ['Void (void)]
  17077. [(? symbol? a)
  17078. (match (dict-ref env a (lambda () #f))
  17079. ['Type (void)]
  17080. [else (error 'type-check "undefined type variable ~a" a)])]
  17081. [`(Vector ,ts ...)
  17082. (for ([t ts]) ((check-well-formed env) t))]
  17083. [`(,ts ... -> ,t)
  17084. (for ([t ts]) ((check-well-formed env) t))
  17085. ((check-well-formed env) t)]
  17086. [`(All ,xs ,t)
  17087. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  17088. ((check-well-formed env^) t)]
  17089. [else (error 'type-check "unrecognized type ~a" ty)]))
  17090. \end{lstlisting}
  17091. \caption{Well-formed types.}
  17092. \label{fig:well-formed-types}
  17093. \end{figure}
  17094. % TODO: interpreter for R'_10
  17095. \section{Compiling Polymorphism}
  17096. \label{sec:compiling-poly}
  17097. Broadly speaking, there are four approaches to compiling parametric
  17098. polymorphism, which we describe below.
  17099. \begin{description}
  17100. \item[Monomorphization] generates a different version of a polymorphic
  17101. function for each set of type arguments that it is used with,
  17102. producing type-specialized code. This approach results in the most
  17103. efficient code but requires whole-program compilation (no separate
  17104. compilation) and increases code size. For our current purposes
  17105. monomorphization is a non-starter because, with first-class
  17106. polymorphism, it is sometimes not possible to determine which
  17107. generic functions are used with which type arguments during
  17108. compilation. (It can be done at runtime, with just-in-time
  17109. compilation.) This approach is used to compile C++
  17110. templates~\citep{stroustrup88:_param_types} and polymorphic
  17111. functions in NESL~\citep{Blelloch:1993aa} and
  17112. ML~\citep{Weeks:2006aa}.
  17113. \item[Uniform representation] generates one version of each
  17114. polymorphic function but requires all values have a common ``boxed''
  17115. format, such as the tagged values of type \code{Any} in
  17116. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  17117. similarly to code in a dynamically typed language (like \LangDyn{}),
  17118. in which primitive operators require their arguments to be projected
  17119. from \code{Any} and their results are injected into \code{Any}. (In
  17120. object-oriented languages, the projection is accomplished via
  17121. virtual method dispatch.) The uniform representation approach is
  17122. compatible with separate compilation and with first-class
  17123. polymorphism. However, it produces the least-efficient code because
  17124. it introduces overhead in the entire program, including
  17125. non-polymorphic code. This approach is used in implementations of
  17126. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  17127. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  17128. Java~\citep{Bracha:1998fk}.
  17129. \item[Mixed representation] generates one version of each polymorphic
  17130. function, using a boxed representation for type
  17131. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  17132. and conversions are performed at the boundaries between monomorphic
  17133. and polymorphic (e.g. when a polymorphic function is instantiated
  17134. and called). This approach is compatible with separate compilation
  17135. and first-class polymorphism and maintains the efficiency of
  17136. monomorphic code. The tradeoff is increased overhead at the boundary
  17137. between monomorphic and polymorphic code. This approach is used in
  17138. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  17139. Java 5 with the addition of autoboxing.
  17140. \item[Type passing] uses the unboxed representation in both
  17141. monomorphic and polymorphic code. Each polymorphic function is
  17142. compiled to a single function with extra parameters that describe
  17143. the type arguments. The type information is used by the generated
  17144. code to know how to access the unboxed values at runtime. This
  17145. approach is used in implementation of the Napier88
  17146. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  17147. passing is compatible with separate compilation and first-class
  17148. polymorphism and maintains the efficiency for monomorphic
  17149. code. There is runtime overhead in polymorphic code from dispatching
  17150. on type information.
  17151. \end{description}
  17152. In this chapter we use the mixed representation approach, partly
  17153. because of its favorable attributes, and partly because it is
  17154. straightforward to implement using the tools that we have already
  17155. built to support gradual typing. To compile polymorphic functions, we
  17156. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  17157. \LangCast{}.
  17158. \section{Erase Types}
  17159. \label{sec:erase-types}
  17160. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  17161. represent type variables. For example, Figure~\ref{fig:map-erase}
  17162. shows the output of the \code{erase-types} pass on the polymorphic
  17163. \code{map} (Figure~\ref{fig:map-poly}). The occurrences of
  17164. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  17165. \code{All} types are removed from the type of \code{map}.
  17166. \begin{figure}[tbp]
  17167. \begin{lstlisting}
  17168. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  17169. : (Vector Any Any)
  17170. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17171. (define (inc [x : Integer]) : Integer (+ x 1))
  17172. (vector-ref ((cast map
  17173. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  17174. ((Integer -> Integer) (Vector Integer Integer)
  17175. -> (Vector Integer Integer)))
  17176. inc (vector 0 41)) 1)
  17177. \end{lstlisting}
  17178. \caption{The polymorphic \code{map} example after type erasure.}
  17179. \label{fig:map-erase}
  17180. \end{figure}
  17181. This process of type erasure creates a challenge at points of
  17182. instantiation. For example, consider the instantiation of
  17183. \code{map} in Figure~\ref{fig:map-type-check}.
  17184. The type of \code{map} is
  17185. \begin{lstlisting}
  17186. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  17187. \end{lstlisting}
  17188. and it is instantiated to
  17189. \begin{lstlisting}
  17190. ((Integer -> Integer) (Vector Integer Integer)
  17191. -> (Vector Integer Integer))
  17192. \end{lstlisting}
  17193. After erasure, the type of \code{map} is
  17194. \begin{lstlisting}
  17195. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  17196. \end{lstlisting}
  17197. but we need to convert it to the instantiated type. This is easy to
  17198. do in the target language \LangCast{} with a single \code{cast}. In
  17199. Figure~\ref{fig:map-erase}, the instantiation of \code{map}
  17200. has been compiled to a \code{cast} from the type of \code{map} to
  17201. the instantiated type. The source and target type of a cast must be
  17202. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  17203. because both the source and target are obtained from the same
  17204. polymorphic type of \code{map}, replacing the type parameters with
  17205. \code{Any} in the former and with the deduced type arguments in the
  17206. later. (Recall that the \code{Any} type is consistent with any type.)
  17207. To implement the \code{erase-types} pass, we recommend defining a
  17208. recursive auxiliary function named \code{erase-type} that applies the
  17209. following two transformations. It replaces type variables with
  17210. \code{Any}
  17211. \begin{lstlisting}
  17212. |$x$|
  17213. |$\Rightarrow$|
  17214. Any
  17215. \end{lstlisting}
  17216. and it removes the polymorphic \code{All} types.
  17217. \begin{lstlisting}
  17218. (All |$xs$| |$T_1$|)
  17219. |$\Rightarrow$|
  17220. |$T'_1$|
  17221. \end{lstlisting}
  17222. Apply the \code{erase-type} function to all of the type annotations in
  17223. the program.
  17224. Regarding the translation of expressions, the case for \code{Inst} is
  17225. the interesting one. We translate it into a \code{Cast}, as shown
  17226. below. The type of the subexpression $e$ is the polymorphic type
  17227. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  17228. $T$, the type $T'$. The target type $T''$ is the result of
  17229. substituting the arguments types $ts$ for the type parameters $xs$ in
  17230. $T$ followed by doing type erasure.
  17231. \begin{lstlisting}
  17232. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  17233. |$\Rightarrow$|
  17234. (Cast |$e'$| |$T'$| |$T''$|)
  17235. \end{lstlisting}
  17236. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  17237. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  17238. Finally, each polymorphic function is translated to a regular
  17239. functions in which type erasure has been applied to all the type
  17240. annotations and the body.
  17241. \begin{lstlisting}
  17242. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  17243. |$\Rightarrow$|
  17244. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  17245. \end{lstlisting}
  17246. \begin{exercise}\normalfont
  17247. Implement a compiler for the polymorphic language \LangPoly{} by
  17248. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  17249. programs that use polymorphic functions. Some of them should make
  17250. use of first-class polymorphism.
  17251. \end{exercise}
  17252. \begin{figure}[p]
  17253. \begin{tikzpicture}[baseline=(current bounding box.center)]
  17254. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  17255. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  17256. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  17257. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  17258. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  17259. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  17260. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  17261. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  17262. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  17263. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  17264. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  17265. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  17266. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  17267. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  17268. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  17269. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  17270. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  17271. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  17272. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  17273. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  17274. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  17275. \path[->,bend right=15] (Rpoly) edge [above] node
  17276. {\ttfamily\footnotesize type\_check} (Rpolyp);
  17277. \path[->,bend right=15] (Rpolyp) edge [above] node
  17278. {\ttfamily\footnotesize erase\_types} (Rgradualp);
  17279. \path[->,bend right=15] (Rgradualp) edge [above] node
  17280. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  17281. \path[->,bend right=15] (Rwhilepp) edge [right] node
  17282. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  17283. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  17284. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  17285. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  17286. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  17287. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  17288. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  17289. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  17290. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  17291. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  17292. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  17293. \path[->,bend left=15] (F1-1) edge [below] node
  17294. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  17295. \path[->,bend right=15] (F1-2) edge [above] node
  17296. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  17297. \path[->,bend right=15] (F1-3) edge [above] node
  17298. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  17299. \path[->,bend right=15] (F1-4) edge [above] node
  17300. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  17301. \path[->,bend right=15] (F1-5) edge [right] node
  17302. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17303. \path[->,bend left=15] (C3-2) edge [left] node
  17304. {\ttfamily\footnotesize select\_instr.} (x86-2);
  17305. \path[->,bend right=15] (x86-2) edge [left] node
  17306. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  17307. \path[->,bend right=15] (x86-2-1) edge [below] node
  17308. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  17309. \path[->,bend right=15] (x86-2-2) edge [left] node
  17310. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  17311. \path[->,bend left=15] (x86-3) edge [above] node
  17312. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  17313. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  17314. \end{tikzpicture}
  17315. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  17316. \label{fig:Rpoly-passes}
  17317. \end{figure}
  17318. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  17319. for the compilation of \LangPoly{}.
  17320. % TODO: challenge problem: specialization of instantiations
  17321. % Further Reading
  17322. \fi
  17323. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17324. \clearpage
  17325. \appendix
  17326. \chapter{Appendix}
  17327. \if\edition\racketEd
  17328. \section{Interpreters}
  17329. \label{appendix:interp}
  17330. \index{subject}{interpreter}
  17331. We provide interpreters for each of the source languages \LangInt{},
  17332. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  17333. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  17334. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  17335. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  17336. and x86 are in the \key{interp.rkt} file.
  17337. \section{Utility Functions}
  17338. \label{appendix:utilities}
  17339. The utility functions described in this section are in the
  17340. \key{utilities.rkt} file of the support code.
  17341. \paragraph{\code{interp-tests}}
  17342. The \key{interp-tests} function runs the compiler passes and the
  17343. interpreters on each of the specified tests to check whether each pass
  17344. is correct. The \key{interp-tests} function has the following
  17345. parameters:
  17346. \begin{description}
  17347. \item[name (a string)] a name to identify the compiler,
  17348. \item[typechecker] a function of exactly one argument that either
  17349. raises an error using the \code{error} function when it encounters a
  17350. type error, or returns \code{\#f} when it encounters a type
  17351. error. If there is no type error, the type checker returns the
  17352. program.
  17353. \item[passes] a list with one entry per pass. An entry is a list with
  17354. four things:
  17355. \begin{enumerate}
  17356. \item a string giving the name of the pass,
  17357. \item the function that implements the pass (a translator from AST
  17358. to AST),
  17359. \item a function that implements the interpreter (a function from
  17360. AST to result value) for the output language,
  17361. \item and a type checker for the output language. Type checkers for
  17362. the $R$ and $C$ languages are provided in the support code. For
  17363. example, the type checkers for \LangVar{} and \LangCVar{} are in
  17364. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  17365. type checker entry is optional. The support code does not provide
  17366. type checkers for the x86 languages.
  17367. \end{enumerate}
  17368. \item[source-interp] an interpreter for the source language. The
  17369. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  17370. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  17371. \item[tests] a list of test numbers that specifies which tests to
  17372. run. (see below)
  17373. \end{description}
  17374. %
  17375. The \key{interp-tests} function assumes that the subdirectory
  17376. \key{tests} has a collection of Racket programs whose names all start
  17377. with the family name, followed by an underscore and then the test
  17378. number, ending with the file extension \key{.rkt}. Also, for each test
  17379. program that calls \code{read} one or more times, there is a file with
  17380. the same name except that the file extension is \key{.in} that
  17381. provides the input for the Racket program. If the test program is
  17382. expected to fail type checking, then there should be an empty file of
  17383. the same name but with extension \key{.tyerr}.
  17384. \paragraph{\code{compiler-tests}}
  17385. runs the compiler passes to generate x86 (a \key{.s} file) and then
  17386. runs the GNU C compiler (gcc) to generate machine code. It runs the
  17387. machine code and checks that the output is $42$. The parameters to the
  17388. \code{compiler-tests} function are similar to those of the
  17389. \code{interp-tests} function, and consist of
  17390. \begin{itemize}
  17391. \item a compiler name (a string),
  17392. \item a type checker,
  17393. \item description of the passes,
  17394. \item name of a test-family, and
  17395. \item a list of test numbers.
  17396. \end{itemize}
  17397. \paragraph{\code{compile-file}}
  17398. takes a description of the compiler passes (see the comment for
  17399. \key{interp-tests}) and returns a function that, given a program file
  17400. name (a string ending in \key{.rkt}), applies all of the passes and
  17401. writes the output to a file whose name is the same as the program file
  17402. name but with \key{.rkt} replaced with \key{.s}.
  17403. \paragraph{\code{read-program}}
  17404. takes a file path and parses that file (it must be a Racket program)
  17405. into an abstract syntax tree.
  17406. \paragraph{\code{parse-program}}
  17407. takes an S-expression representation of an abstract syntax tree and converts it into
  17408. the struct-based representation.
  17409. \paragraph{\code{assert}}
  17410. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  17411. and displays the message \key{msg} if the Boolean \key{bool} is false.
  17412. \paragraph{\code{lookup}}
  17413. % remove discussion of lookup? -Jeremy
  17414. takes a key and an alist, and returns the first value that is
  17415. associated with the given key, if there is one. If not, an error is
  17416. triggered. The alist may contain both immutable pairs (built with
  17417. \key{cons}) and mutable pairs (built with \key{mcons}).
  17418. %The \key{map2} function ...
  17419. \fi %\racketEd
  17420. \section{x86 Instruction Set Quick-Reference}
  17421. \label{sec:x86-quick-reference}
  17422. \index{subject}{x86}
  17423. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  17424. do. We write $A \to B$ to mean that the value of $A$ is written into
  17425. location $B$. Address offsets are given in bytes. The instruction
  17426. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  17427. registers (such as \code{\%rax}), or memory references (such as
  17428. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  17429. reference per instruction. Other operands must be immediates or
  17430. registers.
  17431. \begin{table}[tbp]
  17432. \centering
  17433. \begin{tabular}{l|l}
  17434. \textbf{Instruction} & \textbf{Operation} \\ \hline
  17435. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  17436. \texttt{negq} $A$ & $- A \to A$ \\
  17437. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  17438. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  17439. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  17440. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  17441. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  17442. \texttt{retq} & Pops the return address and jumps to it \\
  17443. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  17444. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  17445. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  17446. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  17447. be an immediate) \\
  17448. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  17449. matches the condition code of the instruction, otherwise go to the
  17450. next instructions. The condition codes are \key{e} for ``equal'',
  17451. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  17452. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  17453. \texttt{jl} $L$ & \\
  17454. \texttt{jle} $L$ & \\
  17455. \texttt{jg} $L$ & \\
  17456. \texttt{jge} $L$ & \\
  17457. \texttt{jmp} $L$ & Jump to label $L$ \\
  17458. \texttt{movq} $A$, $B$ & $A \to B$ \\
  17459. \texttt{movzbq} $A$, $B$ &
  17460. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  17461. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  17462. and the extra bytes of $B$ are set to zero.} \\
  17463. & \\
  17464. & \\
  17465. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  17466. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  17467. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  17468. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  17469. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  17470. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  17471. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  17472. description of the condition codes. $A$ must be a single byte register
  17473. (e.g., \texttt{al} or \texttt{cl}).} \\
  17474. \texttt{setl} $A$ & \\
  17475. \texttt{setle} $A$ & \\
  17476. \texttt{setg} $A$ & \\
  17477. \texttt{setge} $A$ &
  17478. \end{tabular}
  17479. \vspace{5pt}
  17480. \caption{Quick-reference for the x86 instructions used in this book.}
  17481. \label{tab:x86-instr}
  17482. \end{table}
  17483. \if\edition\racketEd
  17484. \cleardoublepage
  17485. \section{Concrete Syntax for Intermediate Languages}
  17486. The concrete syntax of \LangAny{} is defined in
  17487. Figure~\ref{fig:Rany-concrete-syntax}.
  17488. \begin{figure}[tp]
  17489. \centering
  17490. \fbox{
  17491. \begin{minipage}{0.97\textwidth}\small
  17492. \[
  17493. \begin{array}{lcl}
  17494. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  17495. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  17496. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \key{Any} \\
  17497. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17498. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  17499. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  17500. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  17501. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  17502. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  17503. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  17504. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  17505. \MID \LP\key{void?}\;\Exp\RP \\
  17506. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  17507. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  17508. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  17509. \end{array}
  17510. \]
  17511. \end{minipage}
  17512. }
  17513. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  17514. (Figure~\ref{fig:Rlam-syntax}).}
  17515. \label{fig:Rany-concrete-syntax}
  17516. \end{figure}
  17517. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  17518. defined in Figures~\ref{fig:c0-concrete-syntax},
  17519. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  17520. and \ref{fig:c3-concrete-syntax}, respectively.
  17521. \begin{figure}[tbp]
  17522. \fbox{
  17523. \begin{minipage}{0.96\textwidth}
  17524. \small
  17525. \[
  17526. \begin{array}{lcl}
  17527. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  17528. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  17529. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  17530. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  17531. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  17532. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  17533. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  17534. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  17535. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  17536. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  17537. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  17538. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  17539. \end{array}
  17540. \]
  17541. \end{minipage}
  17542. }
  17543. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  17544. \label{fig:c2-concrete-syntax}
  17545. \end{figure}
  17546. \begin{figure}[tp]
  17547. \fbox{
  17548. \begin{minipage}{0.96\textwidth}
  17549. \small
  17550. \[
  17551. \begin{array}{lcl}
  17552. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  17553. \\
  17554. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  17555. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  17556. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  17557. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  17558. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  17559. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  17560. &\MID& \LP\key{fun-ref}~\itm{label}\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  17561. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  17562. \MID \LP\key{collect} \,\itm{int}\RP }\\
  17563. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  17564. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  17565. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  17566. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  17567. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  17568. \LangCFunM{} & ::= & \Def\ldots
  17569. \end{array}
  17570. \]
  17571. \end{minipage}
  17572. }
  17573. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  17574. \label{fig:c3-concrete-syntax}
  17575. \end{figure}
  17576. \fi % racketEd
  17577. \backmatter
  17578. \addtocontents{toc}{\vspace{11pt}}
  17579. %% \addtocontents{toc}{\vspace{11pt}}
  17580. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  17581. \nocite{*}\let\bibname\refname
  17582. \addcontentsline{toc}{fmbm}{\refname}
  17583. \printbibliography
  17584. \printindex{authors}{Author Index}
  17585. \printindex{subject}{Subject Index}
  17586. \end{document}
  17587. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  17588. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  17589. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  17590. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  17591. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  17592. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  17593. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  17594. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  17595. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  17596. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  17597. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  17598. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  17599. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  17600. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  17601. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  17602. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  17603. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  17604. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  17605. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS
  17606. % LocalWords: morekeywords fullflexible