ir.cpp 422 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252
  1. struct irProcedure;
  2. struct irBlock;
  3. struct irValue;
  4. struct irDebugInfo;
  5. struct irModule {
  6. CheckerInfo * info;
  7. gbArena tmp_arena;
  8. // gbAllocator allocator;
  9. gbAllocator tmp_allocator;
  10. bool generate_debug_info;
  11. u64 state_flags;
  12. // String source_filename;
  13. // String layout;
  14. // String triple;
  15. PtrSet<Entity *> min_dep_set;
  16. Map<irValue *> values; // Key: Entity *
  17. StringMap<irValue *> members;
  18. Map<String> entity_names; // Key: Entity * of the typename
  19. Map<irDebugInfo *> debug_info; // Key: Unique pointer
  20. Map<irValue *> anonymous_proc_lits; // Key: Ast *
  21. Map<irValue *> equal_procs; // Key: Type *
  22. Map<irValue *> hasher_procs; // Key: Type *
  23. irDebugInfo * debug_compile_unit;
  24. Array<irDebugInfo *> debug_location_stack;
  25. i32 global_string_index;
  26. i32 global_array_index; // For ConstantSlice
  27. i32 global_generated_index;
  28. // NOTE(bill): To prevent strings from being copied a lot
  29. // Mainly used for file names
  30. StringMap<irValue *> const_strings;
  31. StringMap<irValue *> const_string_byte_slices;
  32. Map<irValue *> constant_value_to_global; // Key: irValue *
  33. Entity * entry_point_entity;
  34. Array<irProcedure *> procs; // NOTE(bill): All procedures with bodies
  35. Array<irValue *> procs_to_generate; // NOTE(bill): Procedures to generate
  36. Array<String> foreign_library_paths; // Only the ones that were used
  37. };
  38. // NOTE(bill): For more info, see https://en.wikipedia.org/wiki/Dominator_(graph_theory)
  39. struct irDomNode {
  40. irBlock * idom; // Parent (Immediate Dominator)
  41. Array<irBlock *> children;
  42. i32 pre, post; // Ordering in tree
  43. };
  44. struct irBlock {
  45. i32 index;
  46. String label;
  47. irProcedure *proc;
  48. Ast * node; // Can be nullptr
  49. Scope * scope;
  50. isize scope_index;
  51. irDomNode dom;
  52. i32 gaps;
  53. Array<irValue *> instrs;
  54. Array<irValue *> locals;
  55. Array<irBlock *> preds;
  56. Array<irBlock *> succs;
  57. };
  58. struct irTargetList {
  59. irTargetList *prev;
  60. bool is_block;
  61. irBlock * break_;
  62. irBlock * continue_;
  63. irBlock * fallthrough_;
  64. };
  65. enum irDeferExitKind {
  66. irDeferExit_Default,
  67. irDeferExit_Return,
  68. irDeferExit_Branch,
  69. };
  70. enum irDeferKind {
  71. irDefer_Node,
  72. irDefer_Instr,
  73. irDefer_Proc,
  74. };
  75. struct irDefer {
  76. irDeferKind kind;
  77. isize scope_index;
  78. isize context_stack_count;
  79. irBlock * block;
  80. union {
  81. Ast *stmt;
  82. // NOTE(bill): 'instr' will be copied every time to create a new one
  83. irValue *instr;
  84. struct {
  85. irValue *deferred;
  86. Array<irValue *> result_as_args;
  87. } proc;
  88. };
  89. };
  90. struct irBranchBlocks {
  91. Ast *label;
  92. irBlock *break_;
  93. irBlock *continue_;
  94. };
  95. struct irContextData {
  96. irValue *value;
  97. isize scope_index;
  98. };
  99. struct irProcedure {
  100. irProcedure * parent;
  101. Array<irProcedure *> children;
  102. Entity * entity;
  103. irModule * module;
  104. String name;
  105. Type * type;
  106. Ast * type_expr;
  107. Ast * body;
  108. u64 tags;
  109. ProcInlining inlining;
  110. bool is_foreign;
  111. bool is_export;
  112. bool is_entry_point;
  113. bool is_startup;
  114. irDebugInfo * debug_scope;
  115. irValue * return_ptr;
  116. Array<irValue *> params;
  117. Array<irDefer> defer_stmts;
  118. Array<irBlock *> blocks;
  119. i32 scope_index;
  120. irBlock * decl_block;
  121. irBlock * entry_block;
  122. irBlock * curr_block;
  123. irTargetList * target_list;
  124. Array<irValue *> referrers;
  125. Ast *curr_stmt;
  126. Array<irContextData> context_stack;
  127. i32 parameter_count;
  128. irValue *return_ptr_hint_value;
  129. Ast * return_ptr_hint_ast;
  130. bool return_ptr_hint_used;
  131. bool ignore_dead_instr;
  132. Array<irBranchBlocks> branch_blocks;
  133. i32 local_count;
  134. i32 instr_count;
  135. i32 block_count;
  136. };
  137. gb_global Arena global_ir_arena = {};
  138. gbAllocator ir_allocator(void) {
  139. Arena *arena = &global_ir_arena;
  140. return arena_allocator(arena);
  141. }
  142. #define IR_STARTUP_TYPE_INFO_PROC_NAME "__$startup_type_info"
  143. #define IR_STARTUP_RUNTIME_PROC_NAME "__$startup_runtime"
  144. #define IR_TYPE_INFO_DATA_NAME "__$type_info_data"
  145. #define IR_TYPE_INFO_TYPES_NAME "__$type_info_types_data"
  146. #define IR_TYPE_INFO_NAMES_NAME "__$type_info_names_data"
  147. #define IR_TYPE_INFO_OFFSETS_NAME "__$type_info_offsets_data"
  148. #define IR_TYPE_INFO_USINGS_NAME "__$type_info_usings_data"
  149. #define IR_TYPE_INFO_TAGS_NAME "__$type_info_tags_data"
  150. #define IR_INSTR_KINDS \
  151. IR_INSTR_KIND(Comment, struct { String text; }) \
  152. IR_INSTR_KIND(Local, struct { \
  153. Entity * entity; \
  154. Type * type; \
  155. bool zero_initialized; \
  156. Array<irValue *> referrers; \
  157. i64 alignment; \
  158. }) \
  159. IR_INSTR_KIND(ZeroInit, struct { irValue *address; }) \
  160. IR_INSTR_KIND(Store, struct { irValue *address, *value; bool is_volatile; }) \
  161. IR_INSTR_KIND(Load, struct { Type *type; irValue *address; i64 custom_align; }) \
  162. IR_INSTR_KIND(InlineCode, struct { BuiltinProcId id; Array<irValue *> operands; Type *type; }) \
  163. IR_INSTR_KIND(AtomicFence, struct { BuiltinProcId id; }) \
  164. IR_INSTR_KIND(AtomicStore, struct { \
  165. irValue *address, *value; \
  166. BuiltinProcId id; \
  167. }) \
  168. IR_INSTR_KIND(AtomicLoad, struct { \
  169. Type *type; irValue *address; \
  170. BuiltinProcId id; \
  171. }) \
  172. IR_INSTR_KIND(AtomicRmw, struct { \
  173. Type *type; irValue *address; \
  174. irValue *value; \
  175. BuiltinProcId id; \
  176. }) \
  177. IR_INSTR_KIND(AtomicCxchg, struct { \
  178. Type *type; irValue *address; \
  179. irValue *old_value; irValue *new_value; \
  180. BuiltinProcId id; \
  181. }) \
  182. IR_INSTR_KIND(PtrOffset, struct { \
  183. irValue *address; \
  184. irValue *offset; \
  185. }) \
  186. IR_INSTR_KIND(ArrayElementPtr, struct { \
  187. irValue *address; \
  188. Type * result_type; \
  189. irValue *elem_index; \
  190. }) \
  191. IR_INSTR_KIND(StructElementPtr, struct { \
  192. irValue *address; \
  193. Type * result_type; \
  194. i32 elem_index; \
  195. }) \
  196. IR_INSTR_KIND(StructExtractValue, struct { \
  197. irValue *address; \
  198. Type * result_type; \
  199. i32 index; \
  200. }) \
  201. IR_INSTR_KIND(UnionTagPtr, struct { \
  202. irValue *address; \
  203. Type *type; /* ^int */ \
  204. }) \
  205. IR_INSTR_KIND(UnionTagValue, struct { \
  206. irValue *address; \
  207. Type *type; /* int */ \
  208. }) \
  209. IR_INSTR_KIND(Conv, struct { \
  210. irConvKind kind; \
  211. irValue *value; \
  212. Type *from, *to; \
  213. }) \
  214. IR_INSTR_KIND(Jump, struct { irBlock *block; }) \
  215. IR_INSTR_KIND(If, struct { \
  216. irValue *cond; \
  217. irBlock *true_block; \
  218. irBlock *false_block; \
  219. }) \
  220. IR_INSTR_KIND(Return, struct { irValue *value; }) \
  221. IR_INSTR_KIND(Select, struct { \
  222. irValue *cond; \
  223. irValue *true_value; \
  224. irValue *false_value; \
  225. }) \
  226. IR_INSTR_KIND(Phi, struct { Array<irValue *> edges; Type *type; })\
  227. IR_INSTR_KIND(Unreachable, i32) \
  228. IR_INSTR_KIND(UnaryOp, struct { \
  229. Type * type; \
  230. TokenKind op; \
  231. irValue * expr; \
  232. }) \
  233. IR_INSTR_KIND(BinaryOp, struct { \
  234. Type * type; \
  235. TokenKind op; \
  236. irValue * left, *right; \
  237. }) \
  238. IR_INSTR_KIND(Call, struct { \
  239. Type * type; /* return type */ \
  240. irValue * value; \
  241. irValue * return_ptr; \
  242. Array<irValue *> args; \
  243. irValue * context_ptr; \
  244. ProcInlining inlining; \
  245. }) \
  246. IR_INSTR_KIND(StartupRuntime, i32) \
  247. IR_INSTR_KIND(DebugDeclare, struct { \
  248. Ast * expr; \
  249. Entity * entity; \
  250. bool is_addr; \
  251. irValue * value; \
  252. }) \
  253. // IR_INSTR_KIND(BoundsCheck, struct { \
  254. // TokenPos pos; \
  255. // irValue *index; \
  256. // irValue *len; \
  257. // }) \
  258. // IR_INSTR_KIND(SliceBoundsCheck, struct { \
  259. // TokenPos pos; \
  260. // irValue *low; \
  261. // irValue *high; \
  262. // irValue *max; \
  263. // bool is_substring; \
  264. // }) \
  265. #define IR_CONV_KINDS \
  266. IR_CONV_KIND(trunc) \
  267. IR_CONV_KIND(zext) \
  268. IR_CONV_KIND(sext) \
  269. IR_CONV_KIND(fptrunc) \
  270. IR_CONV_KIND(fpext) \
  271. IR_CONV_KIND(fptoui) \
  272. IR_CONV_KIND(fptosi) \
  273. IR_CONV_KIND(uitofp) \
  274. IR_CONV_KIND(sitofp) \
  275. IR_CONV_KIND(ptrtoint) \
  276. IR_CONV_KIND(inttoptr) \
  277. IR_CONV_KIND(bitcast) \
  278. IR_CONV_KIND(byteswap)
  279. /*
  280. Odin specifc conversion
  281. byteswap - swap bytes for endian change
  282. */
  283. enum irInstrKind {
  284. irInstr_Invalid,
  285. #define IR_INSTR_KIND(x, ...) GB_JOIN2(irInstr_, x),
  286. IR_INSTR_KINDS
  287. #undef IR_INSTR_KIND
  288. };
  289. String const ir_instr_strings[] = {
  290. {cast(u8 *)"Invalid", gb_size_of("Invalid")-1},
  291. #define IR_INSTR_KIND(x, ...) {cast(u8 *)#x, gb_size_of(#x)-1},
  292. IR_INSTR_KINDS
  293. #undef IR_INSTR_KIND
  294. };
  295. enum irConvKind {
  296. irConv_Invalid,
  297. #define IR_CONV_KIND(x) GB_JOIN2(irConv_, x),
  298. IR_CONV_KINDS
  299. #undef IR_CONV_KIND
  300. };
  301. String const ir_conv_strings[] = {
  302. {cast(u8 *)"Invalid", gb_size_of("Invalid")-1},
  303. #define IR_CONV_KIND(x) {cast(u8 *)#x, gb_size_of(#x)-1},
  304. IR_CONV_KINDS
  305. #undef IR_CONV_KIND
  306. };
  307. #define IR_INSTR_KIND(k, ...) typedef __VA_ARGS__ GB_JOIN2(irInstr, k);
  308. IR_INSTR_KINDS
  309. #undef IR_INSTR_KIND
  310. struct irInstr {
  311. irInstrKind kind;
  312. irBlock *block;
  313. Type *type;
  314. union {
  315. #define IR_INSTR_KIND(k, ...) GB_JOIN2(irInstr, k) k;
  316. IR_INSTR_KINDS
  317. #undef IR_INSTR_KIND
  318. };
  319. };
  320. enum irValueKind {
  321. irValue_Invalid,
  322. irValue_Constant,
  323. irValue_ConstantSlice,
  324. irValue_Nil,
  325. irValue_Undef,
  326. irValue_TypeName,
  327. irValue_Global,
  328. irValue_Param,
  329. irValue_SourceCodeLocation,
  330. irValue_Proc,
  331. irValue_Block,
  332. irValue_Instr,
  333. irValue_Count,
  334. };
  335. struct irValueConstant {
  336. Type * type;
  337. ExactValue value;
  338. };
  339. struct irValueConstantSlice {
  340. Type * type;
  341. irValue *backing_array;
  342. i64 count;
  343. };
  344. struct irValueNil {
  345. Type *type;
  346. };
  347. struct irValueUndef {
  348. Type *type;
  349. };
  350. struct irValueTypeName {
  351. Type * type;
  352. String name;
  353. };
  354. struct irValueGlobal {
  355. String name;
  356. Entity * entity;
  357. Type * type;
  358. irValue * value;
  359. Array<irValue *> referrers;
  360. bool is_constant;
  361. bool is_export;
  362. bool is_private;
  363. bool is_internal;
  364. String thread_local_model;
  365. bool is_foreign;
  366. bool is_unnamed_addr;
  367. };
  368. enum irParamPasskind {
  369. irParamPass_Value, // Pass by value
  370. irParamPass_Pointer, // Pass as a pointer rather than by value
  371. irParamPass_Integer, // Pass as an integer of the same size
  372. irParamPass_ConstRef, // Pass as a pointer but the value is immutable
  373. irParamPass_BitCast, // Pass by value and bit cast to the correct type
  374. irParamPass_Tuple, // Pass across multiple parameters (System V AMD64, up to 2)
  375. };
  376. struct irValueParam {
  377. irParamPasskind kind;
  378. irProcedure * parent;
  379. Entity * entity;
  380. Type * type;
  381. Type * original_type;
  382. i32 index;
  383. Array<irValue *> referrers;
  384. };
  385. struct irValueSourceCodeLocation {
  386. irValue *file;
  387. irValue *line;
  388. irValue *column;
  389. irValue *procedure;
  390. };
  391. struct irValue {
  392. irValueKind kind;
  393. i32 index;
  394. bool index_set;
  395. irDebugInfo * loc;
  396. isize uses;
  397. union {
  398. irValueConstant Constant;
  399. irValueConstantSlice ConstantSlice;
  400. irValueNil Nil;
  401. irValueUndef Undef;
  402. irValueTypeName TypeName;
  403. irValueGlobal Global;
  404. irValueParam Param;
  405. irProcedure Proc;
  406. irBlock Block;
  407. irInstr Instr;
  408. irValueSourceCodeLocation SourceCodeLocation;
  409. };
  410. };
  411. gb_global irValue *v_zero = nullptr;
  412. gb_global irValue *v_one = nullptr;
  413. gb_global irValue *v_zero32 = nullptr;
  414. gb_global irValue *v_one32 = nullptr;
  415. gb_global irValue *v_two32 = nullptr;
  416. gb_global irValue *v_false = nullptr;
  417. gb_global irValue *v_true = nullptr;
  418. gb_global irValue *v_raw_nil = nullptr;
  419. enum irAddrKind {
  420. irAddr_Default,
  421. irAddr_Map,
  422. irAddr_BitField,
  423. irAddr_Context,
  424. irAddr_SoaVariable,
  425. irAddr_RelativePointer,
  426. irAddr_RelativeSlice,
  427. };
  428. struct irAddr {
  429. irAddrKind kind;
  430. irValue * addr;
  431. union {
  432. struct {
  433. irValue *map_key;
  434. Type * map_type;
  435. Type * map_result;
  436. };
  437. struct {
  438. i32 bit_field_value_index;
  439. };
  440. struct {
  441. Selection sel;
  442. } ctx;
  443. struct {
  444. irValue *index;
  445. Ast *index_expr;
  446. } soa;
  447. struct {
  448. bool deref;
  449. } relative;
  450. };
  451. };
  452. Type *ir_type(irValue *value);
  453. irValue *ir_gen_anonymous_proc_lit(irModule *m, String prefix_name, Ast *expr, irProcedure *proc = nullptr);
  454. void ir_begin_procedure_body(irProcedure *proc);
  455. void ir_end_procedure_body(irProcedure *proc);
  456. irValue *ir_get_equal_proc_for_type(irModule *m, Type *type);
  457. irValue *ir_get_hasher_proc_for_type(irModule *m, Type *type);
  458. irAddr ir_addr(irValue *addr) {
  459. irAddr v = {irAddr_Default, addr};
  460. if (addr != nullptr && is_type_relative_pointer(type_deref(ir_type(addr)))) {
  461. GB_ASSERT(is_type_pointer(ir_type(addr)));
  462. v.kind = irAddr_RelativePointer;
  463. } else if (addr != nullptr && is_type_relative_slice(type_deref(ir_type(addr)))) {
  464. GB_ASSERT(is_type_pointer(ir_type(addr)));
  465. v.kind = irAddr_RelativeSlice;
  466. }
  467. return v;
  468. }
  469. irAddr ir_addr_map(irValue *addr, irValue *map_key, Type *map_type, Type *map_result) {
  470. irAddr v = {irAddr_Map, addr};
  471. v.map_key = map_key;
  472. v.map_type = map_type;
  473. v.map_result = map_result;
  474. return v;
  475. }
  476. irAddr ir_addr_context(irValue *addr, Selection sel = empty_selection) {
  477. irAddr v = {irAddr_Context, addr};
  478. v.ctx.sel = sel;
  479. return v;
  480. }
  481. irAddr ir_addr_bit_field(irValue *addr, i32 bit_field_value_index) {
  482. irAddr v = {irAddr_BitField, addr};
  483. v.bit_field_value_index = bit_field_value_index;
  484. return v;
  485. }
  486. irAddr ir_addr_soa_variable(irValue *addr, irValue *index, Ast *index_expr) {
  487. irAddr v = {irAddr_SoaVariable, addr};
  488. v.soa.index = index;
  489. v.soa.index_expr = index_expr;
  490. return v;
  491. }
  492. enum irDebugEncoding {
  493. irDebugBasicEncoding_Invalid = 0,
  494. irDebugBasicEncoding_address = 1,
  495. irDebugBasicEncoding_boolean = 2,
  496. irDebugBasicEncoding_float = 3,
  497. irDebugBasicEncoding_signed = 4,
  498. irDebugBasicEncoding_signed_char = 5,
  499. irDebugBasicEncoding_unsigned = 6,
  500. irDebugBasicEncoding_unsigned_char = 7,
  501. // TODO(lachsinc): Should the following be renamed from basic -> tag to mirror their DW_TAG_*
  502. // counterparts? Perhaps separate out if they truly have different meaning.
  503. irDebugBasicEncoding_member = 13,
  504. irDebugBasicEncoding_pointer_type = 15,
  505. irDebugBasicEncoding_typedef = 22,
  506. irDebugBasicEncoding_array_type = 1,
  507. irDebugBasicEncoding_enumeration_type = 4,
  508. irDebugBasicEncoding_structure_type = 19,
  509. irDebugBasicEncoding_union_type = 23,
  510. };
  511. enum irDebugInfoFlags {
  512. irDebugInfoFlag_Bitfield = (1 << 19),
  513. };
  514. enum irDebugInfoKind {
  515. irDebugInfo_Invalid,
  516. irDebugInfo_CompileUnit,
  517. irDebugInfo_File,
  518. irDebugInfo_Proc,
  519. irDebugInfo_ProcType,
  520. irDebugInfo_Location,
  521. irDebugInfo_LexicalBlock,
  522. irDebugInfo_AllProcs,
  523. irDebugInfo_BasicType, // primitive types
  524. irDebugInfo_DerivedType, // pointer, distinct etc.
  525. irDebugInfo_CompositeType, // array, struct, enum, union etc.
  526. irDebugInfo_Enumerator, // For irDebugInfo_CompositeType if enum
  527. irDebugInfo_GlobalVariableExpression, // used to describe if global is const or not
  528. irDebugInfo_GlobalVariable,
  529. irDebugInfo_LocalVariable,
  530. irDebugInfo_DebugInfoArray, // array of irDebugInfo *'s
  531. irDebugInfo_Count,
  532. };
  533. struct irDebugInfo {
  534. irDebugInfoKind kind;
  535. i32 id;
  536. union {
  537. struct {
  538. AstFile * file;
  539. String producer;
  540. irDebugInfo *enums; // DebugInfoArray
  541. irDebugInfo *globals; // DebugInfoArray
  542. } CompileUnit;
  543. struct {
  544. AstFile *file;
  545. String filename;
  546. String directory;
  547. } File;
  548. struct {
  549. Entity * entity;
  550. String name;
  551. irDebugInfo * file;
  552. TokenPos pos;
  553. irDebugInfo * type;
  554. // TODO(lachsinc): variables / retainedNodes ?
  555. } Proc;
  556. struct {
  557. irDebugInfo * types; // !{return, return, param, param, param.. etc.}
  558. } ProcType;
  559. struct {
  560. TokenPos pos;
  561. irDebugInfo *scope;
  562. } Location;
  563. struct {
  564. TokenPos pos;
  565. irDebugInfo *file;
  566. irDebugInfo *scope;
  567. } LexicalBlock;
  568. struct {
  569. Type * type;
  570. String name;
  571. i32 size;
  572. i32 align;
  573. irDebugEncoding encoding;
  574. } BasicType;
  575. struct {
  576. Type * type;
  577. irDebugEncoding tag;
  578. irDebugInfo * base_type;
  579. String name;
  580. irDebugInfo * scope;
  581. irDebugInfo * file;
  582. TokenPos pos;
  583. i32 size;
  584. i32 align;
  585. i32 offset;
  586. irDebugInfoFlags flags; // Used only for DIFlagBitField.
  587. } DerivedType;
  588. struct {
  589. irDebugEncoding tag;
  590. String name;
  591. irDebugInfo * scope;
  592. irDebugInfo * file;
  593. TokenPos pos;
  594. irDebugInfo * base_type; // optional, used for enumeration_type.
  595. i32 size;
  596. i32 align;
  597. irDebugInfo * elements;
  598. i32 array_count; // for DISubrange
  599. } CompositeType;
  600. struct {
  601. String name;
  602. i64 value;
  603. } Enumerator;
  604. struct {
  605. irDebugInfo *var;
  606. } GlobalVariableExpression;
  607. struct {
  608. String name;
  609. String linkage_name;
  610. irDebugInfo *scope;
  611. irDebugInfo *file;
  612. TokenPos pos;
  613. irDebugInfo *type;
  614. irValue *variable;
  615. } GlobalVariable;
  616. struct {
  617. String name;
  618. irDebugInfo *scope;
  619. irDebugInfo *file;
  620. TokenPos pos;
  621. i32 arg; // Non-zero if proc parameter
  622. irDebugInfo *type;
  623. } LocalVariable;
  624. struct {
  625. Array<irDebugInfo *> elements; // TODO(lachsinc): Leak?
  626. } DebugInfoArray;
  627. };
  628. };
  629. static irDebugInfo IR_DEBUG_INFO_EMPTY = {};
  630. struct irGen {
  631. irModule module;
  632. gbFile output_file;
  633. bool opt_called;
  634. String output_base;
  635. String output_name;
  636. bool print_chkstk;
  637. };
  638. gb_inline bool ir_min_dep_entity(irModule *m, Entity *e) {
  639. return ptr_set_exists(&m->min_dep_set, e);
  640. }
  641. Type *ir_instr_type(irInstr *instr) {
  642. switch (instr->kind) {
  643. case irInstr_InlineCode:
  644. return instr->InlineCode.type;
  645. case irInstr_Local:
  646. return instr->Local.type;
  647. case irInstr_Load:
  648. return instr->Load.type;
  649. case irInstr_AtomicLoad:
  650. return instr->AtomicLoad.type;
  651. case irInstr_AtomicRmw:
  652. return instr->AtomicRmw.type;
  653. case irInstr_AtomicCxchg:
  654. return instr->AtomicCxchg.type;
  655. case irInstr_StructElementPtr:
  656. return instr->StructElementPtr.result_type;
  657. case irInstr_ArrayElementPtr:
  658. return instr->ArrayElementPtr.result_type;
  659. case irInstr_PtrOffset:
  660. return ir_type(instr->PtrOffset.address);
  661. case irInstr_Phi:
  662. return instr->Phi.type;
  663. case irInstr_StructExtractValue:
  664. return instr->StructExtractValue.result_type;
  665. case irInstr_UnionTagPtr:
  666. return instr->UnionTagPtr.type;
  667. case irInstr_UnionTagValue:
  668. return instr->UnionTagValue.type;
  669. case irInstr_UnaryOp:
  670. return instr->UnaryOp.type;
  671. case irInstr_BinaryOp:
  672. return instr->BinaryOp.type;
  673. case irInstr_Conv:
  674. return instr->Conv.to;
  675. case irInstr_Select:
  676. return ir_type(instr->Select.true_value);
  677. case irInstr_Call: {
  678. Type *pt = base_type(instr->Call.type);
  679. if (pt != nullptr) {
  680. if (pt->kind == Type_Tuple && pt->Tuple.variables.count == 1) {
  681. return pt->Tuple.variables[0]->type;
  682. }
  683. return pt;
  684. }
  685. return nullptr;
  686. }
  687. }
  688. return nullptr;
  689. }
  690. Type *ir_type(irValue *value) {
  691. if (value == nullptr) {
  692. return nullptr;
  693. }
  694. switch (value->kind) {
  695. case irValue_Constant:
  696. return value->Constant.type;
  697. case irValue_ConstantSlice:
  698. return value->ConstantSlice.type;
  699. case irValue_Nil:
  700. return value->Nil.type;
  701. case irValue_Undef:
  702. return value->Undef.type;
  703. case irValue_TypeName:
  704. return value->TypeName.type;
  705. case irValue_Global:
  706. return value->Global.type;
  707. case irValue_Param:
  708. return value->Param.type;
  709. case irValue_SourceCodeLocation:
  710. return t_source_code_location;
  711. case irValue_Proc:
  712. return value->Proc.type;
  713. case irValue_Instr:
  714. return ir_instr_type(&value->Instr);
  715. }
  716. return nullptr;
  717. }
  718. irInstr *ir_get_last_instr(irBlock *block) {
  719. if (block != nullptr) {
  720. isize len = block->instrs.count;
  721. if (len > 0) {
  722. irValue *v = block->instrs[len-1];
  723. GB_ASSERT(v->kind == irValue_Instr);
  724. return &v->Instr;
  725. }
  726. }
  727. return nullptr;
  728. }
  729. bool ir_is_instr_terminating(irInstr *i) {
  730. if (i != nullptr) {
  731. switch (i->kind) {
  732. case irInstr_Return:
  733. case irInstr_Unreachable:
  734. return true;
  735. }
  736. }
  737. return false;
  738. }
  739. void ir_add_edge(irBlock *from, irBlock *to) {
  740. GB_ASSERT(from->instrs.count > 0);
  741. if (!ir_is_instr_terminating(ir_get_last_instr(from))) {
  742. array_add(&from->succs, to);
  743. array_add(&to->preds, from);
  744. }
  745. }
  746. void ir_set_instr_block(irValue *instr, irBlock *block) {
  747. if (instr->kind == irValue_Instr) {
  748. instr->Instr.block = block;
  749. }
  750. }
  751. Array<irValue *> *ir_value_referrers(irValue *v) {
  752. switch (v->kind) {
  753. case irValue_Global:
  754. return &v->Global.referrers;
  755. case irValue_Param:
  756. return &v->Param.referrers;
  757. case irValue_Proc: {
  758. if (v->Proc.parent != nullptr) {
  759. return &v->Proc.referrers;
  760. }
  761. return nullptr;
  762. }
  763. case irValue_Instr: {
  764. irInstr *i = &v->Instr;
  765. switch (i->kind) {
  766. case irInstr_Local:
  767. return &i->Local.referrers;
  768. }
  769. break;
  770. }
  771. }
  772. return nullptr;
  773. }
  774. ////////////////////////////////////////////////////////////////
  775. //
  776. // @Make
  777. //
  778. ////////////////////////////////////////////////////////////////
  779. void ir_module_add_value (irModule *m, Entity *e, irValue *v);
  780. void ir_emit_zero_init (irProcedure *p, irValue *address, Ast *expr);
  781. irValue *ir_emit_comment (irProcedure *p, String text);
  782. irValue *ir_emit_store (irProcedure *p, irValue *address, irValue *value, bool is_volatile=false);
  783. irValue *ir_emit_load (irProcedure *p, irValue *address, i64 custom_align=0);
  784. void ir_emit_jump (irProcedure *proc, irBlock *block);
  785. irValue *ir_emit_conv (irProcedure *proc, irValue *value, Type *t);
  786. irValue *ir_type_info (irProcedure *proc, Type *type);
  787. irValue *ir_typeid (irModule *m, Type *type);
  788. irValue *ir_build_expr (irProcedure *proc, Ast *expr);
  789. void ir_build_stmt (irProcedure *proc, Ast *node);
  790. irValue *ir_build_cond (irProcedure *proc, Ast *cond, irBlock *true_block, irBlock *false_block);
  791. void ir_build_defer_stmt (irProcedure *proc, irDefer d);
  792. irAddr ir_build_addr (irProcedure *proc, Ast *expr);
  793. void ir_build_proc (irValue *value, irProcedure *parent);
  794. void ir_gen_global_type_name(irModule *m, Entity *e, String name);
  795. irValue *ir_get_type_info_ptr (irProcedure *proc, Type *type);
  796. void ir_value_set_debug_location(irProcedure *proc, irValue *v);
  797. void ir_push_debug_location (irModule *m, Ast *node, irDebugInfo *scope, Entity *e=nullptr);
  798. void ir_pop_debug_location (irModule *m);
  799. irDebugInfo *ir_add_debug_info_local(irProcedure *proc, Entity *e, i32 arg_id);
  800. irDebugInfo *ir_add_debug_info_file(irModule *module, AstFile *file);
  801. irDebugInfo *ir_add_debug_info_proc(irProcedure *proc);
  802. void ir_emit_increment(irProcedure *proc, irValue *addr);
  803. irValue *ir_emit_array_ep(irProcedure *proc, irValue *s, irValue *index);
  804. irValue *ir_emit_array_epi(irProcedure *proc, irValue *s, i32 index);
  805. irValue *ir_emit_struct_ev(irProcedure *proc, irValue *s, i32 index);
  806. irValue *ir_emit_bitcast(irProcedure *proc, irValue *data, Type *type);
  807. irValue *ir_emit_byte_swap(irProcedure *proc, irValue *value, Type *t);
  808. irValue *ir_find_or_add_entity_string(irModule *m, String str);
  809. irValue *ir_find_or_add_entity_string_byte_slice(irModule *m, String str);
  810. irValue *ir_slice_elem(irProcedure *proc, irValue *slice);
  811. irValue *ir_slice_len(irProcedure *proc, irValue *slice);
  812. void ir_fill_slice(irProcedure *proc, irValue *slice_ptr, irValue *data, irValue *len);
  813. irValue *ir_alloc_value(irValueKind kind) {
  814. irValue *v = gb_alloc_item(ir_allocator(), irValue);
  815. v->kind = kind;
  816. return v;
  817. }
  818. irValue *ir_alloc_instr(irProcedure *proc, irInstrKind kind) {
  819. irValue *v = ir_alloc_value(irValue_Instr);
  820. v->Instr.kind = kind;
  821. proc->instr_count++;
  822. return v;
  823. }
  824. irDebugInfo *ir_alloc_debug_info(irDebugInfoKind kind) {
  825. irDebugInfo *di = gb_alloc_item(ir_allocator(), irDebugInfo);
  826. di->kind = kind;
  827. return di;
  828. }
  829. irValue *ir_value_type_name(String name, Type *type) {
  830. irValue *v = ir_alloc_value(irValue_TypeName);
  831. v->TypeName.name = name;
  832. v->TypeName.type = type;
  833. return v;
  834. }
  835. irValue *ir_value_global(Entity *e, irValue *value) {
  836. irValue *v = ir_alloc_value(irValue_Global);
  837. v->Global.entity = e;
  838. v->Global.type = alloc_type_pointer(e->type);
  839. v->Global.value = value;
  840. array_init(&v->Global.referrers, ir_allocator()); // TODO(bill): Replace heap allocator here
  841. if (value) value->uses += 1;
  842. return v;
  843. }
  844. irValue *ir_value_param(irProcedure *parent, Entity *e, Type *abi_type, i32 index) {
  845. irValue *v = ir_alloc_value(irValue_Param);
  846. v->Param.kind = irParamPass_Value;
  847. v->Param.parent = parent;
  848. if (e != nullptr) {
  849. v->Param.entity = e;
  850. v->Param.original_type = e->type;
  851. }
  852. v->Param.type = abi_type;
  853. v->Param.index = index;
  854. if (e != nullptr && abi_type != e->type) {
  855. if (is_type_pointer(abi_type)) {
  856. GB_ASSERT(e->kind == Entity_Variable);
  857. Type *av = core_type(type_deref(abi_type));
  858. if (are_types_identical(av, core_type(e->type))) {
  859. v->Param.kind = irParamPass_Pointer;
  860. if (e->flags&EntityFlag_Value) {
  861. v->Param.kind = irParamPass_ConstRef;
  862. }
  863. } else {
  864. v->Param.kind = irParamPass_BitCast;
  865. }
  866. } else if (is_type_integer(abi_type)) {
  867. v->Param.kind = irParamPass_Integer;
  868. } else if (abi_type == t_llvm_bool) {
  869. v->Param.kind = irParamPass_Value;
  870. } else if (is_type_boolean(abi_type)) {
  871. v->Param.kind = irParamPass_Integer;
  872. } else if (is_type_simd_vector(abi_type)) {
  873. v->Param.kind = irParamPass_BitCast;
  874. } else if (is_type_float(abi_type)) {
  875. v->Param.kind = irParamPass_BitCast;
  876. } else if (is_type_tuple(abi_type)) {
  877. v->Param.kind = irParamPass_Tuple;
  878. } else {
  879. GB_PANIC("Invalid abi type pass kind: %s", type_to_string(abi_type));
  880. }
  881. }
  882. array_init(&v->Param.referrers, heap_allocator()); // TODO(bill): Replace heap allocator here
  883. return v;
  884. }
  885. irValue *ir_value_nil(Type *type) {
  886. irValue *v = ir_alloc_value(irValue_Nil);
  887. v->Nil.type = type;
  888. return v;
  889. }
  890. irValue *ir_value_undef(Type *type) {
  891. irValue *v = ir_alloc_value(irValue_Undef);
  892. v->Undef.type = type;
  893. return v;
  894. }
  895. String ir_get_global_name(irModule *m, irValue *v) {
  896. if (v->kind != irValue_Global) {
  897. return str_lit("");
  898. }
  899. irValueGlobal *g = &v->Global;
  900. Entity *e = g->entity;
  901. String name = e->token.string;
  902. String *found = map_get(&m->entity_names, hash_entity(e));
  903. if (found != nullptr) {
  904. name = *found;
  905. } else {
  906. GB_ASSERT(name.len > 0);
  907. }
  908. return name;
  909. }
  910. void ir_add_entity_name(irModule *m, Entity *e, String name) {
  911. GB_ASSERT(name.len > 0);
  912. if (e != nullptr && e->kind == Entity_TypeName) {
  913. e->TypeName.ir_mangled_name = name;
  914. }
  915. map_set(&m->entity_names, hash_entity(e), name);
  916. }
  917. irValue *ir_instr_local(irProcedure *p, Entity *e, bool zero_initialized) {
  918. irValue *v = ir_alloc_instr(p, irInstr_Local);
  919. irInstr *i = &v->Instr;
  920. i->Local.entity = e;
  921. i->Local.type = alloc_type_pointer(e->type);
  922. i->Local.zero_initialized = zero_initialized;
  923. // i->Local.alignment = type_align_of(p->module->allocator, e->type);
  924. // TODO(bill): determine the correct alignment
  925. i->Local.alignment = gb_max(16, type_align_of(e->type));
  926. array_init(&i->Local.referrers, heap_allocator()); // TODO(bill): Replace heap allocator here
  927. ir_module_add_value(p->module, e, v);
  928. return v;
  929. }
  930. irValue *ir_instr_zero_init(irProcedure *p, irValue *address) {
  931. irValue *v = ir_alloc_instr(p, irInstr_ZeroInit);
  932. irInstr *i = &v->Instr;
  933. i->ZeroInit.address = address;
  934. if (address) address->uses += 1;
  935. return v;
  936. }
  937. irValue *ir_instr_store(irProcedure *p, irValue *address, irValue *value, bool is_volatile) {
  938. irValue *v = ir_alloc_instr(p, irInstr_Store);
  939. irInstr *i = &v->Instr;
  940. i->Store.address = address;
  941. i->Store.value = value;
  942. i->Store.is_volatile = is_volatile;
  943. if (address) address->uses += 1;
  944. if (value) value->uses += 1;
  945. return v;
  946. }
  947. irValue *ir_instr_load(irProcedure *p, irValue *address) {
  948. irValue *v = ir_alloc_instr(p, irInstr_Load);
  949. irInstr *i = &v->Instr;
  950. i->Load.address = address;
  951. i->Load.type = type_deref(ir_type(address));
  952. if (address) address->uses += 1;
  953. return v;
  954. }
  955. irValue *ir_instr_inline_code(irProcedure *p, BuiltinProcId id, Array<irValue *> const &operands, Type *type) {
  956. irValue *v = ir_alloc_instr(p, irInstr_InlineCode);
  957. irInstr *i = &v->Instr;
  958. i->InlineCode.id = id;
  959. i->InlineCode.operands = operands;
  960. i->InlineCode.type = type;
  961. return v;
  962. }
  963. irValue *ir_instr_atomic_fence(irProcedure *p, BuiltinProcId id) {
  964. irValue *v = ir_alloc_instr(p, irInstr_AtomicFence);
  965. irInstr *i = &v->Instr;
  966. i->AtomicFence.id = id;
  967. return v;
  968. }
  969. irValue *ir_instr_atomic_store(irProcedure *p, irValue *address, irValue *value, BuiltinProcId id) {
  970. irValue *v = ir_alloc_instr(p, irInstr_AtomicStore);
  971. irInstr *i = &v->Instr;
  972. i->AtomicStore.address = address;
  973. i->AtomicStore.value = value;
  974. i->AtomicStore.id = id;
  975. if (address) address->uses += 1;
  976. if (value) value->uses += 1;
  977. return v;
  978. }
  979. irValue *ir_instr_atomic_load(irProcedure *p, irValue *address, BuiltinProcId id) {
  980. irValue *v = ir_alloc_instr(p, irInstr_AtomicLoad);
  981. irInstr *i = &v->Instr;
  982. i->AtomicLoad.address = address;
  983. i->AtomicLoad.type = type_deref(ir_type(address));
  984. i->AtomicLoad.id = id;
  985. if (address) address->uses += 1;
  986. return v;
  987. }
  988. irValue *ir_instr_atomic_rmw(irProcedure *p, irValue *address, irValue *value, BuiltinProcId id) {
  989. irValue *v = ir_alloc_instr(p, irInstr_AtomicRmw);
  990. irInstr *i = &v->Instr;
  991. i->AtomicRmw.type = type_deref(ir_type(address));
  992. i->AtomicRmw.address = address;
  993. i->AtomicRmw.value = value;
  994. i->AtomicRmw.id = id;
  995. if (address) address->uses += 1;
  996. if (value) value->uses += 1;
  997. return v;
  998. }
  999. irValue *ir_instr_atomic_cxchg(irProcedure *p, Type *type, irValue *address, irValue *old_value, irValue *new_value, BuiltinProcId id) {
  1000. irValue *v = ir_alloc_instr(p, irInstr_AtomicCxchg);
  1001. irInstr *i = &v->Instr;
  1002. if (type->kind == Type_Tuple) {
  1003. GB_ASSERT(type->Tuple.variables.count == 2);
  1004. Type *elem = type->Tuple.variables[0]->type;
  1005. // LEAK TODO(bill): LLVM returns {T, i1} whilst Odin does {T, bool}, fix this mapping hack
  1006. gbAllocator a = permanent_allocator();
  1007. Type *llvm_type = alloc_type_tuple();
  1008. array_init(&llvm_type->Tuple.variables, a, 0, 2);
  1009. array_add (&llvm_type->Tuple.variables, alloc_entity_field(nullptr, blank_token, elem, false, 0));
  1010. array_add (&llvm_type->Tuple.variables, alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1));
  1011. type = llvm_type;
  1012. }
  1013. i->AtomicCxchg.type = type;
  1014. i->AtomicCxchg.address = address;
  1015. i->AtomicCxchg.old_value = old_value;
  1016. i->AtomicCxchg.new_value = new_value;
  1017. i->AtomicCxchg.id = id;
  1018. if (address) address->uses += 1;
  1019. if (old_value) old_value->uses += 1;
  1020. if (new_value) new_value->uses += 1;
  1021. return v;
  1022. }
  1023. irValue *ir_instr_array_element_ptr(irProcedure *p, irValue *address, irValue *elem_index) {
  1024. irValue *v = ir_alloc_instr(p, irInstr_ArrayElementPtr);
  1025. irInstr *i = &v->Instr;
  1026. Type *t = ir_type(address);
  1027. GB_ASSERT_MSG(is_type_pointer(t), "%s", type_to_string(t));
  1028. t = base_type(type_deref(t));
  1029. GB_ASSERT(is_type_array(t) || is_type_enumerated_array(t));
  1030. Type *result_type = nullptr;
  1031. if (t->kind == Type_Array) {
  1032. result_type = alloc_type_pointer(t->Array.elem);
  1033. } else if (t->kind == Type_EnumeratedArray) {
  1034. result_type = alloc_type_pointer(t->EnumeratedArray.elem);
  1035. }
  1036. i->ArrayElementPtr.address = address;
  1037. i->ArrayElementPtr.elem_index = elem_index;
  1038. i->ArrayElementPtr.result_type = result_type;
  1039. if (address) address->uses += 1;
  1040. if (elem_index) elem_index->uses += 1;
  1041. GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
  1042. "%s", type_to_string(ir_type(address)));
  1043. return v;
  1044. }
  1045. irValue *ir_instr_struct_element_ptr(irProcedure *p, irValue *address, i32 elem_index, Type *result_type) {
  1046. irValue *v = ir_alloc_instr(p, irInstr_StructElementPtr);
  1047. irInstr *i = &v->Instr;
  1048. i->StructElementPtr.address = address;
  1049. i->StructElementPtr.elem_index = elem_index;
  1050. i->StructElementPtr.result_type = result_type;
  1051. if (address) address->uses += 1;
  1052. GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
  1053. "%s", type_to_string(ir_type(address)));
  1054. return v;
  1055. }
  1056. irValue *ir_instr_ptr_offset(irProcedure *p, irValue *address, irValue *offset) {
  1057. irValue *v = ir_alloc_instr(p, irInstr_PtrOffset);
  1058. irInstr *i = &v->Instr;
  1059. i->PtrOffset.address = address;
  1060. i->PtrOffset.offset = offset;
  1061. if (address) address->uses += 1;
  1062. if (offset) offset->uses += 1;
  1063. GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
  1064. "%s", type_to_string(ir_type(address)));
  1065. GB_ASSERT_MSG(is_type_integer(ir_type(offset)),
  1066. "%s", type_to_string(ir_type(address)));
  1067. return v;
  1068. }
  1069. irValue *ir_instr_struct_extract_value(irProcedure *p, irValue *address, i32 index, Type *result_type) {
  1070. irValue *v = ir_alloc_instr(p, irInstr_StructExtractValue);
  1071. irInstr *i = &v->Instr;
  1072. i->StructExtractValue.address = address;
  1073. i->StructExtractValue.index = index;
  1074. i->StructExtractValue.result_type = result_type;
  1075. if (address) address->uses += 1;
  1076. return v;
  1077. }
  1078. irValue *ir_instr_union_tag_ptr(irProcedure *p, irValue *address) {
  1079. irValue *v = ir_alloc_instr(p, irInstr_UnionTagPtr);
  1080. irInstr *i = &v->Instr;
  1081. i->UnionTagPtr.address = address;
  1082. if (address) address->uses += 1;
  1083. // i->UnionTagPtr.type = alloc_type_pointer(t_type_info_ptr);
  1084. Type *u = type_deref(ir_type(address));
  1085. if (is_type_union_maybe_pointer(u)) {
  1086. GB_PANIC("union #maybe UnionTagPtr");
  1087. }
  1088. i->UnionTagPtr.type = alloc_type_pointer(union_tag_type(u));
  1089. return v;
  1090. }
  1091. irValue *ir_instr_union_tag_value(irProcedure *p, irValue *address) {
  1092. irValue *v = ir_alloc_instr(p, irInstr_UnionTagValue);
  1093. irInstr *i = &v->Instr;
  1094. i->UnionTagValue.address = address;
  1095. if (address) address->uses += 1;
  1096. Type *u = type_deref(ir_type(address));
  1097. if (is_type_union_maybe_pointer(u)) {
  1098. GB_PANIC("union #maybe UnionTagValue");
  1099. }
  1100. i->UnionTagPtr.type = union_tag_type(u);
  1101. return v;
  1102. }
  1103. irValue *ir_instr_unary_op(irProcedure *p, TokenKind op, irValue *expr, Type *type) {
  1104. irValue *v = ir_alloc_instr(p, irInstr_UnaryOp);
  1105. irInstr *i = &v->Instr;
  1106. i->UnaryOp.op = op;
  1107. i->UnaryOp.expr = expr;
  1108. i->UnaryOp.type = type;
  1109. if (expr) expr->uses += 1;
  1110. return v;
  1111. }
  1112. irValue *ir_instr_binary_op(irProcedure *p, TokenKind op, irValue *left, irValue *right, Type *type) {
  1113. irValue *v = ir_alloc_instr(p, irInstr_BinaryOp);
  1114. irInstr *i = &v->Instr;
  1115. i->BinaryOp.op = op;
  1116. i->BinaryOp.left = left;
  1117. i->BinaryOp.right = right;
  1118. i->BinaryOp.type = type;
  1119. if (left) left->uses += 1;
  1120. if (right) right->uses += 1;
  1121. return v;
  1122. }
  1123. irValue *ir_instr_jump(irProcedure *p, irBlock *block) {
  1124. irValue *v = ir_alloc_instr(p, irInstr_Jump);
  1125. irInstr *i = &v->Instr;
  1126. i->Jump.block = block;
  1127. return v;
  1128. }
  1129. irValue *ir_instr_if(irProcedure *p, irValue *cond, irBlock *true_block, irBlock *false_block) {
  1130. irValue *v = ir_alloc_instr(p, irInstr_If);
  1131. irInstr *i = &v->Instr;
  1132. i->If.cond = ir_emit_conv(p, cond, t_llvm_bool);
  1133. i->If.true_block = true_block;
  1134. i->If.false_block = false_block;
  1135. return v;
  1136. }
  1137. irValue *ir_instr_phi(irProcedure *p, Array<irValue *> edges, Type *type) {
  1138. GB_ASSERT(is_type_typed(type));
  1139. irValue *v = ir_alloc_instr(p, irInstr_Phi);
  1140. irInstr *i = &v->Instr;
  1141. i->Phi.edges = edges;
  1142. i->Phi.type = type;
  1143. for_array(j, edges) {
  1144. if (edges[j]) edges[j]->uses += 1;
  1145. }
  1146. return v;
  1147. }
  1148. irValue *ir_instr_unreachable(irProcedure *p) {
  1149. irValue *v = ir_alloc_instr(p, irInstr_Unreachable);
  1150. return v;
  1151. }
  1152. irValue *ir_instr_return(irProcedure *p, irValue *value) {
  1153. irValue *v = ir_alloc_instr(p, irInstr_Return);
  1154. v->Instr.Return.value = value;
  1155. if (value) value->uses += 1;
  1156. return v;
  1157. }
  1158. irValue *ir_instr_select(irProcedure *p, irValue *cond, irValue *t, irValue *f) {
  1159. irValue *v = ir_alloc_instr(p, irInstr_Select);
  1160. v->Instr.Select.cond = cond;
  1161. v->Instr.Select.true_value = t;
  1162. v->Instr.Select.false_value = f;
  1163. if (cond) cond->uses += 1;
  1164. if (t) t->uses += 1;
  1165. if (f) f->uses += 1;
  1166. return v;
  1167. }
  1168. irValue *ir_instr_call(irProcedure *p, irValue *value, irValue *return_ptr, Array<irValue *> args, Type *result_type, irValue *context_ptr, ProcInlining inlining) {
  1169. irValue *v = ir_alloc_instr(p, irInstr_Call);
  1170. v->Instr.Call.value = value;
  1171. v->Instr.Call.return_ptr = return_ptr;
  1172. v->Instr.Call.args = args;
  1173. v->Instr.Call.type = result_type;
  1174. v->Instr.Call.context_ptr = context_ptr;
  1175. v->Instr.Call.inlining = inlining;
  1176. if (value) value->uses += 1;
  1177. if (return_ptr) return_ptr->uses += 1;
  1178. for_array(i, args) {
  1179. if (args[i]) args[i]->uses += 1;
  1180. }
  1181. if (context_ptr) context_ptr->uses += 1;
  1182. return v;
  1183. }
  1184. irValue *ir_instr_conv(irProcedure *p, irConvKind kind, irValue *value, Type *from, Type *to) {
  1185. irValue *v = ir_alloc_instr(p, irInstr_Conv);
  1186. v->Instr.Conv.kind = kind;
  1187. v->Instr.Conv.value = value;
  1188. v->Instr.Conv.from = from;
  1189. v->Instr.Conv.to = to;
  1190. if (value) value->uses += 1;
  1191. return v;
  1192. }
  1193. irValue *ir_instr_comment(irProcedure *p, String text) {
  1194. irValue *v = ir_alloc_instr(p, irInstr_Comment);
  1195. v->Instr.Comment.text = text;
  1196. return v;
  1197. }
  1198. irValue *ir_instr_debug_declare(irProcedure *p, Ast *expr, Entity *entity, bool is_addr, irValue *value) {
  1199. irValue *v = ir_alloc_instr(p, irInstr_DebugDeclare);
  1200. v->Instr.DebugDeclare.expr = expr;
  1201. v->Instr.DebugDeclare.entity = entity;
  1202. v->Instr.DebugDeclare.is_addr = is_addr;
  1203. v->Instr.DebugDeclare.value = value;
  1204. if (value) value->uses += 1;
  1205. return v;
  1206. }
  1207. irValue *ir_value_constant(Type *type, ExactValue value) {
  1208. irValue *v = ir_alloc_value(irValue_Constant);
  1209. v->Constant.type = type;
  1210. v->Constant.value = value;
  1211. return v;
  1212. }
  1213. irValue *ir_value_constant_slice(Type *type, irValue *backing_array, i64 count) {
  1214. irValue *v = ir_alloc_value(irValue_ConstantSlice);
  1215. v->ConstantSlice.type = type;
  1216. v->ConstantSlice.backing_array = backing_array;
  1217. v->ConstantSlice.count = count;
  1218. if (backing_array) backing_array->uses += 1;
  1219. return v;
  1220. }
  1221. irValue *ir_emit(irProcedure *proc, irValue *instr) {
  1222. GB_ASSERT(instr->kind == irValue_Instr);
  1223. irModule *m = proc->module;
  1224. irBlock *b = proc->curr_block;
  1225. instr->Instr.block = b;
  1226. if (b != nullptr) {
  1227. irInstr *i = ir_get_last_instr(b);
  1228. if (!ir_is_instr_terminating(i)) {
  1229. array_add(&b->instrs, instr);
  1230. }
  1231. } else if (instr->Instr.kind != irInstr_Unreachable) {
  1232. GB_PANIC("ir_emit: Instruction missing parent block");
  1233. }
  1234. if (m->generate_debug_info) {
  1235. ir_value_set_debug_location(proc, instr);
  1236. }
  1237. return instr;
  1238. }
  1239. irValue *ir_de_emit(irProcedure *proc, irValue *instr) {
  1240. GB_ASSERT(instr->kind == irValue_Instr);
  1241. irModule *m = proc->module;
  1242. irBlock *b = proc->curr_block;
  1243. GB_ASSERT(b != nullptr);
  1244. irInstr *i = ir_get_last_instr(b);
  1245. GB_ASSERT(i == &instr->Instr);
  1246. array_pop(&b->instrs);
  1247. return instr;
  1248. }
  1249. irValue *ir_const_int(i64 i) {
  1250. return ir_value_constant(t_int, exact_value_i64(i));
  1251. }
  1252. irValue *ir_const_uintptr(u64 i) {
  1253. return ir_value_constant(t_uintptr, exact_value_i64(i));
  1254. }
  1255. irValue *ir_const_u8(u32 i) {
  1256. return ir_value_constant(t_u8, exact_value_i64(i));
  1257. }
  1258. irValue *ir_const_i32(i32 i) {
  1259. return ir_value_constant(t_i32, exact_value_i64(i));
  1260. }
  1261. irValue *ir_const_u32(u32 i) {
  1262. return ir_value_constant(t_u32, exact_value_i64(i));
  1263. }
  1264. irValue *ir_const_i64(i64 i) {
  1265. return ir_value_constant(t_i64, exact_value_i64(i));
  1266. }
  1267. irValue *ir_const_u64(u64 i) {
  1268. return ir_value_constant(t_u64, exact_value_i64(i));
  1269. }
  1270. irValue *ir_const_f32(f32 f) {
  1271. return ir_value_constant(t_f32, exact_value_float(f));
  1272. }
  1273. irValue *ir_const_f64(f64 f) {
  1274. return ir_value_constant(t_f64, exact_value_float(f));
  1275. }
  1276. irValue *ir_const_bool(bool b) {
  1277. return ir_value_constant(t_bool, exact_value_bool(b != 0));
  1278. }
  1279. irValue *ir_const_string(irModule *m, String s) {
  1280. return ir_find_or_add_entity_string(m, s);
  1281. // return ir_value_constant(t_string, exact_value_string(s));
  1282. }
  1283. irValue *ir_value_procedure(irModule *m, Entity *entity, Type *type, Ast *type_expr, Ast *body, String name) {
  1284. irValue *v = ir_alloc_value(irValue_Proc);
  1285. v->Proc.module = m;
  1286. v->Proc.entity = entity;
  1287. v->Proc.type = type;
  1288. v->Proc.type_expr = type_expr;
  1289. v->Proc.body = body;
  1290. v->Proc.name = name;
  1291. array_init(&v->Proc.referrers, heap_allocator());
  1292. Type *t = base_type(type);
  1293. GB_ASSERT(is_type_proc(t));
  1294. array_init(&v->Proc.params, heap_allocator(), 0, t->Proc.param_count);
  1295. return v;
  1296. }
  1297. irValue *ir_generate_array(irModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  1298. gbAllocator a = ir_allocator();
  1299. Token token = {Token_Ident};
  1300. isize name_len = prefix.len + 1 + 20;
  1301. auto suffix_id = cast(unsigned long long)id;
  1302. char *text = gb_alloc_array(a, char, name_len+1);
  1303. gb_snprintf(text, name_len,
  1304. "%.*s-%llu", LIT(prefix), suffix_id);
  1305. text[name_len] = 0;
  1306. String s = make_string_c(text);
  1307. Entity *e = alloc_entity_variable(nullptr, make_token_ident(s), alloc_type_array(elem_type, count));
  1308. irValue *value = ir_value_global(e, nullptr);
  1309. value->Global.is_private = true;
  1310. ir_module_add_value(m, e, value);
  1311. string_map_set(&m->members, s, value);
  1312. return value;
  1313. }
  1314. irBlock *ir_new_block(irProcedure *proc, Ast *node, char const *label) {
  1315. Scope *scope = nullptr;
  1316. if (node != nullptr) {
  1317. scope = scope_of_node(node);
  1318. GB_ASSERT_MSG(scope != nullptr, "Block scope not found for %.*s", LIT(ast_strings[node->kind]));
  1319. }
  1320. irValue *v = ir_alloc_value(irValue_Block);
  1321. v->Block.label = make_string_c(label);
  1322. v->Block.node = node;
  1323. v->Block.scope = scope;
  1324. v->Block.proc = proc;
  1325. // TODO(bill): Is this correct or even needed?
  1326. v->Block.scope_index = proc->scope_index;
  1327. array_init(&v->Block.instrs, heap_allocator());
  1328. array_init(&v->Block.locals, heap_allocator());
  1329. array_init(&v->Block.preds, heap_allocator());
  1330. array_init(&v->Block.succs, heap_allocator());
  1331. irBlock *block = &v->Block;
  1332. return block;
  1333. }
  1334. void ir_add_block_to_proc(irProcedure *proc, irBlock *b) {
  1335. for_array(i, proc->blocks) {
  1336. if (proc->blocks[i] == b) {
  1337. return;
  1338. }
  1339. }
  1340. array_add(&proc->blocks, b);
  1341. b->index = proc->block_count++;
  1342. }
  1343. void ir_start_block(irProcedure *proc, irBlock *block) {
  1344. proc->curr_block = block;
  1345. if (block != nullptr) {
  1346. ir_add_block_to_proc(proc, block);
  1347. }
  1348. }
  1349. irValue *ir_emit_transmute(irProcedure *proc, irValue *value, Type *t);
  1350. irValue *ir_address_from_load_or_generate_local(irProcedure *proc, irValue *val);
  1351. irValue *ir_emit_struct_ep(irProcedure *proc, irValue *s, i32 index);
  1352. irDefer ir_add_defer_node(irProcedure *proc, isize scope_index, Ast *stmt) {
  1353. irDefer d = {irDefer_Node};
  1354. d.scope_index = scope_index;
  1355. d.context_stack_count = proc->context_stack.count;
  1356. d.block = proc->curr_block;
  1357. d.stmt = stmt;
  1358. array_add(&proc->defer_stmts, d);
  1359. return d;
  1360. }
  1361. irDefer ir_add_defer_instr(irProcedure *proc, isize scope_index, irValue *instr) {
  1362. irDefer d = {irDefer_Instr};
  1363. d.scope_index = proc->scope_index;
  1364. d.block = proc->curr_block;
  1365. d.instr = instr; // NOTE(bill): It will make a copy everytime it is called
  1366. array_add(&proc->defer_stmts, d);
  1367. return d;
  1368. }
  1369. irDefer ir_add_defer_proc(irProcedure *proc, isize scope_index, irValue *deferred, Array<irValue *> const &result_as_args) {
  1370. irDefer d = {irDefer_Proc};
  1371. d.scope_index = proc->scope_index;
  1372. d.block = proc->curr_block;
  1373. d.proc.deferred = deferred;
  1374. d.proc.result_as_args = result_as_args;
  1375. array_add(&proc->defer_stmts, d);
  1376. return d;
  1377. }
  1378. irValue *ir_add_module_constant(irModule *m, Type *type, ExactValue value);
  1379. irValue *ir_check_compound_lit_constant(irModule *m, Ast *expr) {
  1380. expr = unparen_expr(expr);
  1381. if (expr == nullptr) {
  1382. return nullptr;
  1383. }
  1384. if (expr->kind == Ast_CompoundLit) {
  1385. ast_node(cl, CompoundLit, expr);
  1386. for_array(i, cl->elems) {
  1387. Ast *elem = cl->elems[i];
  1388. if (elem->kind == Ast_FieldValue) {
  1389. ast_node(fv, FieldValue, elem);
  1390. ir_check_compound_lit_constant(m, fv->value);
  1391. } else {
  1392. ir_check_compound_lit_constant(m, elem);
  1393. }
  1394. }
  1395. }
  1396. if (expr->kind == Ast_ProcLit) {
  1397. return ir_gen_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  1398. }
  1399. if (expr->kind == Ast_Ident || expr->kind == Ast_SelectorExpr) {
  1400. TypeAndValue tav = type_and_value_of_expr(expr);
  1401. if (tav.mode == Addressing_Constant) {
  1402. return ir_add_module_constant(m, tav.type, tav.value);
  1403. }
  1404. }
  1405. return nullptr;
  1406. }
  1407. irValue *ir_add_module_constant(irModule *m, Type *type, ExactValue value) {
  1408. gbAllocator a = ir_allocator();
  1409. if (is_type_slice(type)) {
  1410. if (value.kind == ExactValue_String) {
  1411. GB_ASSERT(is_type_u8_slice(type));
  1412. return ir_find_or_add_entity_string_byte_slice(m, value.value_string);
  1413. } else {
  1414. ast_node(cl, CompoundLit, value.value_compound);
  1415. isize count = cl->elems.count;
  1416. if (count == 0) {
  1417. return ir_value_nil(type);
  1418. }
  1419. count = gb_max(cl->max_count, count);
  1420. Type *elem = base_type(type)->Slice.elem;
  1421. Type *t = alloc_type_array(elem, count);
  1422. irValue *backing_array = ir_add_module_constant(m, t, value);
  1423. isize max_len = 7+8+1;
  1424. u8 *str = cast(u8 *)gb_alloc_array(a, u8, max_len);
  1425. isize len = gb_snprintf(cast(char *)str, max_len, "csba$%x", m->global_array_index);
  1426. m->global_array_index++;
  1427. String name = make_string(str, len-1);
  1428. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  1429. irValue *g = ir_value_global(e, backing_array);
  1430. ir_module_add_value(m, e, g);
  1431. string_map_set(&m->members, name, g);
  1432. return ir_value_constant_slice(type, g, count);
  1433. }
  1434. }
  1435. if (value.kind == ExactValue_Compound) {
  1436. // NOTE(bill): Removed for numerous reasons
  1437. irValue *lit = ir_check_compound_lit_constant(m, value.value_compound);
  1438. if (lit != nullptr) {
  1439. return lit;
  1440. }
  1441. }
  1442. return ir_value_constant(type, value);
  1443. }
  1444. irValue *ir_add_global_string_array(irModule *m, String string) {
  1445. irValue *global_constant_value = nullptr;
  1446. {
  1447. irValue **found = string_map_get(&m->const_string_byte_slices, string);
  1448. if (found != nullptr) {
  1449. global_constant_value = *found;
  1450. irValue **global_found = map_get(&m->constant_value_to_global, hash_pointer(global_constant_value));
  1451. if (global_found != nullptr) {
  1452. return *global_found;
  1453. }
  1454. }
  1455. }
  1456. if (global_constant_value == nullptr) {
  1457. global_constant_value = ir_find_or_add_entity_string_byte_slice(m, string);
  1458. }
  1459. Type *type = alloc_type_array(t_u8, string.len+1);
  1460. isize max_len = 6+8+1;
  1461. u8 *str = cast(u8 *)gb_alloc_array(ir_allocator(), u8, max_len);
  1462. isize len = gb_snprintf(cast(char *)str, max_len, "str$%x", m->global_string_index);
  1463. m->global_string_index++;
  1464. String name = make_string(str, len-1);
  1465. Token token = {Token_String};
  1466. token.string = name;
  1467. Entity *entity = alloc_entity_constant(nullptr, token, type, exact_value_string(string));
  1468. irValue *g = ir_value_global(entity, global_constant_value);
  1469. g->Global.is_private = true;
  1470. g->Global.is_unnamed_addr = true;
  1471. g->Global.is_constant = true;
  1472. map_set(&m->constant_value_to_global, hash_pointer(global_constant_value), g);
  1473. ir_module_add_value(m, entity, g);
  1474. string_map_set(&m->members, name, g);
  1475. return g;
  1476. }
  1477. void ir_add_foreign_library_path(irModule *m, Entity *e) {
  1478. if (e == nullptr) {
  1479. return;
  1480. }
  1481. GB_ASSERT(e->kind == Entity_LibraryName);
  1482. GB_ASSERT(e->flags & EntityFlag_Used);
  1483. for_array(i, e->LibraryName.paths) {
  1484. String library_path = e->LibraryName.paths[i];
  1485. if (library_path.len == 0) {
  1486. continue;
  1487. }
  1488. bool ok = true;
  1489. for_array(path_index, m->foreign_library_paths) {
  1490. String path = m->foreign_library_paths[path_index];
  1491. #if defined(GB_SYSTEM_WINDOWS)
  1492. if (str_eq_ignore_case(path, library_path)) {
  1493. #else
  1494. if (str_eq(path, library_path)) {
  1495. #endif
  1496. ok = false;
  1497. break;
  1498. }
  1499. }
  1500. if (ok) {
  1501. array_add(&m->foreign_library_paths, library_path);
  1502. }
  1503. }
  1504. }
  1505. void ir_push_context_onto_stack(irProcedure *proc, irValue *ctx) {
  1506. irContextData cd = {ctx, proc->scope_index};
  1507. array_add(&proc->context_stack, cd);
  1508. }
  1509. irValue *ir_add_local(irProcedure *proc, Entity *e, Ast *expr, bool zero_initialized, i32 param_index = 0) {
  1510. irBlock *b = proc->decl_block; // all variables must be in the first block
  1511. irValue *instr = ir_instr_local(proc, e, true);
  1512. instr->Instr.block = b;
  1513. array_add(&b->instrs, instr);
  1514. array_add(&b->locals, instr);
  1515. proc->local_count++;
  1516. if (zero_initialized) {
  1517. ir_emit_zero_init(proc, instr, expr);
  1518. }
  1519. set_procedure_abi_types(e->type);
  1520. // if (proc->module->generate_debug_info && expr != nullptr && proc->entity != nullptr) {
  1521. // if (proc->module->generate_debug_info && proc->entity != nullptr) {
  1522. if (proc->module->generate_debug_info) {
  1523. // GB_ASSERT_NOT_NULL(proc->debug_scope);
  1524. if (expr != nullptr) {
  1525. ir_emit(proc, ir_instr_debug_declare(proc, expr, e, true, instr));
  1526. }
  1527. if (e->scope != nullptr && proc->debug_scope != nullptr) {
  1528. irDebugInfo *di_local = ir_add_debug_info_local(proc, e, param_index);
  1529. }
  1530. }
  1531. return instr;
  1532. }
  1533. irValue *ir_add_local_for_identifier(irProcedure *proc, Ast *ident, bool zero_initialized) {
  1534. Entity *e = entity_of_node(ident);
  1535. if (e != nullptr) {
  1536. String name = e->token.string;
  1537. ir_emit_comment(proc, name);
  1538. if (e->kind == Entity_Variable &&
  1539. e->Variable.is_foreign) {
  1540. if (e->Variable.link_name.len != 0) {
  1541. name = e->Variable.link_name;
  1542. }
  1543. StringHashKey key = string_hash_string(name);
  1544. irValue **prev_value = string_map_get(&proc->module->members, key);
  1545. if (prev_value == nullptr) {
  1546. ir_add_foreign_library_path(proc->module, e->Variable.foreign_library);
  1547. // NOTE(bill): Don't do mutliple declarations in the IR
  1548. irValue *g = ir_value_global(e, nullptr);
  1549. g->Global.name = name;
  1550. g->Global.is_foreign = true;
  1551. ir_module_add_value(proc->module, e, g);
  1552. string_map_set(&proc->module->members, key, g);
  1553. return g;
  1554. } else {
  1555. return *prev_value;
  1556. }
  1557. }
  1558. return ir_add_local(proc, e, ident, zero_initialized);
  1559. }
  1560. return nullptr;
  1561. }
  1562. irValue *ir_add_local_generated(irProcedure *proc, Type *type, bool zero_initialized) {
  1563. GB_ASSERT(type != nullptr);
  1564. type = default_type(type);
  1565. Scope *scope = nullptr;
  1566. if (proc->curr_block) {
  1567. scope = proc->curr_block->scope;
  1568. }
  1569. Entity *e = alloc_entity_variable(scope, empty_token, type);
  1570. return ir_add_local(proc, e, nullptr, zero_initialized);
  1571. }
  1572. irValue *ir_add_global_generated(irModule *m, Type *type, irValue *value) {
  1573. GB_ASSERT(type != nullptr);
  1574. type = default_type(type);
  1575. isize max_len = 7+8+1;
  1576. u8 *str = cast(u8 *)gb_alloc_array(ir_allocator(), u8, max_len);
  1577. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  1578. m->global_generated_index++;
  1579. String name = make_string(str, len-1);
  1580. Scope *scope = nullptr;
  1581. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  1582. irValue *g = ir_value_global(e, value);
  1583. ir_module_add_value(m, e, g);
  1584. string_map_set(&m->members, name, g);
  1585. return g;
  1586. }
  1587. irValue *ir_add_param(irProcedure *proc, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  1588. irValue *v = ir_value_param(proc, e, abi_type, index);
  1589. array_add(&proc->params, v);
  1590. irValueParam *p = &v->Param;
  1591. irValue *res = nullptr;
  1592. ir_push_debug_location(proc->module, e ? e->identifier : nullptr, proc->debug_scope, e);
  1593. defer (ir_pop_debug_location(proc->module));
  1594. switch (p->kind) {
  1595. case irParamPass_Value: {
  1596. irValue *l = ir_add_local(proc, e, expr, false, index);
  1597. irValue *x = v;
  1598. if (abi_type == t_llvm_bool) {
  1599. x = ir_emit_conv(proc, x, t_bool);
  1600. }
  1601. ir_emit_store(proc, l, x);
  1602. return x;
  1603. }
  1604. case irParamPass_Pointer:
  1605. ir_module_add_value(proc->module, e, v);
  1606. return ir_emit_load(proc, v);
  1607. case irParamPass_Integer: {
  1608. irValue *l = ir_add_local(proc, e, expr, false, index);
  1609. irValue *iptr = ir_emit_conv(proc, l, alloc_type_pointer(p->type));
  1610. ir_emit_store(proc, iptr, v);
  1611. return ir_emit_load(proc, l);
  1612. }
  1613. case irParamPass_ConstRef:
  1614. ir_module_add_value(proc->module, e, v);
  1615. return ir_emit_load(proc, v);
  1616. case irParamPass_BitCast: {
  1617. irValue *l = ir_add_local(proc, e, expr, false, index);
  1618. irValue *x = ir_emit_transmute(proc, v, e->type);
  1619. ir_emit_store(proc, l, x);
  1620. return x;
  1621. }
  1622. case irParamPass_Tuple: {
  1623. irValue *l = ir_add_local(proc, e, expr, true, index);
  1624. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  1625. irValue *ptr = ir_emit_transmute(proc, l, alloc_type_pointer(st));
  1626. if (abi_type->Tuple.variables.count > 0) {
  1627. array_pop(&proc->params);
  1628. }
  1629. for_array(i, abi_type->Tuple.variables) {
  1630. Type *t = abi_type->Tuple.variables[i]->type;
  1631. irValue *elem = ir_value_param(proc, nullptr, t, index+cast(i32)i);
  1632. array_add(&proc->params, elem);
  1633. irValue *dst = ir_emit_struct_ep(proc, ptr, cast(i32)i);
  1634. ir_emit_store(proc, dst, elem);
  1635. }
  1636. return ir_emit_load(proc, l);
  1637. }
  1638. }
  1639. GB_PANIC("Unreachable");
  1640. return nullptr;
  1641. }
  1642. ////////////////////////////////////////////////////////////////
  1643. //
  1644. // @Debug
  1645. //
  1646. ////////////////////////////////////////////////////////////////
  1647. irDebugInfo *ir_add_debug_info_type(irModule *module, Type *type, Entity *e, irDebugInfo *scope, irDebugInfo *file);
  1648. irDebugInfo *ir_add_debug_info_array(irModule *module, isize count, isize capacity) {
  1649. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DebugInfoArray);
  1650. array_init(&di->DebugInfoArray.elements, ir_allocator(), count, capacity);
  1651. map_set(&module->debug_info, hash_pointer(di), di);
  1652. return di;
  1653. }
  1654. irDebugInfo *ir_add_debug_info_file(irModule *module, AstFile *file) {
  1655. // if (!proc->module->generate_debug_info) {
  1656. // return nullptr;
  1657. // }
  1658. irDebugInfo **existing = map_get(&module->debug_info, hash_ast_file(file));
  1659. if (existing != nullptr) {
  1660. GB_ASSERT((*existing)->kind == irDebugInfo_File);
  1661. return *existing;
  1662. }
  1663. GB_ASSERT(file != nullptr);
  1664. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_File);
  1665. di->File.file = file;
  1666. String filename = file->tokenizer.fullpath;
  1667. String directory = filename;
  1668. isize slash_index = 0;
  1669. for (isize i = filename.len-1; i >= 0; i--) {
  1670. if (filename[i] == '\\' ||
  1671. filename[i] == '/') {
  1672. break;
  1673. }
  1674. slash_index = i;
  1675. }
  1676. directory.len = slash_index-1;
  1677. filename.text = filename.text + slash_index;
  1678. filename.len -= slash_index;
  1679. di->File.filename = filename;
  1680. di->File.directory = directory;
  1681. map_set(&module->debug_info, hash_ast_file(file), di);
  1682. return di;
  1683. }
  1684. irDebugEncoding ir_debug_encoding_for_basic(BasicKind kind) {
  1685. switch (kind) {
  1686. case Basic_llvm_bool:
  1687. case Basic_bool:
  1688. case Basic_b8:
  1689. case Basic_b16:
  1690. case Basic_b32:
  1691. case Basic_b64:
  1692. return irDebugBasicEncoding_boolean;
  1693. case Basic_i8:
  1694. return irDebugBasicEncoding_signed_char;
  1695. case Basic_u8:
  1696. return irDebugBasicEncoding_unsigned_char;
  1697. case Basic_i16:
  1698. case Basic_i32:
  1699. case Basic_i64:
  1700. case Basic_i128:
  1701. case Basic_i16le:
  1702. case Basic_i32le:
  1703. case Basic_i64le:
  1704. case Basic_i128le:
  1705. case Basic_i16be:
  1706. case Basic_i32be:
  1707. case Basic_i64be:
  1708. case Basic_i128be:
  1709. case Basic_int:
  1710. case Basic_rune:
  1711. case Basic_typeid:
  1712. return irDebugBasicEncoding_signed;
  1713. case Basic_u16:
  1714. case Basic_u32:
  1715. case Basic_u64:
  1716. case Basic_u128:
  1717. case Basic_u16le:
  1718. case Basic_u32le:
  1719. case Basic_u64le:
  1720. case Basic_u128le:
  1721. case Basic_u16be:
  1722. case Basic_u32be:
  1723. case Basic_u64be:
  1724. case Basic_u128be:
  1725. case Basic_uint:
  1726. case Basic_uintptr:
  1727. return irDebugBasicEncoding_unsigned;
  1728. // case Basic_f16:
  1729. case Basic_f32:
  1730. case Basic_f64:
  1731. case Basic_f32le:
  1732. case Basic_f64le:
  1733. case Basic_f32be:
  1734. case Basic_f64be:
  1735. return irDebugBasicEncoding_float;
  1736. // case Basic_complex32:
  1737. case Basic_complex64:
  1738. case Basic_complex128:
  1739. case Basic_cstring:
  1740. case Basic_string:
  1741. case Basic_any:
  1742. case Basic_rawptr:
  1743. case Basic_quaternion128:
  1744. case Basic_quaternion256:
  1745. break; // not a "DIBasicType"
  1746. }
  1747. GB_PANIC("Unreachable %d", kind);
  1748. return irDebugBasicEncoding_Invalid;
  1749. }
  1750. i32 ir_debug_info_bits(i64 size) {
  1751. return 8*cast(i32)size;
  1752. }
  1753. i32 ir_debug_size_bits(Type *type) {
  1754. return ir_debug_info_bits(type_size_of(type));
  1755. }
  1756. i32 ir_debug_align_bits(Type *type) {
  1757. return ir_debug_info_bits(type_align_of(type));
  1758. }
  1759. irDebugInfo *ir_add_debug_info_field_internal(irModule *module, String name, Type *type, i32 offset_bits, Entity *e, irDebugInfo *scope) {
  1760. // NOTE(lachsinc): Caller is expected to insert the returned value into map themselves.
  1761. // "scope", if set, should be inserted into map prior to calling to ensure no cyclical dependency issues.
  1762. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  1763. // GB_ASSERT_MSG(name.len > 0, "%s", type_to_string(type));
  1764. di->DerivedType.name = name;
  1765. di->DerivedType.tag = irDebugBasicEncoding_member;
  1766. di->DerivedType.size = ir_debug_size_bits(type);
  1767. di->DerivedType.offset = offset_bits;
  1768. di->DerivedType.scope = scope;
  1769. // NOTE(lachsinc): It is "safe" to overwrite this base_type after a call to this function,
  1770. // if you need to set a specific type for this field.
  1771. di->DerivedType.base_type = ir_add_debug_info_type(module, type, e, scope, nullptr);
  1772. GB_ASSERT_NOT_NULL(di->DerivedType.base_type);
  1773. return di;
  1774. }
  1775. irDebugInfo *ir_add_debug_info_field(irModule *module, irDebugInfo *scope, Entity *e, Type *scope_type, i32 index, Type *type, irDebugInfo *file) {
  1776. // NOTE(lachsinc): This lookup will only work for struct fields!!
  1777. if (e) {
  1778. irDebugInfo **existing = map_get(&module->debug_info, hash_entity(e));
  1779. if (existing != nullptr) {
  1780. return *existing;
  1781. }
  1782. }
  1783. irDebugInfo *di = ir_add_debug_info_field_internal(module, make_string(nullptr, 0), type, 0, e, scope);
  1784. void *ptr_to_hash = nullptr;
  1785. if (scope_type) {
  1786. Type *scope_base = base_type(scope_type);
  1787. if (is_type_struct(scope_type) || is_type_tuple(scope_type)) {
  1788. if (is_type_struct(scope_type) && scope_base->Struct.are_offsets_set) {
  1789. di->DerivedType.offset = ir_debug_info_bits(scope_base->Struct.offsets[index]);
  1790. } else if (is_type_tuple(scope_type) && scope_base->Tuple.are_offsets_set) {
  1791. di->DerivedType.offset = ir_debug_info_bits(scope_base->Tuple.offsets[index]);
  1792. } else {
  1793. di->DerivedType.offset = ir_debug_info_bits(type_offset_of(scope_base, index));
  1794. }
  1795. if (e) {
  1796. ptr_to_hash = e;
  1797. di->DerivedType.name = e->token.string;
  1798. if (e->token.string.len == 0) {
  1799. // If no name available for field, use its field index as its name.
  1800. isize max_len = 8;
  1801. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  1802. isize len = gb_snprintf(cast(char *)str, 8, "%d", index);
  1803. di->DerivedType.name = make_string(str, len-1);
  1804. }
  1805. di->DerivedType.pos = e->token.pos;
  1806. } else {
  1807. GB_PANIC("Unreachable"); // struct field Entity's should be provided.
  1808. }
  1809. } else if (is_type_union(scope_base)) {
  1810. // TODO(lachsinc): Handle this in a more generic manner/pass in??...
  1811. // Token token = base_type(scope_base)->Union.node->UnionType.token;
  1812. // di->DerivedType.name = token.string;
  1813. // di->DerivedType.pos = token.pos;
  1814. if (is_type_named(type)) {
  1815. di->DerivedType.name = type->kind == Type_Named ? type->Named.name : type->Basic.name;
  1816. }
  1817. ptr_to_hash = di;
  1818. }
  1819. }
  1820. di->DerivedType.file = file;
  1821. GB_ASSERT_NOT_NULL(ptr_to_hash);
  1822. map_set(&module->debug_info, hash_pointer(ptr_to_hash), di);
  1823. return di;
  1824. }
  1825. irDebugInfo *ir_add_debug_info_enumerator(irModule *module, Entity *e) {
  1826. irDebugInfo **existing = map_get(&module->debug_info, hash_entity(e));
  1827. if (existing != nullptr) {
  1828. return *existing;
  1829. }
  1830. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_Enumerator);
  1831. di->Enumerator.name = e->token.string;
  1832. GB_ASSERT(e->kind == Entity_Constant);
  1833. GB_ASSERT(e->Constant.value.kind == ExactValue_Integer);
  1834. di->Enumerator.value = big_int_to_i64(&e->Constant.value.value_integer);
  1835. map_set(&module->debug_info, hash_entity(e), di);
  1836. return di;
  1837. }
  1838. irDebugInfo *ir_add_debug_info_type_dynamic_array(irModule *module, Type *type, Entity *e, irDebugInfo *scope, irDebugInfo *file) {
  1839. GB_ASSERT(type->kind == Type_DynamicArray);
  1840. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1841. di->CompositeType.name = str_lit("dynamic_array"); // TODO(lachsinc): [dynamic] .. type->DynamicArray.elem name
  1842. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1843. di->CompositeType.size = ir_debug_size_bits(t_rawptr) +
  1844. ir_debug_size_bits(t_int) +
  1845. ir_debug_size_bits(t_int) +
  1846. ir_debug_size_bits(t_allocator);
  1847. di->CompositeType.align = ir_debug_align_bits(t_rawptr);
  1848. map_set(&module->debug_info, hash_type(type), di);
  1849. // Data pointer type
  1850. // TODO(lachsinc): Perhaps lookup/alloc-a-fake Type_Pointer type and go via ir_add_debug_info_type() with it.
  1851. irDebugInfo *data_ptr_di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  1852. data_ptr_di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  1853. data_ptr_di->DerivedType.size = ir_debug_size_bits(t_rawptr);
  1854. map_set(&module->debug_info, hash_pointer(data_ptr_di), data_ptr_di);
  1855. data_ptr_di->DerivedType.base_type = ir_add_debug_info_type(module, type->DynamicArray.elem, e, scope, file);
  1856. irDebugInfo *data_di = ir_add_debug_info_field_internal(module, str_lit("data"), t_rawptr,
  1857. 0,
  1858. nullptr,
  1859. di);
  1860. data_di->DerivedType.base_type = data_ptr_di;
  1861. map_set(&module->debug_info, hash_pointer(data_di), data_di);
  1862. irDebugInfo *len_di = ir_add_debug_info_field_internal(module, str_lit("len"), t_int,
  1863. data_di->DerivedType.size,
  1864. nullptr,
  1865. di);
  1866. map_set(&module->debug_info, hash_pointer(len_di), len_di);
  1867. irDebugInfo *cap_di = ir_add_debug_info_field_internal(module, str_lit("cap"), t_int,
  1868. data_di->DerivedType.size +
  1869. len_di->DerivedType.size,
  1870. nullptr,
  1871. di);
  1872. map_set(&module->debug_info, hash_pointer(cap_di), cap_di);
  1873. irDebugInfo *alloc_di = ir_add_debug_info_field_internal(module, str_lit("allocator"), t_allocator,
  1874. data_di->DerivedType.size +
  1875. len_di->DerivedType.size +
  1876. cap_di->DerivedType.size,
  1877. nullptr,
  1878. di);
  1879. map_set(&module->debug_info, hash_pointer(alloc_di), alloc_di);
  1880. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 4);
  1881. array_add(&elements_di->DebugInfoArray.elements, data_di);
  1882. array_add(&elements_di->DebugInfoArray.elements, len_di);
  1883. array_add(&elements_di->DebugInfoArray.elements, cap_di);
  1884. array_add(&elements_di->DebugInfoArray.elements, alloc_di);
  1885. di->CompositeType.elements = elements_di;
  1886. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1887. return di;
  1888. }
  1889. irDebugInfo *ir_add_debug_info_type_bit_field(irModule *module, Type *type, Entity *e, irDebugInfo *scope) {
  1890. GB_ASSERT(type->kind == Type_BitField || (type->kind == Type_Named && type->Named.base->kind == Type_BitField));
  1891. Type *bf_type = base_type(type);
  1892. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1893. di->CompositeType.name = is_type_named(type) ? type->Named.name : str_lit("bit_field");
  1894. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1895. di->CompositeType.size = ir_debug_size_bits(bf_type);
  1896. map_set(&module->debug_info, hash_type(type), di);
  1897. GB_ASSERT(bf_type->BitField.fields.count == bf_type->BitField.offsets.count &&
  1898. bf_type->BitField.fields.count == bf_type->BitField.sizes.count);
  1899. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, bf_type->BitField.fields.count);
  1900. di->CompositeType.elements = elements_di;
  1901. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1902. for_array(field_index, bf_type->BitField.fields) {
  1903. Entity *field = bf_type->BitField.fields[field_index];
  1904. u32 offset = bf_type->BitField.offsets[field_index];
  1905. u32 size = bf_type->BitField.sizes[field_index];
  1906. String name = str_lit("field_todo");
  1907. if (field != nullptr && field->token.string.len > 0) {
  1908. name = field->token.string;
  1909. }
  1910. // TODO(lachsinc): t_i64 may not be safe to use for all bitfields?
  1911. irDebugInfo *field_di = ir_add_debug_info_field_internal(module, name, t_i64,
  1912. 0,
  1913. nullptr,
  1914. di);
  1915. // NOTE(lachsinc): Above calls BitFieldValues type_size_of() which returns size in bits,
  1916. // replace with its true bit value here..
  1917. field_di->DerivedType.size = size;
  1918. field_di->DerivedType.offset = offset; // Offset stored in bits already, no need to convert
  1919. field_di->DerivedType.flags = irDebugInfoFlag_Bitfield;
  1920. map_set(&module->debug_info, hash_pointer(field_di), field_di);
  1921. array_add(&elements_di->DebugInfoArray.elements, field_di);
  1922. }
  1923. return di;
  1924. }
  1925. irDebugInfo *ir_add_debug_info_type_bit_set(irModule *module, Type *type, Entity *e, irDebugInfo *scope) {
  1926. GB_ASSERT(type->kind == Type_BitSet || type->kind == Type_Named);
  1927. Type *base = base_type(type);
  1928. Type *named = nullptr;
  1929. if (type->kind == Type_Named) {
  1930. named = type;
  1931. }
  1932. Type *elem_type = nullptr;
  1933. if (base->BitSet.elem != nullptr) {
  1934. // TODO(lachsinc): Do bitsets have integration with non-primitive types other than enums?
  1935. elem_type = base->BitSet.elem;
  1936. if (elem_type->kind == Type_Enum) {
  1937. GB_ASSERT(elem_type->Enum.fields.count == base->BitSet.upper + 1);
  1938. }
  1939. }
  1940. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1941. di->CompositeType.name = named != nullptr ? named->Named.name : str_lit("bit_set");
  1942. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1943. di->CompositeType.size = ir_debug_size_bits(base);
  1944. map_set(&module->debug_info, hash_type(type), di);
  1945. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, base->BitSet.upper + 1);
  1946. di->CompositeType.elements = elements_di;
  1947. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1948. for (i64 i = 0; i <= base->BitSet.upper; ++i) {
  1949. u32 offset = cast(u32)i;
  1950. // TODO(lachsinc): Maybe name these fields numbered ascending?
  1951. String name = str_lit("field_todo");
  1952. if (elem_type != nullptr && is_type_enum(elem_type)) {
  1953. // name = base_type(elem_type)->Enum.fields[i]->token.string;
  1954. }
  1955. irDebugInfo *field_di = ir_add_debug_info_field_internal(module, name, t_u32, // TODO(lachsinc): u32 fine??
  1956. 0,
  1957. nullptr,
  1958. di);
  1959. field_di->DerivedType.size = 1;
  1960. field_di->DerivedType.offset = offset; // Offset stored in bits already, no need to convert
  1961. field_di->DerivedType.flags = irDebugInfoFlag_Bitfield;
  1962. map_set(&module->debug_info, hash_pointer(field_di), field_di);
  1963. array_add(&elements_di->DebugInfoArray.elements, field_di);
  1964. }
  1965. return di;
  1966. }
  1967. irDebugInfo *ir_add_debug_info_type_string(irModule *module, irDebugInfo *scope, Entity *e, Type *type) {
  1968. // TODO(lachsinc): Does this only occur once ??
  1969. irDebugInfo **existing = map_get(&module->debug_info, hash_type(t_string));
  1970. if (existing != nullptr) {
  1971. GB_ASSERT((*existing)->kind == irDebugInfo_CompositeType);
  1972. return *existing;
  1973. } else {
  1974. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1975. di->CompositeType.name = type->Basic.name;
  1976. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1977. di->CompositeType.size = ir_debug_size_bits(t_string);
  1978. di->CompositeType.align = ir_debug_align_bits(t_string);
  1979. map_set(&module->debug_info, hash_type(type), di);
  1980. // Field "data"
  1981. irDebugInfo *data_di = ir_add_debug_info_field_internal(module, str_lit("data"), t_cstring,
  1982. 0,
  1983. nullptr,
  1984. di);
  1985. map_set(&module->debug_info, hash_pointer(data_di), data_di);
  1986. // Field "len"
  1987. irDebugInfo *len_di = ir_add_debug_info_field_internal(module, str_lit("len"), t_i64,
  1988. data_di->DerivedType.size,
  1989. nullptr,
  1990. di);
  1991. map_set(&module->debug_info, hash_pointer(len_di), len_di);
  1992. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 2);
  1993. array_add(&elements_di->DebugInfoArray.elements, data_di);
  1994. array_add(&elements_di->DebugInfoArray.elements, len_di);
  1995. di->CompositeType.elements = elements_di;
  1996. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1997. return di;
  1998. }
  1999. }
  2000. irDebugInfo *ir_add_debug_info_type_any(irModule *module) {
  2001. irDebugInfo **existing = map_get(&module->debug_info, hash_type(t_any));
  2002. if (existing != nullptr) {
  2003. GB_ASSERT((*existing)->kind == irDebugInfo_CompositeType);
  2004. return *existing;
  2005. } else {
  2006. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2007. di->CompositeType.name = t_any->Basic.name;
  2008. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2009. di->CompositeType.size = ir_debug_size_bits(t_any);
  2010. di->CompositeType.align = ir_debug_align_bits(t_any);
  2011. map_set(&module->debug_info, hash_type(t_any), di);
  2012. // Field "data"
  2013. irDebugInfo *data_di = ir_add_debug_info_field_internal(module, str_lit("data"), t_rawptr,
  2014. 0,
  2015. nullptr,
  2016. di);
  2017. map_set(&module->debug_info, hash_pointer(data_di), data_di);
  2018. // Field "id"
  2019. irDebugInfo *id_di = ir_add_debug_info_field_internal(module, str_lit("id"), t_typeid,
  2020. data_di->DerivedType.size,
  2021. nullptr,
  2022. di);
  2023. map_set(&module->debug_info, hash_pointer(id_di), id_di);
  2024. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 2);
  2025. array_add(&elements_di->DebugInfoArray.elements, data_di);
  2026. array_add(&elements_di->DebugInfoArray.elements, id_di);
  2027. di->CompositeType.elements = elements_di;
  2028. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  2029. return di;
  2030. }
  2031. }
  2032. irDebugInfo *ir_add_debug_info_type_complex(irModule *module, Type *type) {
  2033. GB_ASSERT(type->kind == Type_Basic && is_type_complex(type));
  2034. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2035. map_set(&module->debug_info, hash_type(type), di);
  2036. di->CompositeType.name = type->Basic.name;
  2037. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2038. di->CompositeType.size = ir_debug_size_bits(type);
  2039. Type *field_type = base_complex_elem_type(type);
  2040. irDebugInfo *real_di = ir_add_debug_info_field_internal(module, str_lit("real"), field_type, 0*cast(i32)type_size_of(field_type), nullptr, di);
  2041. irDebugInfo *imag_di = ir_add_debug_info_field_internal(module, str_lit("imag"), field_type, 1*cast(i32)type_size_of(field_type), nullptr, di);
  2042. map_set(&module->debug_info, hash_pointer(real_di), real_di);
  2043. map_set(&module->debug_info, hash_pointer(imag_di), imag_di);
  2044. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 2);
  2045. array_add(&elements_di->DebugInfoArray.elements, real_di);
  2046. array_add(&elements_di->DebugInfoArray.elements, imag_di);
  2047. di->CompositeType.elements = elements_di;
  2048. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  2049. return di;
  2050. }
  2051. irDebugInfo *ir_add_debug_info_type_quaternion(irModule *module, Type *type) {
  2052. GB_ASSERT(type->kind == Type_Basic && is_type_quaternion(type));
  2053. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2054. map_set(&module->debug_info, hash_type(type), di);
  2055. di->CompositeType.name = type->Basic.name;
  2056. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2057. di->CompositeType.size = ir_debug_size_bits(type);
  2058. Type *field_type = base_complex_elem_type(type);
  2059. // @QuaternionLayout
  2060. irDebugInfo *imag_di = ir_add_debug_info_field_internal(module, str_lit("imag"), field_type, 0*cast(i32)type_size_of(field_type), nullptr, di);
  2061. irDebugInfo *jmag_di = ir_add_debug_info_field_internal(module, str_lit("jmag"), field_type, 1*cast(i32)type_size_of(field_type), nullptr, di);
  2062. irDebugInfo *kmag_di = ir_add_debug_info_field_internal(module, str_lit("kmag"), field_type, 2*cast(i32)type_size_of(field_type), nullptr, di);
  2063. irDebugInfo *real_di = ir_add_debug_info_field_internal(module, str_lit("real"), field_type, 3*cast(i32)type_size_of(field_type), nullptr, di);
  2064. map_set(&module->debug_info, hash_pointer(imag_di), imag_di);
  2065. map_set(&module->debug_info, hash_pointer(jmag_di), jmag_di);
  2066. map_set(&module->debug_info, hash_pointer(kmag_di), kmag_di);
  2067. map_set(&module->debug_info, hash_pointer(real_di), real_di);
  2068. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 4);
  2069. array_add(&elements_di->DebugInfoArray.elements, imag_di);
  2070. array_add(&elements_di->DebugInfoArray.elements, jmag_di);
  2071. array_add(&elements_di->DebugInfoArray.elements, kmag_di);
  2072. array_add(&elements_di->DebugInfoArray.elements, real_di);
  2073. di->CompositeType.elements = elements_di;
  2074. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  2075. return di;
  2076. }
  2077. irDebugInfo *ir_add_debug_info_proc_type(irModule *module, Type *type) {
  2078. GB_ASSERT(type->kind == Type_Proc);
  2079. irDebugInfo **existing = map_get(&module->debug_info, hash_type(type));
  2080. if (existing != nullptr) {
  2081. GB_ASSERT((*existing)->kind == irDebugInfo_ProcType);
  2082. return *existing;
  2083. }
  2084. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_ProcType);
  2085. map_set(&module->debug_info, hash_type(type), di);
  2086. isize result_count = type->Proc.result_count;
  2087. isize param_count = type->Proc.param_count;
  2088. // gb_max(result_count, 1) because llvm expects explicit "null" return type
  2089. di->ProcType.types = ir_add_debug_info_array(module, 0, gb_max(result_count, 1) + param_count);
  2090. // TODO(bill): Is this even correct?!
  2091. irDebugInfo *scope = di;
  2092. // Result/return types
  2093. if (result_count >= 1) {
  2094. TypeTuple *results_tuple = &type->Proc.results->Tuple;
  2095. for_array(i, results_tuple->variables) {
  2096. Entity *e = results_tuple->variables[i];
  2097. if (e->kind != Entity_Variable) {
  2098. continue;
  2099. }
  2100. irDebugInfo *type_di = ir_add_debug_info_type(module, e->type, e, scope, nullptr);
  2101. GB_ASSERT_NOT_NULL(type_di);
  2102. array_add(&di->ProcType.types->DebugInfoArray.elements, type_di);
  2103. }
  2104. } else {
  2105. // llvm expects "!{null}" for a function without return type, use nullptr to represent it.
  2106. array_add(&di->ProcType.types->DebugInfoArray.elements, (irDebugInfo*)nullptr);
  2107. }
  2108. // Param types
  2109. if (param_count >= 1) {
  2110. TypeTuple *params_tuple = &type->Proc.params->Tuple;
  2111. for_array(i, params_tuple->variables) {
  2112. Entity *e = params_tuple->variables[i];
  2113. if (e->kind != Entity_Variable) {
  2114. continue;
  2115. }
  2116. irDebugInfo *type_di = ir_add_debug_info_type(module, e->type, e, scope, nullptr);
  2117. GB_ASSERT_NOT_NULL(type_di);
  2118. array_add(&di->ProcType.types->DebugInfoArray.elements, type_di);
  2119. }
  2120. }
  2121. return di;
  2122. }
  2123. irDebugInfo *ir_add_debug_info_type(irModule *module, Type *type, Entity *e, irDebugInfo *scope, irDebugInfo *file) {
  2124. // NOTE(lachsinc): Special handling for procedure pointers - we hash their types directly into DISubroutineType's
  2125. // but we need them interpreted as pointers when we use them as variables.
  2126. if (type->kind == Type_Proc) {
  2127. if (e->kind == Entity_Variable || e->kind == Entity_TypeName) {
  2128. // TODO(lachsinc): Wasteful (maybe?). Create a derived type for _every_ different proc ptr type
  2129. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2130. map_set(&module->debug_info, hash_pointer(di), di);
  2131. di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  2132. di->DerivedType.size = ir_debug_size_bits(t_rawptr);
  2133. di->DerivedType.base_type = ir_add_debug_info_proc_type(module, type);
  2134. return di;
  2135. } else {
  2136. GB_PANIC("Proc definitions should have their type created manually (not through this function)");
  2137. }
  2138. }
  2139. irDebugInfo **existing = map_get(&module->debug_info, hash_type(type));
  2140. if (existing != nullptr) {
  2141. return *existing;
  2142. }
  2143. // Reset entity/location info, if applicable, for every type we try add.
  2144. // TODO(lachsinc): Confirm this doesn't mess up field's scopes etc.
  2145. if (type->kind == Type_Named) {
  2146. e = type->Named.type_name;
  2147. if (e) {
  2148. CheckerInfo *info = module->info;
  2149. file = ir_add_debug_info_file(module, ast_file_of_filename(info, e->token.pos.file));
  2150. // TODO(lachsinc): Determine proper scope for type declaration location stuff.
  2151. scope = file;
  2152. }
  2153. }
  2154. // TODO(lachsinc): Reorder if tests, "unique" types, like basic etc. should go last, they are most likely to hit the existing hashed type
  2155. // and no point checking them for the rest of the types. Or just use a massive switch...
  2156. // NOTE(lachsinc): Types should be inserted into debug_info map as their named, not base_type()'d counterparts.
  2157. Type *base = base_type(type);
  2158. if (type->kind == Type_Named) {
  2159. Type *named_base = type->Named.base;
  2160. // TODO(lachsinc): Better way to determine distinct etc. or just handle structs, enums before we reach here.
  2161. // ir_is_type_aggregate() except with no call to base_type().
  2162. if (named_base->kind != Type_Struct &&
  2163. named_base->kind != Type_Union &&
  2164. named_base->kind != Type_Enum &&
  2165. named_base->kind != Type_BitField &&
  2166. named_base->kind != Type_Tuple) {
  2167. // distinct / typedef etc.
  2168. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2169. if (type->kind == Type_Named) {
  2170. di->DerivedType.name = type->Named.name;
  2171. } else if (named_base->kind == Type_Basic) {
  2172. di->DerivedType.name = named_base->Basic.name;
  2173. }
  2174. di->DerivedType.tag = irDebugBasicEncoding_typedef;
  2175. map_set(&module->debug_info, hash_type(type), di);
  2176. // TODO(lachsinc): Do we need to try and resolve a new entity/scope for the base type?
  2177. // Maybe we also want to pull out type->Named.type_name ?? in the case it is a Named
  2178. di->DerivedType.base_type = ir_add_debug_info_type(module, named_base, e, scope, file);
  2179. return di;
  2180. }
  2181. }
  2182. if (type->kind == Type_Basic) {
  2183. switch (type->Basic.kind) {
  2184. // Composite basic types
  2185. case Basic_complex64: case Basic_complex128:
  2186. return ir_add_debug_info_type_complex(module, type);
  2187. case Basic_quaternion128: case Basic_quaternion256:
  2188. return ir_add_debug_info_type_quaternion(module, type);
  2189. case Basic_string:
  2190. return ir_add_debug_info_type_string(module, scope, e, type);
  2191. case Basic_any:
  2192. return ir_add_debug_info_type_any(module);
  2193. // Derived basic types
  2194. case Basic_cstring:
  2195. case Basic_rawptr: {
  2196. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2197. di->DerivedType.name = type->Basic.name;
  2198. di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  2199. di->DerivedType.size = ir_debug_size_bits(t_rawptr);
  2200. di->DerivedType.align = ir_debug_align_bits(t_rawptr); // TODO(lachsinc): Not sure if align is required.
  2201. map_set(&module->debug_info, hash_type(type), di);
  2202. if (type->Basic.kind == Basic_cstring) {
  2203. di->DerivedType.base_type = ir_add_debug_info_type(module, t_i8, e, scope, file);
  2204. } else {
  2205. // NOTE(lachsinc): llvm expects "null" for rawptr/voidptr
  2206. }
  2207. return di;
  2208. }
  2209. // Basic basic types
  2210. default: {
  2211. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_BasicType);
  2212. di->BasicType.encoding = ir_debug_encoding_for_basic(type->Basic.kind);
  2213. di->BasicType.name = type->Basic.name;
  2214. di->BasicType.size = ir_debug_size_bits(type);
  2215. di->BasicType.align = ir_debug_align_bits(type);
  2216. map_set(&module->debug_info, hash_type(type), di);
  2217. return di;
  2218. }
  2219. }
  2220. }
  2221. if (is_type_pointer(type)) {
  2222. // TODO(lachsinc): Ensure this handles pointer-to-pointer of same type etc. correctly.
  2223. Type *deref = type_deref(base);
  2224. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2225. di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  2226. di->DerivedType.size = ir_debug_size_bits(type);
  2227. // NOTE(lachsinc): Map set before creating base_type to avoid circular dependency issues.
  2228. map_set(&module->debug_info, hash_type(type), di);
  2229. if (is_type_struct(deref)) {
  2230. int i = 123;
  2231. }
  2232. di->DerivedType.base_type = ir_add_debug_info_type(module, deref, e, scope, file);
  2233. return di;
  2234. }
  2235. if (is_type_opaque(type)) {
  2236. return ir_add_debug_info_type(module, strip_opaque_type(type), e, scope, file);
  2237. }
  2238. if (is_type_struct(type) ||
  2239. is_type_union(type) || is_type_enum(type) || is_type_tuple(type)) {
  2240. if (type->kind == Type_Named) {
  2241. // NOTE(lachsinc): Named named's should always be handled prior as typedefs.
  2242. GB_ASSERT(type->Named.base->kind != Type_Named);
  2243. }
  2244. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2245. // NOTE(lachsinc): Set map value before resolving field types to avoid circular dependencies.
  2246. map_set(&module->debug_info, hash_type(type), di);
  2247. if (is_type_named(type)) {
  2248. di->CompositeType.name = type->kind == Type_Named ? type->Named.name : type->Basic.name;
  2249. }
  2250. if (e) {
  2251. di->CompositeType.file = file;
  2252. di->CompositeType.scope = scope;
  2253. di->CompositeType.pos = e->token.pos;
  2254. }
  2255. di->CompositeType.size = ir_debug_size_bits(type);
  2256. // di->CompositeType.align = ir_debug_align_bits(type); // TODO(lachsinc): Necessary?
  2257. if (is_type_struct(type)) {
  2258. GB_ASSERT(base->kind == Type_Struct);
  2259. if (!is_type_named(type)) {
  2260. di->CompositeType.name = str_lit("struct");
  2261. GB_ASSERT_NOT_NULL(scope);
  2262. di->CompositeType.scope = scope;
  2263. }
  2264. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2265. di->CompositeType.elements = ir_add_debug_info_array(module, 0, base->Struct.fields.count);
  2266. for_array(field_index, base->Struct.fields) {
  2267. array_add(&di->CompositeType.elements->DebugInfoArray.elements,
  2268. ir_add_debug_info_field(module, di, base->Struct.fields[field_index], type,
  2269. cast(i32)field_index, base->Struct.fields[field_index]->type, file));
  2270. }
  2271. } else if (is_type_union(type)) {
  2272. GB_ASSERT(base->kind == Type_Union);
  2273. if (!is_type_named(type)) {
  2274. di->CompositeType.name = str_lit("union");
  2275. GB_ASSERT_NOT_NULL(scope);
  2276. di->CompositeType.scope = scope;
  2277. }
  2278. di->CompositeType.tag = irDebugBasicEncoding_union_type;
  2279. di->CompositeType.elements = ir_add_debug_info_array(module, 0, base->Union.variants.count);
  2280. // TODO(lachsinc): Cleanup; this should be handled in a more generic manner for all types.
  2281. file = ir_add_debug_info_file(module, base->Union.node->file);
  2282. GB_ASSERT_NOT_NULL(file); // Union debug info requires file info
  2283. di->CompositeType.file = file;
  2284. di->CompositeType.pos = base->Union.node->UnionType.token.pos;
  2285. for_array(field_index, base->Union.variants) {
  2286. // TODO(bill): Union pseudo-"fields"
  2287. // irDebugInfo *di = ir_add_debug_info_field(module, di, nullptr, type, cast(i32)field_index, base->Union.variants[field_index], file);
  2288. // array_add(&di->CompositeType.elements->DebugInfoArray.elements, di);
  2289. }
  2290. } else if (is_type_enum(type)) {
  2291. GB_ASSERT(base->kind == Type_Enum);
  2292. if (!is_type_named(type)) {
  2293. di->CompositeType.name = str_lit("enum");
  2294. GB_ASSERT_NOT_NULL(scope);
  2295. di->CompositeType.scope = scope;
  2296. }
  2297. di->CompositeType.tag = irDebugBasicEncoding_enumeration_type;
  2298. di->CompositeType.base_type = ir_add_debug_info_type(module, base->Enum.base_type, e, scope, file);
  2299. di->CompositeType.elements = ir_add_debug_info_array(module, 0, base->Enum.fields.count);
  2300. for_array(field_index, base->Enum.fields) {
  2301. array_add(&di->CompositeType.elements->DebugInfoArray.elements,
  2302. ir_add_debug_info_enumerator(module, base->Enum.fields[field_index]));
  2303. }
  2304. // TODO(lachsinc): Do we want to ensure this is an enum in the global scope before
  2305. // adding it into the modules enum array ??
  2306. array_add(&module->debug_compile_unit->CompileUnit.enums->DebugInfoArray.elements, di);
  2307. } else if (is_type_tuple(type)) {
  2308. GB_ASSERT(base->kind == Type_Tuple);
  2309. if (!is_type_named(type)) {
  2310. di->CompositeType.name = str_lit("tuple");
  2311. GB_ASSERT_NOT_NULL(scope);
  2312. di->CompositeType.scope = scope;
  2313. }
  2314. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2315. di->CompositeType.elements = ir_add_debug_info_array(module, 0, base->Tuple.variables.count);
  2316. // TODO(lachsinc): Ensure offsets are set properly?
  2317. for_array(var_index, base->Tuple.variables) {
  2318. array_add(&di->CompositeType.elements->DebugInfoArray.elements,
  2319. ir_add_debug_info_field(module, di, base->Tuple.variables[var_index], type,
  2320. cast(i32)var_index, base->Tuple.variables[var_index]->type, file));
  2321. }
  2322. }
  2323. return di;
  2324. }
  2325. if (is_type_dynamic_array(type)) {
  2326. return ir_add_debug_info_type_dynamic_array(module, type, e, scope, file);
  2327. }
  2328. if (is_type_array(type)) {
  2329. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2330. di->CompositeType.size = ir_debug_size_bits(type);
  2331. di->CompositeType.align = ir_debug_align_bits(type);
  2332. di->CompositeType.tag = irDebugBasicEncoding_array_type;
  2333. di->CompositeType.array_count = (i32)type->Array.count;
  2334. map_set(&module->debug_info, hash_type(type), di);
  2335. di->CompositeType.base_type = ir_add_debug_info_type(module, type->Array.elem, e, scope, file);
  2336. GB_ASSERT(base->kind != Type_Named);
  2337. return di;
  2338. }
  2339. if (is_type_enumerated_array(type)) {
  2340. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2341. di->CompositeType.size = ir_debug_size_bits(type);
  2342. di->CompositeType.align = ir_debug_align_bits(type);
  2343. di->CompositeType.tag = irDebugBasicEncoding_array_type;
  2344. di->CompositeType.array_count = (i32)type->EnumeratedArray.count;
  2345. map_set(&module->debug_info, hash_type(type), di);
  2346. di->CompositeType.base_type = ir_add_debug_info_type(module, type->EnumeratedArray.elem, e, scope, file);
  2347. GB_ASSERT(base->kind != Type_Named);
  2348. return di;
  2349. }
  2350. if (is_type_slice(type)) {
  2351. // NOTE(lachsinc): Every slice type has its own composite type / field debug infos created. This is sorta wasteful.
  2352. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2353. di->CompositeType.name = str_lit("slice");
  2354. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2355. di->CompositeType.size = ir_debug_size_bits(type); // TODO(lachsinc): Correct ??
  2356. di->CompositeType.align = ir_debug_align_bits(type);
  2357. map_set(&module->debug_info, hash_type(type), di);
  2358. // Data pointer type
  2359. irDebugInfo *data_ptr_di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2360. Type *elem_type = type->Slice.elem;
  2361. if (is_type_named(elem_type)) {
  2362. data_ptr_di->DerivedType.name = elem_type->kind == Type_Named ? elem_type->Named.name : elem_type->Basic.name;
  2363. }
  2364. data_ptr_di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  2365. data_ptr_di->DerivedType.size = ir_debug_size_bits(t_rawptr);
  2366. map_set(&module->debug_info, hash_pointer(data_ptr_di), data_ptr_di);
  2367. data_ptr_di->DerivedType.base_type = ir_add_debug_info_type(module, elem_type, e, scope, file);
  2368. irDebugInfo *data_di = ir_add_debug_info_field_internal(module, str_lit("data"), t_rawptr,
  2369. 0,
  2370. nullptr,
  2371. di);
  2372. data_di->DerivedType.base_type = data_ptr_di;
  2373. map_set(&module->debug_info, hash_pointer(data_di), data_di);
  2374. irDebugInfo *len_di = ir_add_debug_info_field_internal(module, str_lit("len"), t_int,
  2375. data_di->DerivedType.size,
  2376. nullptr,
  2377. di);
  2378. map_set(&module->debug_info, hash_pointer(len_di), len_di);
  2379. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 2);
  2380. array_add(&elements_di->DebugInfoArray.elements, data_di);
  2381. array_add(&elements_di->DebugInfoArray.elements, len_di);
  2382. di->CompositeType.elements = elements_di;
  2383. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  2384. return di;
  2385. }
  2386. if (is_type_map(type)) {
  2387. // TODO(lachsinc): Looks like "generated_struct_type" map.entries.data is just a u8*, we could
  2388. // always look at the map header and create the debug info manually (if we
  2389. // want struct members to be interpreted as the correct type).
  2390. // Also; are hashes meant to be interpreted as bool*'s ?? or is that simply slot occupied data?
  2391. return ir_add_debug_info_type(module, type->Map.generated_struct_type, e, scope, file);
  2392. }
  2393. // NOTE(lachsinc): For now we just interpret all BitFieldValues as i64 inside ir_add_debug_info_type_bit_field().
  2394. /*
  2395. if (is_type_bit_field_value(type)) {
  2396. // NOTE(Lachsinc): Suboptimal; creates a new type for each unique bit field value type
  2397. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_BasicType);
  2398. di->BasicType.encoding = irDebugBasicEncoding_unsigned;
  2399. // di->BasicType.name = str_lit("todo");
  2400. di->BasicType.size = base->BitFieldValue.bits;
  2401. map_set(&module->debug_info, hash_type(type), di);
  2402. return di;
  2403. }
  2404. */
  2405. if (is_type_bit_field(type)) {
  2406. return ir_add_debug_info_type_bit_field(module, type, e, scope);
  2407. }
  2408. if (is_type_bit_set(type)) {
  2409. return ir_add_debug_info_type_bit_set(module, type, e, scope);
  2410. }
  2411. if (is_type_simd_vector(type)) {
  2412. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2413. di->CompositeType.size = ir_debug_size_bits(type);
  2414. di->CompositeType.align = ir_debug_align_bits(type);
  2415. di->CompositeType.tag = irDebugBasicEncoding_array_type;
  2416. di->CompositeType.array_count = (i32)type->SimdVector.count;
  2417. map_set(&module->debug_info, hash_type(type), di);
  2418. di->CompositeType.base_type = ir_add_debug_info_type(module, type->SimdVector.elem, e, scope, file);
  2419. GB_ASSERT(base->kind != Type_Named);
  2420. return di;
  2421. }
  2422. if (is_type_relative_pointer(type)) {
  2423. Type *base_integer = base_type(type)->RelativePointer.base_integer;
  2424. base_integer = core_type(base_integer);
  2425. GB_ASSERT(base_integer->kind == Type_Basic);
  2426. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_BasicType);
  2427. di->BasicType.encoding = ir_debug_encoding_for_basic(base_integer->Basic.kind);
  2428. di->BasicType.name = base_integer->Basic.name;
  2429. di->BasicType.size = ir_debug_size_bits(type);
  2430. di->BasicType.align = ir_debug_align_bits(type);
  2431. map_set(&module->debug_info, hash_type(type), di);
  2432. return di;
  2433. }
  2434. if (is_type_relative_slice(type)) {
  2435. Type *base_integer = base_type(type)->RelativeSlice.base_integer;
  2436. base_integer = core_type(base_integer);
  2437. // NOTE(lachsinc): Every slice type has its own composite type / field debug infos created. This is sorta wasteful.
  2438. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2439. di->CompositeType.name = str_lit("relative slice");
  2440. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2441. di->CompositeType.size = ir_debug_size_bits(type); // TODO(lachsinc): Correct ??
  2442. di->CompositeType.align = ir_debug_align_bits(type);
  2443. map_set(&module->debug_info, hash_type(type), di);
  2444. irDebugInfo *data_di = ir_add_debug_info_field_internal(module, str_lit("data"), base_integer,
  2445. 0,
  2446. nullptr,
  2447. di);
  2448. map_set(&module->debug_info, hash_pointer(data_di), data_di);
  2449. irDebugInfo *len_di = ir_add_debug_info_field_internal(module, str_lit("len"), base_integer,
  2450. data_di->DerivedType.size,
  2451. nullptr,
  2452. di);
  2453. map_set(&module->debug_info, hash_pointer(len_di), len_di);
  2454. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 2);
  2455. array_add(&elements_di->DebugInfoArray.elements, data_di);
  2456. array_add(&elements_di->DebugInfoArray.elements, len_di);
  2457. di->CompositeType.elements = elements_di;
  2458. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  2459. return di;
  2460. }
  2461. GB_PANIC("Unreachable %s", type_to_string(type));
  2462. return nullptr;
  2463. }
  2464. irDebugInfo *ir_add_debug_info_global(irModule *module, irValue *v) {
  2465. if (!module->generate_debug_info) {
  2466. return nullptr;
  2467. }
  2468. Entity *e = v->Global.entity;
  2469. // NOTE(lachsinc): Just to be safe/robust; globals are likely added once only?
  2470. irDebugInfo **existing = map_get(&module->debug_info, hash_entity(e));
  2471. if (existing != nullptr) {
  2472. return *existing;
  2473. }
  2474. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_GlobalVariableExpression);
  2475. map_set(&module->debug_info, hash_entity(e), di);
  2476. // Create or fetch file debug info.
  2477. CheckerInfo *info = module->info;
  2478. String filename = e->token.pos.file;
  2479. AstFile *f = ast_file_of_filename(info, filename);
  2480. GB_ASSERT_NOT_NULL(f);
  2481. irDebugInfo *scope = ir_add_debug_info_file(module, f);
  2482. irDebugInfo *var_di = ir_alloc_debug_info(irDebugInfo_GlobalVariable);
  2483. var_di->GlobalVariable.name = e->token.string;
  2484. var_di->GlobalVariable.scope = scope;
  2485. var_di->GlobalVariable.file = scope;
  2486. var_di->GlobalVariable.pos = e->token.pos;
  2487. var_di->GlobalVariable.variable = v;
  2488. // NOTE(lachsinc): The "DIGlobalVariableExpression" owns us, and is what we refer to from other
  2489. // locations in the ir source, so we will reserve the "e" hash for it, and use something else
  2490. // unique for the DIGlobalVariable's hash.
  2491. map_set(&module->debug_info, hash_pointer(var_di), var_di);
  2492. var_di->GlobalVariable.type = ir_add_debug_info_type(module, e->type, nullptr, scope, nullptr);
  2493. GB_ASSERT_NOT_NULL(var_di->GlobalVariable.type);
  2494. di->GlobalVariableExpression.var = var_di;
  2495. array_add(&module->debug_compile_unit->CompileUnit.globals->DebugInfoArray.elements, di);
  2496. return di;
  2497. }
  2498. irDebugInfo *ir_add_debug_info_block(irProcedure *proc, Scope *scope) {
  2499. irModule *module = proc->module;
  2500. irDebugInfo **existing = map_get(&module->debug_info, hash_pointer(scope));
  2501. if (existing != nullptr) {
  2502. GB_ASSERT((*existing)->kind == irDebugInfo_LexicalBlock);
  2503. return *existing;
  2504. }
  2505. Ast *block = scope->node;
  2506. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_LexicalBlock);
  2507. di->LexicalBlock.file = proc->debug_scope->Proc.file;
  2508. di->LexicalBlock.scope = proc->debug_scope;
  2509. di->LexicalBlock.pos = ast_token(block).pos;
  2510. map_set(&module->debug_info, hash_pointer(scope), di);
  2511. return di;
  2512. }
  2513. irDebugInfo *ir_add_debug_info_local(irProcedure *proc, Entity *e, i32 arg_id) {
  2514. // TODO(lachsinc): Not sure if this handles generated locals properly as they may not have
  2515. // enough information contained inside "e".
  2516. irModule *module = proc->module;
  2517. if (!module->generate_debug_info) {
  2518. return nullptr;
  2519. }
  2520. irDebugInfo *scope = nullptr;
  2521. irDebugInfo *file = nullptr;
  2522. if (e->scope && e->scope->node->kind == Ast_ProcType) {
  2523. scope = proc->debug_scope;
  2524. file = proc->debug_scope->Proc.file;
  2525. } else {
  2526. scope = ir_add_debug_info_block(proc, e->scope);
  2527. file = scope->LexicalBlock.file;
  2528. }
  2529. GB_ASSERT_NOT_NULL(scope);
  2530. GB_ASSERT_NOT_NULL(file);
  2531. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_LocalVariable);
  2532. di->LocalVariable.name = e->token.string;
  2533. di->LocalVariable.scope = scope;
  2534. di->LocalVariable.file = file;
  2535. di->LocalVariable.pos = e->token.pos;
  2536. di->LocalVariable.arg = arg_id;
  2537. di->LocalVariable.type = ir_add_debug_info_type(module, e->type, e, scope, file); // TODO(lachsinc): Is this the correct entity to pass? Or do we want a TypeName ??
  2538. map_set(&module->debug_info, hash_entity(e), di);
  2539. return di;
  2540. }
  2541. irDebugInfo *ir_add_debug_info_proc(irProcedure *proc) {
  2542. irModule *module = proc->module;
  2543. if (!module->generate_debug_info) {
  2544. return nullptr;
  2545. }
  2546. Entity *entity = proc->entity;
  2547. // Add / retrieve debug info for file.
  2548. CheckerInfo *info = proc->module->info;
  2549. String filename = proc->entity->token.pos.file;
  2550. AstFile *f = ast_file_of_filename(info, filename);
  2551. irDebugInfo *file = nullptr;
  2552. if (f) {
  2553. file = ir_add_debug_info_file(proc->module, f);
  2554. }
  2555. // TODO(lachsinc): Should scope be made separate to file?
  2556. irDebugInfo *scope = file;
  2557. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_Proc);
  2558. map_set(&proc->module->debug_info, hash_entity(entity), di);
  2559. di->Proc.entity = entity;
  2560. di->Proc.name = proc->name;
  2561. di->Proc.file = file;
  2562. di->Proc.pos = entity->token.pos;
  2563. di->Proc.type = ir_add_debug_info_proc_type(proc->module, proc->type);
  2564. proc->debug_scope = di;
  2565. return di;
  2566. }
  2567. irDebugInfo *ir_add_debug_info_location(irModule *m, Ast *node, irDebugInfo *scope, Entity *e) {
  2568. if (node == nullptr || scope == nullptr) {
  2569. if (e != nullptr && scope != nullptr) {
  2570. // irDebugInfo **existing = map_get(&m->debug_info, hash_entity(e));
  2571. // if (existing != nullptr) {
  2572. // return *existing;
  2573. // }
  2574. // // TODO HACK(bill): This is a little dirty but it is should do for the weird edge cases
  2575. // irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_Location);
  2576. // di->Location.pos = e->token.pos;
  2577. // di->Location.scope = scope;
  2578. // map_set(&m->debug_info, hash_entity(e), di);
  2579. // return di;
  2580. }
  2581. return nullptr;
  2582. }
  2583. // TODO(lachsinc): Should we traverse the node/children until we find one with
  2584. // valid token/pos and use that instead??
  2585. irDebugInfo **existing = map_get(&m->debug_info, hash_node(node));
  2586. if (existing != nullptr) {
  2587. return *existing;
  2588. }
  2589. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_Location);
  2590. di->Location.pos = ast_token(node).pos;
  2591. di->Location.scope = scope;
  2592. map_set(&m->debug_info, hash_node(node), di);
  2593. return di;
  2594. }
  2595. void ir_push_debug_location(irModule *m, Ast *node, irDebugInfo *scope, Entity *e) {
  2596. irDebugInfo *debug_location = ir_add_debug_info_location(m, node, scope, e);
  2597. array_add(&m->debug_location_stack, debug_location);
  2598. }
  2599. void ir_pop_debug_location(irModule *m) {
  2600. GB_ASSERT_MSG(m->debug_location_stack.count > 0, "Attempt to pop debug location stack too many times");
  2601. array_pop(&m->debug_location_stack);
  2602. }
  2603. ////////////////////////////////////////////////////////////////
  2604. //
  2605. // @Emit
  2606. //
  2607. ////////////////////////////////////////////////////////////////
  2608. irValue *ir_emit_runtime_call(irProcedure *proc, char const *name_, Array<irValue *> args, Ast *expr = nullptr, ProcInlining inlining = ProcInlining_none);
  2609. irValue *ir_emit_package_call(irProcedure *proc, char const *package_name_, char const *name_, Array<irValue *> args, Ast *expr = nullptr, ProcInlining inlining = ProcInlining_none);
  2610. irValue *ir_emit_store(irProcedure *p, irValue *address, irValue *value, bool is_volatile) {
  2611. Type *a = type_deref(ir_type(address));
  2612. if (is_type_boolean(a)) {
  2613. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  2614. value = ir_emit_conv(p, value, a);
  2615. }
  2616. if (address) address->uses += 1;
  2617. if (value) value->uses += 1;
  2618. Type *b = ir_type(value);
  2619. if (!is_type_untyped(b)) {
  2620. GB_ASSERT_MSG(are_types_identical(core_type(a), core_type(b)), "%s %s", type_to_string(a), type_to_string(b));
  2621. }
  2622. return ir_emit(p, ir_instr_store(p, address, value, is_volatile));
  2623. }
  2624. irValue *ir_emit_load(irProcedure *p, irValue *address, i64 custom_align) {
  2625. GB_ASSERT(address != nullptr);
  2626. Type *t = type_deref(ir_type(address));
  2627. // if (is_type_boolean(t)) {
  2628. // return ir_emit(p, ir_instr_load_bool(p, address));
  2629. // }
  2630. if (address) address->uses += 1;
  2631. auto instr = ir_instr_load(p, address);
  2632. instr->Instr.Load.custom_align = custom_align;
  2633. return ir_emit(p, instr);
  2634. }
  2635. irValue *ir_emit_select(irProcedure *p, irValue *cond, irValue *t, irValue *f) {
  2636. if (cond) cond->uses += 1;
  2637. if (t) t->uses += 1;
  2638. if (f) f->uses += 1;
  2639. return ir_emit(p, ir_instr_select(p, cond, t, f));
  2640. }
  2641. void ir_value_set_debug_location(irProcedure *proc, irValue *v) {
  2642. GB_ASSERT_NOT_NULL(proc);
  2643. GB_ASSERT_NOT_NULL(v);
  2644. if (v->loc != nullptr) {
  2645. return; // Already set
  2646. }
  2647. if (proc->is_startup) {
  2648. // ignore startup procedures
  2649. return;
  2650. }
  2651. irModule *m = proc->module;
  2652. GB_ASSERT(m->debug_location_stack.count > 0);
  2653. v->loc = *array_end_ptr(&m->debug_location_stack);
  2654. if (v->loc == nullptr && proc->entity != nullptr) {
  2655. if (proc->is_entry_point || (string_compare(proc->name, str_lit(IR_STARTUP_RUNTIME_PROC_NAME)) == 0)) {
  2656. // NOTE(lachsinc): Entry point (main()) and runtime_startup are the only ones where null location is considered valid.
  2657. } else {
  2658. if (v->kind == irValue_Instr) {
  2659. auto *instr = &v->Instr;
  2660. gb_printf_err("Instruction kind: %.*s\n", LIT(ir_instr_strings[instr->kind]));
  2661. if (instr->kind == irInstr_DebugDeclare) {
  2662. gb_printf_err("\t%.*s\n", LIT(instr->DebugDeclare.entity->token.string));
  2663. }
  2664. }
  2665. GB_PANIC("Value without debug location: %.*s %p; %p :: %s", LIT(proc->name), proc->entity, v, type_to_string(proc->type));
  2666. }
  2667. }
  2668. }
  2669. void ir_emit_zero_init(irProcedure *p, irValue *address, Ast *expr) {
  2670. gbAllocator a = ir_allocator();
  2671. Type *t = type_deref(ir_type(address));
  2672. isize sz = type_size_of(t);
  2673. if (address) address->uses += 1;
  2674. if (!(gb_is_power_of_two(sz) && sz <= build_context.max_align)) {
  2675. // TODO(bill): Is this a good idea?
  2676. auto args = array_make<irValue *>(a, 2);
  2677. args[0] = ir_emit_conv(p, address, t_rawptr);
  2678. args[1] = ir_const_int(type_size_of(t));
  2679. AstPackage *pkg_runtime = get_core_package(p->module->info, str_lit("runtime"));
  2680. if (p->entity != nullptr) {
  2681. String name = p->entity->token.string;
  2682. if (p->entity->pkg != pkg_runtime && !(name == "mem_zero" || name == "memset")) {
  2683. ir_emit_comment(p, str_lit("ZeroInit"));
  2684. irValue *v = ir_emit_package_call(p, "runtime", "mem_zero", args, expr);
  2685. return;
  2686. }
  2687. }
  2688. }
  2689. ir_emit(p, ir_instr_zero_init(p, address));
  2690. }
  2691. irValue *ir_emit_comment(irProcedure *p, String text) {
  2692. return ir_emit(p, ir_instr_comment(p, text));
  2693. }
  2694. void ir_emit_init_context(irProcedure *proc, irValue *c) {
  2695. GB_ASSERT(c != nullptr);
  2696. irModule *m = proc->module;
  2697. gbAllocator a = ir_allocator();
  2698. auto args = array_make<irValue *>(a, 1);
  2699. args[0] = c;
  2700. ir_emit_runtime_call(proc, "__init_context", args);
  2701. }
  2702. irValue *ir_copy_value_to_ptr(irProcedure *proc, irValue *val, Type *new_type, i64 alignment) {
  2703. i64 type_alignment = type_align_of(new_type);
  2704. if (alignment < type_alignment) {
  2705. alignment = type_alignment;
  2706. }
  2707. GB_ASSERT_MSG(are_types_identical(new_type, ir_type(val)), "%s %s", type_to_string(new_type), type_to_string(ir_type(val)));
  2708. irValue *ptr = ir_add_local_generated(proc, new_type, false);
  2709. ptr->Instr.Local.alignment = alignment;
  2710. ir_emit_store(proc, ptr, val);
  2711. return ptr;
  2712. }
  2713. irValue *ir_emit_bitcast(irProcedure *proc, irValue *data, Type *type) {
  2714. return ir_emit(proc, ir_instr_conv(proc, irConv_bitcast, data, ir_type(data), type));
  2715. }
  2716. void ir_emit_unreachable(irProcedure *proc) {
  2717. ir_emit(proc, ir_instr_unreachable(proc));
  2718. }
  2719. irValue *ir_get_package_value(irModule *m, String package_name, String entity_name) {
  2720. AstPackage *rt_pkg = get_core_package(m->info, package_name);
  2721. Entity *e = scope_lookup_current(rt_pkg->scope, entity_name);
  2722. irValue **found = map_get(&m->values, hash_entity(e));
  2723. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(e->token.string));
  2724. return *found;
  2725. }
  2726. irValue *ir_find_or_generate_context_ptr(irProcedure *proc) {
  2727. if (proc->context_stack.count > 0) {
  2728. return proc->context_stack[proc->context_stack.count-1].value;
  2729. }
  2730. irValue *c = ir_add_local_generated(proc, t_context, true);
  2731. ir_push_context_onto_stack(proc, c);
  2732. ir_emit_init_context(proc, c);
  2733. return c;
  2734. }
  2735. Array<irValue *> ir_value_to_array(irProcedure *p, irValue *value) {
  2736. Array<irValue *> array = {};
  2737. Type *t = base_type(ir_type(value));
  2738. if (t == nullptr) {
  2739. // Do nothing
  2740. } else if (is_type_tuple(t)) {
  2741. GB_ASSERT(t->kind == Type_Tuple);
  2742. auto *rt = &t->Tuple;
  2743. if (rt->variables.count > 0) {
  2744. array = array_make<irValue *>(ir_allocator(), rt->variables.count);
  2745. for_array(i, rt->variables) {
  2746. irValue *elem = ir_emit_struct_ev(p, value, cast(i32)i);
  2747. array[i] = elem;
  2748. }
  2749. }
  2750. } else {
  2751. array = array_make<irValue *>(ir_allocator(), 1);
  2752. array[0] = value;
  2753. }
  2754. return array;
  2755. }
  2756. irValue *ir_emit_call(irProcedure *p, irValue *value, Array<irValue *> const &args, ProcInlining inlining = ProcInlining_none, bool use_return_ptr_hint = false) {
  2757. Type *pt = base_type(ir_type(value));
  2758. GB_ASSERT(pt->kind == Type_Proc);
  2759. Type *results = pt->Proc.results;
  2760. if (p->entity != nullptr) {
  2761. if (p->entity->flags & EntityFlag_Disabled) {
  2762. return nullptr;
  2763. }
  2764. }
  2765. defer (if (pt->Proc.diverging) {
  2766. ir_emit_unreachable(p);
  2767. });
  2768. irValue *context_ptr = nullptr;
  2769. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2770. context_ptr = ir_find_or_generate_context_ptr(p);
  2771. }
  2772. set_procedure_abi_types(pt);
  2773. bool is_c_vararg = pt->Proc.c_vararg;
  2774. isize param_count = pt->Proc.param_count;
  2775. if (is_c_vararg) {
  2776. GB_ASSERT(param_count-1 <= args.count);
  2777. param_count -= 1;
  2778. } else {
  2779. GB_ASSERT_MSG(param_count == args.count, "%.*s %td == %td", LIT(p->entity->token.string), param_count, args.count);
  2780. }
  2781. auto processed_args = array_make<irValue *>(permanent_allocator(), 0, args.count);
  2782. for (isize i = 0; i < param_count; i++) {
  2783. Entity *e = pt->Proc.params->Tuple.variables[i];
  2784. if (e->kind != Entity_Variable) {
  2785. array_add(&processed_args, args[i]);
  2786. continue;
  2787. }
  2788. GB_ASSERT(e->flags & EntityFlag_Param);
  2789. Type *original_type = e->type;
  2790. Type *new_type = pt->Proc.abi_compat_params[i];
  2791. Type *arg_type = ir_type(args[i]);
  2792. if (are_types_identical(arg_type, new_type)) {
  2793. // NOTE(bill): Done
  2794. array_add(&processed_args, args[i]);
  2795. } else if (!are_types_identical(original_type, new_type)) {
  2796. if (is_type_pointer(new_type) && !is_type_pointer(original_type)) {
  2797. Type *av = core_type(type_deref(new_type));
  2798. if (are_types_identical(av, core_type(original_type))) {
  2799. if (e->flags&EntityFlag_ImplicitReference) {
  2800. array_add(&processed_args, ir_address_from_load_or_generate_local(p, args[i]));
  2801. } else if (!is_type_pointer(arg_type)) {
  2802. array_add(&processed_args, ir_copy_value_to_ptr(p, args[i], original_type, 16));
  2803. }
  2804. } else {
  2805. array_add(&processed_args, ir_emit_transmute(p, args[i], new_type));
  2806. }
  2807. } else if (is_type_integer(new_type) || is_type_float(new_type)) {
  2808. array_add(&processed_args, ir_emit_transmute(p, args[i], new_type));
  2809. } else if (new_type == t_llvm_bool) {
  2810. array_add(&processed_args, ir_emit_conv(p, args[i], new_type));
  2811. } else if (is_type_simd_vector(new_type)) {
  2812. array_add(&processed_args, ir_emit_transmute(p, args[i], new_type));
  2813. } else if (is_type_tuple(new_type)) {
  2814. Type *abi_type = pt->Proc.abi_compat_params[i];
  2815. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  2816. irValue *x = nullptr;
  2817. i64 st_sz = type_size_of(st);
  2818. i64 arg_sz = type_size_of(ir_type(args[i]));
  2819. if (st_sz == arg_sz) {
  2820. x = ir_emit_transmute(p, args[i], st);
  2821. } else {
  2822. // NOTE(bill): struct{f32, f32, f32} != struct{#simd[2]f32, f32}
  2823. GB_ASSERT(st_sz > arg_sz);
  2824. irValue *xx = ir_add_local_generated(p, st, false);
  2825. irValue *pp = ir_emit_conv(p, xx, alloc_type_pointer(ir_type(args[i])));
  2826. ir_emit_store(p, pp, args[i]);
  2827. x = ir_emit_load(p, xx);
  2828. }
  2829. for (isize j = 0; j < new_type->Tuple.variables.count; j++) {
  2830. irValue *xx = ir_emit_struct_ev(p, x, cast(i32)j);
  2831. array_add(&processed_args, xx);
  2832. }
  2833. } else {
  2834. if (type_size_of(new_type) == type_size_of(original_type)) {
  2835. irValue *x = ir_emit_transmute(p, args[i], new_type);
  2836. array_add(&processed_args, x);
  2837. } else {
  2838. GB_PANIC("ABI ERROR: %s %s %s\n", type_to_string(original_type), type_to_string(new_type), type_to_string(arg_type));
  2839. }
  2840. }
  2841. } else {
  2842. irValue *x = ir_emit_conv(p, args[i], new_type);
  2843. array_add(&processed_args, x);
  2844. }
  2845. }
  2846. if (inlining == ProcInlining_none) {
  2847. inlining = p->inlining;
  2848. }
  2849. irValue *result = nullptr;
  2850. Type *abi_rt = pt->Proc.abi_compat_result_type;
  2851. Type *rt = reduce_tuple_to_single_type(results);
  2852. if (pt->Proc.return_by_pointer) {
  2853. irValue *return_ptr = nullptr;
  2854. if (use_return_ptr_hint && p->return_ptr_hint_value != nullptr) {
  2855. if (are_types_identical(type_deref(ir_type(p->return_ptr_hint_value)), rt)) {
  2856. return_ptr = p->return_ptr_hint_value;
  2857. p->return_ptr_hint_used = true;
  2858. return_ptr->uses += 1;
  2859. }
  2860. }
  2861. if (return_ptr == nullptr) {
  2862. return_ptr = ir_add_local_generated(p, rt, true);
  2863. }
  2864. GB_ASSERT(is_type_pointer(ir_type(return_ptr)));
  2865. ir_emit(p, ir_instr_call(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining));
  2866. result = ir_emit_load(p, return_ptr);
  2867. } else {
  2868. result = ir_emit(p, ir_instr_call(p, value, nullptr, processed_args, abi_rt, context_ptr, inlining));
  2869. if (abi_rt != results) {
  2870. result = ir_emit_transmute(p, result, rt);
  2871. }
  2872. }
  2873. if (value->kind == irValue_Proc) {
  2874. irProcedure *the_proc = &value->Proc;
  2875. Entity *e = the_proc->entity;
  2876. if (e != nullptr && entity_has_deferred_procedure(e)) {
  2877. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  2878. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  2879. irValue **deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  2880. GB_ASSERT(deferred_found != nullptr);
  2881. irValue *deferred = *deferred_found;
  2882. auto in_args = args;
  2883. Array<irValue *> result_as_args = {};
  2884. switch (kind) {
  2885. case DeferredProcedure_none:
  2886. break;
  2887. case DeferredProcedure_in:
  2888. result_as_args = in_args;
  2889. break;
  2890. case DeferredProcedure_out:
  2891. result_as_args = ir_value_to_array(p, result);
  2892. break;
  2893. case DeferredProcedure_in_out:
  2894. {
  2895. auto out_args = ir_value_to_array(p, result);
  2896. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  2897. array_copy(&result_as_args, in_args, 0);
  2898. array_copy(&result_as_args, out_args, in_args.count);
  2899. }
  2900. break;
  2901. }
  2902. ir_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  2903. }
  2904. }
  2905. return result;
  2906. }
  2907. irValue *ir_emit_runtime_call(irProcedure *proc, char const *name_, Array<irValue *> args, Ast *expr, ProcInlining inlining) {
  2908. String name = make_string_c(cast(char *)name_);
  2909. AstPackage *p = proc->module->info->runtime_package;
  2910. Entity *e = scope_lookup_current(p->scope, name);
  2911. irValue **found = map_get(&proc->module->values, hash_entity(e));
  2912. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(name));
  2913. irValue *gp = *found;
  2914. irValue *call = ir_emit_call(proc, gp, args, inlining);
  2915. return call;
  2916. }
  2917. irValue *ir_emit_package_call(irProcedure *proc, char const *package_name_, char const *name_, Array<irValue *> args, Ast *expr, ProcInlining inlining) {
  2918. String name = make_string_c(cast(char *)name_);
  2919. String package_name = make_string_c(cast(char *)package_name_);
  2920. AstPackage *p = get_core_package(proc->module->info, package_name);
  2921. Entity *e = scope_lookup_current(p->scope, name);
  2922. irValue **found = map_get(&proc->module->values, hash_entity(e));
  2923. GB_ASSERT_MSG(found != nullptr, "%s.%.*s", package_name_, LIT(name));
  2924. irValue *gp = *found;
  2925. irValue *call = ir_emit_call(proc, gp, args, inlining);
  2926. return call;
  2927. }
  2928. void ir_emit_defer_stmts(irProcedure *proc, irDeferExitKind kind, irBlock *block) {
  2929. isize count = proc->defer_stmts.count;
  2930. isize i = count;
  2931. while (i --> 0) {
  2932. irDefer d = proc->defer_stmts[i];
  2933. isize prev_context_stack_count = proc->context_stack.count;
  2934. defer (proc->context_stack.count = prev_context_stack_count);
  2935. proc->context_stack.count = d.context_stack_count;
  2936. if (kind == irDeferExit_Default) {
  2937. if (proc->scope_index == d.scope_index &&
  2938. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  2939. ir_build_defer_stmt(proc, d);
  2940. array_pop(&proc->defer_stmts);
  2941. continue;
  2942. } else {
  2943. break;
  2944. }
  2945. } else if (kind == irDeferExit_Return) {
  2946. ir_build_defer_stmt(proc, d);
  2947. } else if (kind == irDeferExit_Branch) {
  2948. GB_ASSERT(block != nullptr);
  2949. isize lower_limit = block->scope_index;
  2950. if (lower_limit < d.scope_index) {
  2951. ir_build_defer_stmt(proc, d);
  2952. }
  2953. }
  2954. }
  2955. }
  2956. void ir_open_scope(irProcedure *proc) {
  2957. proc->scope_index++;
  2958. }
  2959. void ir_close_scope(irProcedure *proc, irDeferExitKind kind, irBlock *block, bool pop_stack=true) {
  2960. ir_emit_defer_stmts(proc, kind, block);
  2961. GB_ASSERT(proc->scope_index > 0);
  2962. // NOTE(bill): Remove `context`s made in that scope
  2963. isize end_idx = proc->context_stack.count-1;
  2964. isize pop_count = 0;
  2965. for (;;) {
  2966. if (end_idx < 0) {
  2967. break;
  2968. }
  2969. irContextData *end = &proc->context_stack[end_idx];
  2970. if (end == nullptr) {
  2971. break;
  2972. }
  2973. if (end->scope_index != proc->scope_index) {
  2974. break;
  2975. }
  2976. end_idx -= 1;
  2977. pop_count += 1;
  2978. }
  2979. if (pop_stack) {
  2980. for (isize i = 0; i < pop_count; i++) {
  2981. array_pop(&proc->context_stack);
  2982. }
  2983. }
  2984. proc->scope_index--;
  2985. }
  2986. void ir_emit_return(irProcedure *proc, irValue *v) {
  2987. ir_emit_defer_stmts(proc, irDeferExit_Return, nullptr);
  2988. if (proc->type->Proc.return_by_pointer) {
  2989. ir_emit_store(proc, proc->return_ptr, v);
  2990. ir_emit(proc, ir_instr_return(proc, nullptr));
  2991. } else {
  2992. Type *abi_rt = proc->type->Proc.abi_compat_result_type;
  2993. if (abi_rt != proc->type->Proc.results) {
  2994. v = ir_emit_transmute(proc, v, abi_rt);
  2995. }
  2996. ir_emit(proc, ir_instr_return(proc, v));
  2997. }
  2998. if (v) v->uses += 1;
  2999. }
  3000. void ir_emit_jump(irProcedure *proc, irBlock *target_block) {
  3001. irBlock *b = proc->curr_block;
  3002. if (b == nullptr) {
  3003. return;
  3004. }
  3005. ir_emit(proc, ir_instr_jump(proc, target_block));
  3006. ir_add_edge(b, target_block);
  3007. ir_start_block(proc, nullptr);
  3008. }
  3009. void ir_emit_if(irProcedure *proc, irValue *cond, irBlock *true_block, irBlock *false_block) {
  3010. irBlock *b = proc->curr_block;
  3011. if (b == nullptr) {
  3012. return;
  3013. }
  3014. ir_emit(proc, ir_instr_if(proc, cond, true_block, false_block));
  3015. ir_add_edge(b, true_block);
  3016. ir_add_edge(b, false_block);
  3017. ir_start_block(proc, nullptr);
  3018. if (cond) cond->uses += 1;
  3019. }
  3020. irValue *ir_emit_comp(irProcedure *proc, TokenKind op_kind, irValue *left, irValue *right);
  3021. irValue *ir_gen_map_header(irProcedure *proc, irValue *map_val_ptr, Type *map_type) {
  3022. GB_ASSERT_MSG(is_type_pointer(ir_type(map_val_ptr)), "%s", type_to_string(ir_type(map_val_ptr)));
  3023. gbAllocator a = ir_allocator();
  3024. irValue *h = ir_add_local_generated(proc, t_map_header, false); // all the values will be initialzed later
  3025. map_type = base_type(map_type);
  3026. Type *key_type = map_type->Map.key;
  3027. Type *val_type = map_type->Map.value;
  3028. // NOTE(bill): Removes unnecessary allocation if split gep
  3029. irValue *gep0 = ir_emit_struct_ep(proc, h, 0);
  3030. irValue *m = ir_emit_conv(proc, map_val_ptr, type_deref(ir_type(gep0)));
  3031. ir_emit_store(proc, gep0, m);
  3032. i64 entry_size = type_size_of (map_type->Map.entry_type);
  3033. i64 entry_align = type_align_of (map_type->Map.entry_type);
  3034. i64 key_offset = type_offset_of(map_type->Map.entry_type, 2);
  3035. i64 key_size = type_size_of (map_type->Map.key);
  3036. i64 value_offset = type_offset_of(map_type->Map.entry_type, 3);
  3037. i64 value_size = type_size_of (map_type->Map.value);
  3038. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 1), ir_get_equal_proc_for_type(proc->module, key_type));
  3039. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 2), ir_const_int(entry_size));
  3040. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 3), ir_const_int(entry_align));
  3041. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 4), ir_const_uintptr(key_offset));
  3042. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 5), ir_const_int(key_size));
  3043. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 6), ir_const_uintptr(value_offset));
  3044. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 7), ir_const_int(value_size));
  3045. return ir_emit_load(proc, h);
  3046. }
  3047. irValue *ir_const_hash(irModule *m, irValue *key, Type *key_type) {
  3048. irValue *hashed_key = nullptr;
  3049. if (key->kind == irValue_Constant) {
  3050. u64 hash = 0xcbf29ce484222325;
  3051. if (is_type_string(key_type)) {
  3052. GB_ASSERT(key->Constant.value.kind == ExactValue_String);
  3053. String s = key->Constant.value.value_string;
  3054. hash = fnv64a(s.text, s.len);
  3055. } else {
  3056. return nullptr;
  3057. }
  3058. // TODO(bill): other const hash types
  3059. if (build_context.word_size == 4) {
  3060. hash &= 0xffffffffull;
  3061. }
  3062. hashed_key = ir_const_uintptr(hash);
  3063. }
  3064. return hashed_key;
  3065. }
  3066. irValue *ir_gen_map_hash(irProcedure *proc, irValue *key, Type *key_type) {
  3067. Type *hash_type = t_u64;
  3068. irValue *v = ir_add_local_generated(proc, t_map_hash, true);
  3069. Type *t = base_type(ir_type(key));
  3070. key = ir_emit_conv(proc, key, key_type);
  3071. irValue *key_ptr = ir_address_from_load_or_generate_local(proc, key);
  3072. key_ptr = ir_emit_conv(proc, key_ptr, t_rawptr);
  3073. irValue *hashed_key = ir_const_hash(proc->module, key, key_type);
  3074. if (hashed_key == nullptr) {
  3075. irValue *hasher = ir_get_hasher_proc_for_type(proc->module, key_type);
  3076. auto args = array_make<irValue *>(permanent_allocator(), 2);
  3077. args[0] = key_ptr;
  3078. args[1] = ir_value_constant(t_uintptr, exact_value_i64(0));
  3079. hashed_key = ir_emit_call(proc, hasher, args);
  3080. }
  3081. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), hashed_key);
  3082. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 1), key_ptr);
  3083. return ir_emit_load(proc, v);
  3084. }
  3085. // NOTE(bill): Returns nullptr if not possible
  3086. irValue *ir_address_from_load_or_generate_local(irProcedure *proc, irValue *val) {
  3087. if (val->kind == irValue_Instr) {
  3088. if (val->Instr.kind == irInstr_Load) {
  3089. return val->Instr.Load.address;
  3090. }
  3091. }
  3092. Type *type = ir_type(val);
  3093. irValue *local = ir_add_local_generated(proc, type, false);
  3094. ir_emit_store(proc, local, val);
  3095. return local;
  3096. }
  3097. irValue *ir_address_from_load(irProcedure *proc, irValue *val) {
  3098. if (val->kind == irValue_Instr) {
  3099. if (val->Instr.kind == irInstr_Load) {
  3100. return val->Instr.Load.address;
  3101. }
  3102. }
  3103. GB_PANIC("ir_address_from_load");
  3104. return nullptr;
  3105. }
  3106. Type *ir_addr_type(irAddr const &addr) {
  3107. if (addr.addr == nullptr) {
  3108. return nullptr;
  3109. }
  3110. if (addr.kind == irAddr_Map) {
  3111. Type *t = base_type(addr.map_type);
  3112. GB_ASSERT(is_type_map(t));
  3113. return t->Map.value;
  3114. }
  3115. Type *t = ir_type(addr.addr);
  3116. GB_ASSERT(is_type_pointer(t));
  3117. return type_deref(t);
  3118. }
  3119. irValue *ir_emit_source_code_location(irProcedure *proc, String procedure, TokenPos pos);
  3120. irValue *ir_emit_source_code_location(irProcedure *proc, Ast *node);
  3121. irValue *ir_emit_ptr_offset(irProcedure *proc, irValue *ptr, irValue *offset);
  3122. irValue *ir_emit_arith(irProcedure *proc, TokenKind op, irValue *left, irValue *right, Type *type);
  3123. irValue *ir_emit_deep_field_gep(irProcedure *proc, irValue *e, Selection sel);
  3124. void ir_emit_bounds_check(irProcedure *proc, Token token, irValue *index, irValue *len);
  3125. irValue *ir_insert_dynamic_map_key_and_value(irProcedure *proc, irValue *addr, Type *map_type,
  3126. irValue *map_key, irValue *map_value, Ast *node) {
  3127. map_type = base_type(map_type);
  3128. irValue *h = ir_gen_map_header(proc, addr, map_type);
  3129. irValue *key = ir_gen_map_hash(proc, map_key, map_type->Map.key);
  3130. irValue *v = ir_emit_conv(proc, map_value, map_type->Map.value);
  3131. irValue *ptr = ir_add_local_generated(proc, ir_type(v), false);
  3132. ir_emit_store(proc, ptr, v);
  3133. auto args = array_make<irValue *>(ir_allocator(), 4);
  3134. args[0] = h;
  3135. args[1] = key;
  3136. args[2] = ir_emit_conv(proc, ptr, t_rawptr);
  3137. args[3] = ir_emit_source_code_location(proc, node);
  3138. return ir_emit_runtime_call(proc, "__dynamic_map_set", args);
  3139. }
  3140. irValue *ir_soa_struct_len(irProcedure *proc, irValue *value) {
  3141. Type *t = base_type(ir_type(value));
  3142. bool is_ptr = false;
  3143. if (is_type_pointer(t)) {
  3144. is_ptr = true;
  3145. t = base_type(type_deref(t));
  3146. }
  3147. if (t->Struct.soa_kind == StructSoa_Fixed) {
  3148. return ir_const_int(t->Struct.soa_count);
  3149. }
  3150. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  3151. t->Struct.soa_kind == StructSoa_Dynamic);
  3152. isize n = 0;
  3153. Type *elem = base_type(t->Struct.soa_elem);
  3154. if (elem->kind == Type_Struct) {
  3155. n = elem->Struct.fields.count;
  3156. } else if (elem->kind == Type_Array) {
  3157. n = elem->Array.count;
  3158. } else {
  3159. GB_PANIC("Unreachable");
  3160. }
  3161. if (is_ptr) {
  3162. irValue *v = ir_emit_struct_ep(proc, value, cast(i32)n);
  3163. return ir_emit_load(proc, v);
  3164. }
  3165. return ir_emit_struct_ev(proc, value, cast(i32)n);
  3166. }
  3167. irValue *ir_soa_struct_cap(irProcedure *proc, irValue *value) {
  3168. Type *t = base_type(ir_type(value));
  3169. bool is_ptr = false;
  3170. if (is_type_pointer(t)) {
  3171. is_ptr = true;
  3172. t = base_type(type_deref(t));
  3173. }
  3174. if (t->Struct.soa_kind == StructSoa_Fixed) {
  3175. return ir_const_int(t->Struct.soa_count);
  3176. }
  3177. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  3178. isize n = 0;
  3179. Type *elem = base_type(t->Struct.soa_elem);
  3180. if (elem->kind == Type_Struct) {
  3181. n = elem->Struct.fields.count+1;
  3182. } else if (elem->kind == Type_Array) {
  3183. n = elem->Array.count+1;
  3184. } else {
  3185. GB_PANIC("Unreachable");
  3186. }
  3187. if (is_ptr) {
  3188. irValue *v = ir_emit_struct_ep(proc, value, cast(i32)n);
  3189. return ir_emit_load(proc, v);
  3190. }
  3191. return ir_emit_struct_ev(proc, value, cast(i32)n);
  3192. }
  3193. irValue *ir_addr_load(irProcedure *proc, irAddr const &addr);
  3194. void ir_addr_store(irProcedure *proc, irAddr addr, irValue *value) {
  3195. if (addr.addr == nullptr) {
  3196. return;
  3197. }
  3198. if (addr.kind == irAddr_RelativePointer && addr.relative.deref) {
  3199. addr = ir_addr(ir_address_from_load(proc, ir_addr_load(proc, addr)));
  3200. }
  3201. if (addr.kind == irAddr_RelativePointer) {
  3202. Type *rel_ptr = base_type(ir_addr_type(addr));
  3203. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  3204. value = ir_emit_conv(proc, value, rel_ptr->RelativePointer.pointer_type);
  3205. GB_ASSERT(is_type_pointer(ir_type(addr.addr)));
  3206. irValue *ptr = ir_emit_conv(proc, addr.addr, t_uintptr);
  3207. irValue *val_ptr = ir_emit_conv(proc, value, t_uintptr);
  3208. irValue *offset = offset = ir_emit_arith(proc, Token_Sub, val_ptr, ptr, t_uintptr);
  3209. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  3210. offset = ir_emit_conv(proc, offset, t_i64);
  3211. }
  3212. offset = ir_emit_conv(proc, offset, rel_ptr->RelativePointer.base_integer);
  3213. irValue *offset_ptr = ir_emit_conv(proc, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  3214. offset = ir_emit_select(proc,
  3215. ir_emit_comp(proc, Token_CmpEq, val_ptr, ir_value_nil(t_uintptr)),
  3216. ir_value_nil(rel_ptr->RelativePointer.base_integer),
  3217. offset
  3218. );
  3219. ir_emit_store(proc, offset_ptr, offset);
  3220. return;
  3221. } else if (addr.kind == irAddr_RelativeSlice) {
  3222. Type *rel_ptr = base_type(ir_addr_type(addr));
  3223. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  3224. value = ir_emit_conv(proc, value, rel_ptr->RelativeSlice.slice_type);
  3225. GB_ASSERT(is_type_pointer(ir_type(addr.addr)));
  3226. irValue *ptr = ir_emit_conv(proc, ir_emit_struct_ep(proc, addr.addr, 0), t_uintptr);
  3227. irValue *val_ptr = ir_emit_conv(proc, ir_slice_elem(proc, value), t_uintptr);
  3228. irValue *offset = ir_emit_arith(proc, Token_Sub, val_ptr, ptr, t_uintptr);
  3229. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  3230. offset = ir_emit_conv(proc, offset, t_i64);
  3231. }
  3232. offset = ir_emit_conv(proc, offset, rel_ptr->RelativePointer.base_integer);
  3233. irValue *offset_ptr = ir_emit_conv(proc, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  3234. offset = ir_emit_select(proc,
  3235. ir_emit_comp(proc, Token_CmpEq, val_ptr, ir_value_nil(t_uintptr)),
  3236. ir_value_nil(rel_ptr->RelativePointer.base_integer),
  3237. offset
  3238. );
  3239. ir_emit_store(proc, offset_ptr, offset);
  3240. irValue *len = ir_slice_len(proc, value);
  3241. len = ir_emit_conv(proc, len, rel_ptr->RelativePointer.base_integer);
  3242. irValue *len_ptr = ir_emit_struct_ep(proc, addr.addr, 1);
  3243. ir_emit_store(proc, len_ptr, len);
  3244. return;
  3245. } else if (addr.kind == irAddr_Map) {
  3246. ir_insert_dynamic_map_key_and_value(proc, addr.addr, addr.map_type, addr.map_key, value, proc->curr_stmt);
  3247. return;
  3248. } else if (addr.kind == irAddr_BitField) {
  3249. gbAllocator a = ir_allocator();
  3250. Type *bft = base_type(type_deref(ir_type(addr.addr)));
  3251. GB_ASSERT(is_type_bit_field(bft));
  3252. i32 value_index = addr.bit_field_value_index;
  3253. i32 offset = bft->BitField.offsets[value_index];
  3254. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  3255. i32 byte_index = offset / 8;
  3256. i32 bit_inset = offset % 8;
  3257. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  3258. if (size_in_bytes == 0) {
  3259. GB_ASSERT(size_in_bits == 0);
  3260. return;
  3261. }
  3262. Type *int_type = nullptr;
  3263. switch (size_in_bytes) {
  3264. case 1: int_type = t_u8; break;
  3265. case 2: int_type = t_u16; break;
  3266. case 4: int_type = t_u32; break;
  3267. case 8: int_type = t_u64; break;
  3268. }
  3269. GB_ASSERT(int_type != nullptr);
  3270. value = ir_emit_conv(proc, value, int_type);
  3271. irValue *bytes = ir_emit_conv(proc, addr.addr, t_u8_ptr);
  3272. bytes = ir_emit_ptr_offset(proc, bytes, ir_const_int(byte_index));
  3273. if (bit_inset == 0) {
  3274. irValue *v = value;
  3275. i32 sa = 8*size_in_bytes - size_in_bits;
  3276. if (sa > 0) {
  3277. irValue *shift_amount = ir_const_int(sa);
  3278. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
  3279. v = ir_emit_arith(proc, Token_Shr, v, shift_amount, int_type);
  3280. }
  3281. irValue *ptr = ir_emit_conv(proc, bytes, alloc_type_pointer(int_type));
  3282. irValue *sv = ir_emit_load(proc, ptr, 1);
  3283. // NOTE(bill): Zero out the lower bits that need to be stored to
  3284. sv = ir_emit_arith(proc, Token_Shr, sv, ir_const_int(size_in_bits), int_type);
  3285. sv = ir_emit_arith(proc, Token_Shl, sv, ir_const_int(size_in_bits), int_type);
  3286. v = ir_emit_arith(proc, Token_Or, sv, v, int_type);
  3287. ir_emit_store(proc, ptr, v, true);
  3288. return;
  3289. }
  3290. GB_ASSERT(0 < bit_inset && bit_inset < 8);
  3291. // First byte
  3292. {
  3293. irValue *shift_amount = ir_const_int(bit_inset);
  3294. irValue *ptr = ir_emit_conv(proc, bytes, alloc_type_pointer(t_u8));
  3295. irValue *v = ir_emit_conv(proc, value, t_u8);
  3296. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, t_u8);
  3297. irValue *sv = ir_emit_load(proc, bytes, 1);
  3298. // NOTE(bill): Zero out the upper bits that need to be stored to
  3299. sv = ir_emit_arith(proc, Token_Shl, sv, ir_const_int(8-bit_inset), t_u8);
  3300. sv = ir_emit_arith(proc, Token_Shr, sv, ir_const_int(8-bit_inset), t_u8);
  3301. v = ir_emit_arith(proc, Token_Or, sv, v, t_u8);
  3302. ir_emit_store(proc, ptr, v, true);
  3303. }
  3304. // Remaining bytes
  3305. if (bit_inset+size_in_bits > 8) {
  3306. irValue *ptr = ir_emit_conv(proc, ir_emit_ptr_offset(proc, bytes, v_one), alloc_type_pointer(int_type));
  3307. irValue *v = ir_emit_conv(proc, value, int_type);
  3308. v = ir_emit_arith(proc, Token_Shr, v, ir_const_int(8-bit_inset), int_type);
  3309. irValue *sv = ir_emit_load(proc, ptr, 1);
  3310. // NOTE(bill): Zero out the lower bits that need to be stored to
  3311. sv = ir_emit_arith(proc, Token_Shr, sv, ir_const_int(size_in_bits-bit_inset), int_type);
  3312. sv = ir_emit_arith(proc, Token_Shl, sv, ir_const_int(size_in_bits-bit_inset), int_type);
  3313. v = ir_emit_arith(proc, Token_Or, sv, v, int_type);
  3314. ir_emit_store(proc, ptr, v, true);
  3315. }
  3316. return;
  3317. } else if (addr.kind == irAddr_Context) {
  3318. irValue *old = ir_emit_load(proc, ir_find_or_generate_context_ptr(proc));
  3319. irValue *next = ir_add_local_generated(proc, t_context, true);
  3320. ir_emit_store(proc, next, old);
  3321. ir_push_context_onto_stack(proc, next);
  3322. if (addr.ctx.sel.index.count > 0) {
  3323. irValue *lhs = ir_emit_deep_field_gep(proc, next, addr.ctx.sel);
  3324. irValue *rhs = ir_emit_conv(proc, value, type_deref(ir_type(lhs)));
  3325. ir_emit_store(proc, lhs, rhs);
  3326. } else {
  3327. irValue *lhs = next;
  3328. irValue *rhs = ir_emit_conv(proc, value, ir_addr_type(addr));
  3329. ir_emit_store(proc, lhs, rhs);
  3330. }
  3331. return;
  3332. } else if (addr.kind == irAddr_SoaVariable) {
  3333. Type *t = type_deref(ir_type(addr.addr));
  3334. t = base_type(t);
  3335. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  3336. value = ir_emit_conv(proc, value, t->Struct.soa_elem);
  3337. irValue *index = addr.soa.index;
  3338. if (index->kind != irValue_Constant || t->Struct.soa_kind != StructSoa_Fixed) {
  3339. Type *t = base_type(type_deref(ir_type(addr.addr)));
  3340. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  3341. i64 count = t->Struct.soa_count;
  3342. irValue *len = ir_const_int(count);
  3343. ir_emit_bounds_check(proc, ast_token(addr.soa.index_expr), index, len);
  3344. }
  3345. for_array(i, t->Struct.fields) {
  3346. irValue *dst = ir_emit_struct_ep(proc, addr.addr, cast(i32)i);
  3347. dst = ir_emit_array_ep(proc, dst, index);
  3348. irValue *src = ir_emit_struct_ev(proc, value, cast(i32)i);
  3349. ir_emit_store(proc, dst, src);
  3350. }
  3351. return;
  3352. }
  3353. irValue *v = ir_emit_conv(proc, value, ir_addr_type(addr));
  3354. ir_emit_store(proc, addr.addr, v);
  3355. }
  3356. irValue *ir_addr_load(irProcedure *proc, irAddr const &addr) {
  3357. if (addr.addr == nullptr) {
  3358. GB_PANIC("Illegal addr load");
  3359. return nullptr;
  3360. }
  3361. if (addr.kind == irAddr_RelativePointer) {
  3362. Type *rel_ptr = base_type(ir_addr_type(addr));
  3363. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  3364. irValue *ptr = ir_emit_conv(proc, addr.addr, t_uintptr);
  3365. irValue *offset = ir_emit_conv(proc, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  3366. offset = ir_emit_load(proc, offset);
  3367. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  3368. offset = ir_emit_conv(proc, offset, t_i64);
  3369. }
  3370. offset = ir_emit_conv(proc, offset, t_uintptr);
  3371. irValue *absolute_ptr = ir_emit_arith(proc, Token_Add, ptr, offset, t_uintptr);
  3372. absolute_ptr = ir_emit_conv(proc, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  3373. irValue *cond = ir_emit_comp(proc, Token_CmpEq, offset, ir_value_nil(rel_ptr->RelativePointer.base_integer));
  3374. // NOTE(bill): nil check
  3375. irValue *nil_ptr = ir_value_nil(rel_ptr->RelativePointer.pointer_type);
  3376. irValue *final_ptr = ir_emit_select(proc, cond, nil_ptr, absolute_ptr);
  3377. return ir_emit_load(proc, final_ptr);
  3378. } else if (addr.kind == irAddr_RelativeSlice) {
  3379. Type *rel_ptr = base_type(ir_addr_type(addr));
  3380. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  3381. irValue *offset_ptr = ir_emit_struct_ep(proc, addr.addr, 0);
  3382. irValue *ptr = ir_emit_conv(proc, offset_ptr, t_uintptr);
  3383. irValue *offset = ir_emit_load(proc, offset_ptr);
  3384. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  3385. offset = ir_emit_conv(proc, offset, t_i64);
  3386. }
  3387. offset = ir_emit_conv(proc, offset, t_uintptr);
  3388. irValue *absolute_ptr = ir_emit_arith(proc, Token_Add, ptr, offset, t_uintptr);
  3389. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  3390. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  3391. Type *slice_elem = slice_type->Slice.elem;
  3392. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  3393. absolute_ptr = ir_emit_conv(proc, absolute_ptr, slice_elem_ptr);
  3394. irValue *cond = ir_emit_comp(proc, Token_CmpEq, offset, ir_value_nil(rel_ptr->RelativeSlice.base_integer));
  3395. // NOTE(bill): nil check
  3396. irValue *nil_ptr = ir_value_nil(slice_elem_ptr);
  3397. irValue *data = ir_emit_select(proc, cond, nil_ptr, absolute_ptr);
  3398. irValue *len = ir_emit_load(proc, ir_emit_struct_ep(proc, addr.addr, 1));
  3399. len = ir_emit_conv(proc, len, t_int);
  3400. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  3401. ir_fill_slice(proc, slice, data, len);
  3402. return ir_emit_load(proc, slice);
  3403. } else if (addr.kind == irAddr_Map) {
  3404. Type *map_type = base_type(addr.map_type);
  3405. irValue *v = ir_add_local_generated(proc, map_type->Map.lookup_result_type, true);
  3406. irValue *h = ir_gen_map_header(proc, addr.addr, map_type);
  3407. irValue *key = ir_gen_map_hash(proc, addr.map_key, map_type->Map.key);
  3408. auto args = array_make<irValue *>(ir_allocator(), 2);
  3409. args[0] = h;
  3410. args[1] = key;
  3411. irValue *ptr = ir_emit_runtime_call(proc, "__dynamic_map_get", args);
  3412. irValue *ok = ir_emit_conv(proc, ir_emit_comp(proc, Token_NotEq, ptr, v_raw_nil), t_bool);
  3413. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 1), ok);
  3414. irBlock *then = ir_new_block(proc, nullptr, "map.get.then");
  3415. irBlock *done = ir_new_block(proc, nullptr, "map.get.done");
  3416. ir_emit_if(proc, ok, then, done);
  3417. ir_start_block(proc, then);
  3418. {
  3419. // TODO(bill): mem copy it instead?
  3420. irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
  3421. irValue *value = ir_emit_conv(proc, ptr, ir_type(gep0));
  3422. ir_emit_store(proc, gep0, ir_emit_load(proc, value));
  3423. }
  3424. ir_emit_jump(proc, done);
  3425. ir_start_block(proc, done);
  3426. if (is_type_tuple(addr.map_result)) {
  3427. return ir_emit_load(proc, v);
  3428. } else {
  3429. irValue *single = ir_emit_struct_ep(proc, v, 0);
  3430. return ir_emit_load(proc, single);
  3431. }
  3432. } else if (addr.kind == irAddr_BitField) {
  3433. gbAllocator a = ir_allocator();
  3434. Type *bft = base_type(type_deref(ir_type(addr.addr)));
  3435. GB_ASSERT(is_type_bit_field(bft));
  3436. i32 value_index = addr.bit_field_value_index;
  3437. i32 offset = bft->BitField.offsets[value_index];
  3438. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  3439. i32 byte_index = offset / 8;
  3440. i32 bit_inset = offset % 8;
  3441. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  3442. if (size_in_bytes == 0) {
  3443. GB_ASSERT(size_in_bits == 0);
  3444. return v_zero32;
  3445. }
  3446. Type *int_type = nullptr;
  3447. switch (size_in_bytes) {
  3448. case 1: int_type = t_u8; break;
  3449. case 2: int_type = t_u16; break;
  3450. case 4: int_type = t_u32; break;
  3451. case 8: int_type = t_u64; break;
  3452. }
  3453. GB_ASSERT(int_type != nullptr);
  3454. irValue *bytes = ir_emit_conv(proc, addr.addr, t_u8_ptr);
  3455. bytes = ir_emit_ptr_offset(proc, bytes, ir_const_int(byte_index));
  3456. Type *int_ptr = alloc_type_pointer(int_type);
  3457. i32 sa = 8*size_in_bytes - size_in_bits;
  3458. if (bit_inset == 0) {
  3459. irValue *v = ir_emit_load(proc, ir_emit_conv(proc, bytes, int_ptr), 1);
  3460. if (sa > 0) {
  3461. irValue *shift_amount = ir_const_int(sa);
  3462. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
  3463. v = ir_emit_arith(proc, Token_Shr, v, shift_amount, int_type);
  3464. }
  3465. return v;
  3466. }
  3467. GB_ASSERT(8 > bit_inset);
  3468. irValue *ptr = ir_emit_conv(proc, bytes, int_ptr);
  3469. irValue *v = ir_emit_load(proc, ptr, 1);
  3470. v = ir_emit_arith(proc, Token_Shr, v, ir_const_int(bit_inset), int_type);
  3471. if (sa > 0) {
  3472. irValue *shift_amount = ir_const_int(sa);
  3473. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
  3474. v = ir_emit_arith(proc, Token_Shr, v, shift_amount, int_type);
  3475. }
  3476. return v;
  3477. } else if (addr.kind == irAddr_Context) {
  3478. if (addr.ctx.sel.index.count > 0) {
  3479. irValue *a = addr.addr;
  3480. irValue *b = ir_emit_deep_field_gep(proc, a, addr.ctx.sel);
  3481. return ir_emit_load(proc, b);
  3482. }
  3483. } else if (addr.kind == irAddr_SoaVariable) {
  3484. Type *t = type_deref(ir_type(addr.addr));
  3485. t = base_type(t);
  3486. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  3487. Type *elem = t->Struct.soa_elem;
  3488. irValue *len = nullptr;
  3489. if (t->Struct.soa_kind == StructSoa_Fixed) {
  3490. len = ir_const_int(t->Struct.soa_count);
  3491. } else {
  3492. irValue *v = ir_emit_load(proc, addr.addr);
  3493. len = ir_soa_struct_len(proc, v);
  3494. }
  3495. irValue *res = ir_add_local_generated(proc, elem, true);
  3496. if (addr.soa.index->kind != irValue_Constant || t->Struct.soa_kind != StructSoa_Fixed) {
  3497. ir_emit_bounds_check(proc, ast_token(addr.soa.index_expr), addr.soa.index, len);
  3498. }
  3499. if (t->Struct.soa_kind == StructSoa_Fixed) {
  3500. for_array(i, t->Struct.fields) {
  3501. Entity *field = t->Struct.fields[i];
  3502. Type *base_type = field->type;
  3503. GB_ASSERT(base_type->kind == Type_Array);
  3504. irValue *dst = ir_emit_struct_ep(proc, res, cast(i32)i);
  3505. irValue *src_ptr = ir_emit_struct_ep(proc, addr.addr, cast(i32)i);
  3506. src_ptr = ir_emit_array_ep(proc, src_ptr, addr.soa.index);
  3507. irValue *src = ir_emit_load(proc, src_ptr);
  3508. ir_emit_store(proc, dst, src);
  3509. }
  3510. } else {
  3511. isize field_count = t->Struct.fields.count;
  3512. if (t->Struct.soa_kind == StructSoa_Slice) {
  3513. field_count -= 1;
  3514. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  3515. field_count -= 3;
  3516. }
  3517. for (isize i = 0; i < field_count; i++) {
  3518. Entity *field = t->Struct.fields[i];
  3519. Type *base_type = field->type;
  3520. GB_ASSERT(base_type->kind == Type_Pointer);
  3521. Type *elem = base_type->Pointer.elem;
  3522. irValue *dst = ir_emit_struct_ep(proc, res, cast(i32)i);
  3523. irValue *src_ptr = ir_emit_struct_ep(proc, addr.addr, cast(i32)i);
  3524. src_ptr = ir_emit_ptr_offset(proc, src_ptr, addr.soa.index);
  3525. irValue *src = ir_emit_load(proc, src_ptr);
  3526. src = ir_emit_load(proc, src);
  3527. ir_emit_store(proc, dst, src);
  3528. }
  3529. }
  3530. return ir_emit_load(proc, res);
  3531. }
  3532. Type *t = base_type(ir_type(addr.addr));
  3533. if (t->kind == Type_Proc) {
  3534. // NOTE(bill): Imported procedures don't require a load as they are pointers
  3535. return addr.addr;
  3536. }
  3537. return ir_emit_load(proc, addr.addr);
  3538. }
  3539. irValue *ir_addr_get_ptr(irProcedure *proc, irAddr const &addr, bool allow_reference=false) {
  3540. if (addr.addr == nullptr) {
  3541. GB_PANIC("Illegal addr -> nullptr");
  3542. return nullptr;
  3543. }
  3544. switch (addr.kind) {
  3545. case irAddr_Map: {
  3546. if (allow_reference) {
  3547. Type *map_type = base_type(addr.map_type);
  3548. irValue *h = ir_gen_map_header(proc, addr.addr, map_type);
  3549. irValue *key = ir_gen_map_hash(proc, addr.map_key, map_type->Map.key);
  3550. auto args = array_make<irValue *>(ir_allocator(), 2);
  3551. args[0] = h;
  3552. args[1] = key;
  3553. irValue *ptr = ir_emit_runtime_call(proc, "__dynamic_map_get", args);
  3554. return ir_emit_conv(proc, ptr, alloc_type_pointer(map_type->Map.value));
  3555. } else {
  3556. irValue *v = ir_addr_load(proc, addr);
  3557. return ir_address_from_load_or_generate_local(proc, v);
  3558. }
  3559. }
  3560. case irAddr_RelativePointer: {
  3561. Type *rel_ptr = base_type(ir_addr_type(addr));
  3562. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  3563. irValue *ptr = ir_emit_conv(proc, addr.addr, t_uintptr);
  3564. irValue *offset = ir_emit_conv(proc, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  3565. offset = ir_emit_load(proc, offset);
  3566. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  3567. offset = ir_emit_conv(proc, offset, t_i64);
  3568. }
  3569. offset = ir_emit_conv(proc, offset, t_uintptr);
  3570. irValue *absolute_ptr = ir_emit_arith(proc, Token_Add, ptr, offset, t_uintptr);
  3571. absolute_ptr = ir_emit_conv(proc, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  3572. irValue *cond = ir_emit_comp(proc, Token_CmpEq, offset, ir_value_nil(rel_ptr->RelativePointer.base_integer));
  3573. // NOTE(bill): nil check
  3574. irValue *nil_ptr = ir_value_nil(rel_ptr->RelativePointer.pointer_type);
  3575. irValue *final_ptr = ir_emit_select(proc, cond, nil_ptr, absolute_ptr);
  3576. return final_ptr;
  3577. }
  3578. case irAddr_BitField: {
  3579. irValue *v = ir_addr_load(proc, addr);
  3580. return ir_address_from_load_or_generate_local(proc, v);
  3581. }
  3582. case irAddr_Context:
  3583. GB_PANIC("irAddr_Context should be handled elsewhere");
  3584. }
  3585. return addr.addr;
  3586. }
  3587. irValue *ir_build_addr_ptr(irProcedure *proc, Ast *expr) {
  3588. irAddr addr = ir_build_addr(proc, expr);
  3589. return ir_addr_get_ptr(proc, addr);
  3590. }
  3591. irValue *ir_dynamic_array_len(irProcedure *proc, irValue *da);
  3592. irValue *ir_dynamic_array_cap(irProcedure *proc, irValue *da);
  3593. irValue *ir_map_entries(irProcedure *proc, irValue *value) {
  3594. gbAllocator a = ir_allocator();
  3595. Type *t = base_type(ir_type(value));
  3596. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  3597. init_map_internal_types(t);
  3598. Type *gst = t->Map.generated_struct_type;
  3599. i32 index = 1;
  3600. irValue *entries = ir_emit(proc, ir_instr_struct_extract_value(proc, value, index, gst->Struct.fields[index]->type));
  3601. return entries;
  3602. }
  3603. irValue *ir_map_entries_ptr(irProcedure *proc, irValue *value) {
  3604. gbAllocator a = ir_allocator();
  3605. Type *t = base_type(type_deref(ir_type(value)));
  3606. if (is_type_pointer(t)) {
  3607. value = ir_emit_load(proc, value);
  3608. t = base_type(type_deref(t));
  3609. }
  3610. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  3611. init_map_internal_types(t);
  3612. Type *gst = t->Map.generated_struct_type;
  3613. i32 index = 1;
  3614. Type *ptr_t = alloc_type_pointer(gst->Struct.fields[index]->type);
  3615. irValue *entries = ir_emit(proc, ir_instr_struct_element_ptr(proc, value, index, ptr_t));
  3616. return entries;
  3617. }
  3618. irValue *ir_map_len(irProcedure *proc, irValue *value) {
  3619. irValue *entries = ir_map_entries(proc, value);
  3620. return ir_dynamic_array_len(proc, entries);
  3621. }
  3622. irValue *ir_map_cap(irProcedure *proc, irValue *value) {
  3623. irValue *entries = ir_map_entries(proc, value);
  3624. return ir_dynamic_array_cap(proc, entries);
  3625. }
  3626. struct irLoopData {
  3627. irValue *idx_addr;
  3628. irValue *idx;
  3629. irBlock *body;
  3630. irBlock *done;
  3631. irBlock *loop;
  3632. };
  3633. irLoopData ir_loop_start(irProcedure *proc, isize count, Type *index_type=t_int) {
  3634. irLoopData data = {};
  3635. irValue *max = ir_const_int(count);
  3636. data.idx_addr = ir_add_local_generated(proc, index_type, true);
  3637. data.body = ir_new_block(proc, nullptr, "loop.body");
  3638. data.done = ir_new_block(proc, nullptr, "loop.done");
  3639. data.loop = ir_new_block(proc, nullptr, "loop.loop");
  3640. ir_emit_jump(proc, data.loop);
  3641. ir_start_block(proc, data.loop);
  3642. data.idx = ir_emit_load(proc, data.idx_addr);
  3643. irValue *cond = ir_emit_comp(proc, Token_Lt, data.idx, max);
  3644. ir_emit_if(proc, cond, data.body, data.done);
  3645. ir_start_block(proc, data.body);
  3646. return data;
  3647. }
  3648. void ir_loop_end(irProcedure *proc, irLoopData const &data) {
  3649. if (data.idx_addr != nullptr) {
  3650. ir_emit_increment(proc, data.idx_addr);
  3651. ir_emit_jump(proc, data.loop);
  3652. ir_start_block(proc, data.done);
  3653. }
  3654. }
  3655. irValue *ir_emit_ptr_offset(irProcedure *proc, irValue *ptr, irValue *offset) {
  3656. offset = ir_emit_conv(proc, offset, t_int);
  3657. return ir_emit(proc, ir_instr_ptr_offset(proc, ptr, offset));
  3658. }
  3659. irValue *ir_emit_unary_arith(irProcedure *proc, TokenKind op, irValue *x, Type *type) {
  3660. switch (op) {
  3661. case Token_Add:
  3662. return x;
  3663. case Token_Not: // Boolean not
  3664. case Token_Xor: // Bitwise not
  3665. case Token_Sub: // Bitwise Not
  3666. break;
  3667. case Token_Pointer:
  3668. GB_PANIC("This should be handled elsewhere");
  3669. break;
  3670. }
  3671. if (is_type_array(ir_type(x))) {
  3672. ir_emit_comment(proc, str_lit("array.arith.begin"));
  3673. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  3674. Type *tl = base_type(ir_type(x));
  3675. irValue *val = ir_address_from_load_or_generate_local(proc, x);
  3676. GB_ASSERT(is_type_array(type));
  3677. Type *elem_type = base_array_type(type);
  3678. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3679. irValue *res = ir_add_local_generated(proc, type, false);
  3680. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  3681. i32 count = cast(i32)tl->Array.count;
  3682. if (inline_array_arith) {
  3683. // inline
  3684. for (i32 i = 0; i < count; i++) {
  3685. irValue *e = ir_emit_load(proc, ir_emit_array_epi(proc, val, i));
  3686. irValue *z = ir_emit_unary_arith(proc, op, e, elem_type);
  3687. ir_emit_store(proc, ir_emit_array_epi(proc, res, i), z);
  3688. }
  3689. } else {
  3690. auto loop_data = ir_loop_start(proc, count, t_i32);
  3691. irValue *e = ir_emit_load(proc, ir_emit_array_ep(proc, val, loop_data.idx));
  3692. irValue *z = ir_emit_unary_arith(proc, op, e, elem_type);
  3693. ir_emit_store(proc, ir_emit_array_ep(proc, res, loop_data.idx), z);
  3694. ir_loop_end(proc, loop_data);
  3695. }
  3696. ir_emit_comment(proc, str_lit("array.arith.end"));
  3697. return ir_emit_load(proc, res);
  3698. }
  3699. if (op == Token_Not) {
  3700. irValue *cmp = ir_emit_comp(proc, Token_CmpEq, x, v_false);
  3701. return ir_emit_conv(proc, cmp, type);
  3702. }
  3703. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  3704. Type *platform_type = integer_endian_type_to_platform_type(type);
  3705. irValue *v = ir_emit_byte_swap(proc, x, platform_type);
  3706. irValue *res = ir_emit(proc, ir_instr_unary_op(proc, op, v, platform_type));
  3707. return ir_emit_byte_swap(proc, res, type);
  3708. }
  3709. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  3710. Type *platform_type = integer_endian_type_to_platform_type(type);
  3711. irValue *v = ir_emit_byte_swap(proc, x, platform_type);
  3712. irValue *res = ir_emit(proc, ir_instr_unary_op(proc, op, v, platform_type));
  3713. return ir_emit_byte_swap(proc, res, type);
  3714. }
  3715. if (op == Token_Sub) {
  3716. if (is_type_integer(ir_type(x))) {
  3717. return ir_emit(proc, ir_instr_unary_op(proc, op, x, type));
  3718. } else if (is_type_float(ir_type(x))) {
  3719. return ir_emit(proc, ir_instr_unary_op(proc, op, x, type));
  3720. } else if (is_type_complex(ir_type(x))) {
  3721. irValue *addr = ir_add_local_generated(proc, ir_type(x), false);
  3722. irValue *v0 = ir_emit_struct_ev(proc, x, 0);
  3723. irValue *v1 = ir_emit_struct_ev(proc, x, 1);
  3724. v0 = ir_emit(proc, ir_instr_unary_op(proc, op, v0, ir_type(v0)));
  3725. v1 = ir_emit(proc, ir_instr_unary_op(proc, op, v1, ir_type(v1)));
  3726. ir_emit_store(proc, ir_emit_struct_ep(proc, addr, 0), v0);
  3727. ir_emit_store(proc, ir_emit_struct_ep(proc, addr, 1), v1);
  3728. return ir_emit_load(proc, addr);
  3729. } else if (is_type_quaternion(ir_type(x))) {
  3730. irValue *addr = ir_add_local_generated(proc, ir_type(x), false);
  3731. irValue *v0 = ir_emit_struct_ev(proc, x, 0);
  3732. irValue *v1 = ir_emit_struct_ev(proc, x, 1);
  3733. irValue *v2 = ir_emit_struct_ev(proc, x, 2);
  3734. irValue *v3 = ir_emit_struct_ev(proc, x, 3);
  3735. v0 = ir_emit(proc, ir_instr_unary_op(proc, op, v0, ir_type(v0)));
  3736. v1 = ir_emit(proc, ir_instr_unary_op(proc, op, v1, ir_type(v1)));
  3737. v2 = ir_emit(proc, ir_instr_unary_op(proc, op, v2, ir_type(v2)));
  3738. v3 = ir_emit(proc, ir_instr_unary_op(proc, op, v3, ir_type(v3)));
  3739. ir_emit_store(proc, ir_emit_struct_ep(proc, addr, 0), v0);
  3740. ir_emit_store(proc, ir_emit_struct_ep(proc, addr, 1), v1);
  3741. ir_emit_store(proc, ir_emit_struct_ep(proc, addr, 2), v2);
  3742. ir_emit_store(proc, ir_emit_struct_ep(proc, addr, 3), v3);
  3743. return ir_emit_load(proc, addr);
  3744. }
  3745. }
  3746. return ir_emit(proc, ir_instr_unary_op(proc, op, x, type));
  3747. }
  3748. irValue *ir_emit_arith(irProcedure *proc, TokenKind op, irValue *left, irValue *right, Type *type) {
  3749. Type *t_left = ir_type(left);
  3750. Type *t_right = ir_type(right);
  3751. if (is_type_array(t_left) || is_type_array(t_right)) {
  3752. ir_emit_comment(proc, str_lit("array.arith.begin"));
  3753. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  3754. left = ir_emit_conv(proc, left, type);
  3755. right = ir_emit_conv(proc, right, type);
  3756. irValue *lhs = ir_address_from_load_or_generate_local(proc, left);
  3757. irValue *rhs = ir_address_from_load_or_generate_local(proc, right);
  3758. GB_ASSERT(is_type_array(type));
  3759. Type *elem_type = base_array_type(type);
  3760. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3761. irValue *res = ir_add_local_generated(proc, type, false);
  3762. i64 count = base_type(type)->Array.count;
  3763. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  3764. if (inline_array_arith) {
  3765. // inline
  3766. for (i32 i = 0; i < count; i++) {
  3767. irValue *x_ptr = ir_emit_array_epi(proc, lhs, i);
  3768. irValue *y_ptr = ir_emit_array_epi(proc, rhs, i);
  3769. irValue *dst_ptr = ir_emit_array_epi(proc, res, i);
  3770. irValue *x = ir_emit_load(proc, x_ptr);
  3771. irValue *y = ir_emit_load(proc, y_ptr);
  3772. irValue *z = ir_emit_arith(proc, op, x, y, elem_type);
  3773. ir_emit_store(proc, dst_ptr, z);
  3774. }
  3775. } else {
  3776. auto loop_data = ir_loop_start(proc, count, t_i32);
  3777. irValue *x_ptr = ir_emit_array_ep(proc, lhs, loop_data.idx);
  3778. irValue *y_ptr = ir_emit_array_ep(proc, rhs, loop_data.idx);
  3779. irValue *dst_ptr = ir_emit_array_ep(proc, res, loop_data.idx);
  3780. irValue *x = ir_emit_load(proc, x_ptr);
  3781. irValue *y = ir_emit_load(proc, y_ptr);
  3782. irValue *z = ir_emit_arith(proc, op, x, y, elem_type);
  3783. ir_emit_store(proc, dst_ptr, z);
  3784. ir_loop_end(proc, loop_data);
  3785. }
  3786. ir_emit_comment(proc, str_lit("array.arith.end"));
  3787. return ir_emit_load(proc, res);
  3788. }
  3789. if (is_type_complex(t_left)) {
  3790. ir_emit_comment(proc, str_lit("complex.arith.begin"));
  3791. defer (ir_emit_comment(proc, str_lit("complex.arith.end")));
  3792. Type *ft = base_complex_elem_type(t_left);
  3793. if (op == Token_Quo) {
  3794. auto args = array_make<irValue *>(permanent_allocator(), 2);
  3795. args[0] = left;
  3796. args[1] = right;
  3797. switch (type_size_of(ft)) {
  3798. case 4: return ir_emit_runtime_call(proc, "quo_complex64", args);
  3799. case 8: return ir_emit_runtime_call(proc, "quo_complex128", args);
  3800. default: GB_PANIC("Unknown float type"); break;
  3801. }
  3802. }
  3803. irValue *res = ir_add_local_generated(proc, type, false); // NOTE: initialized in full later
  3804. irValue *a = ir_emit_struct_ev(proc, left, 0);
  3805. irValue *b = ir_emit_struct_ev(proc, left, 1);
  3806. irValue *c = ir_emit_struct_ev(proc, right, 0);
  3807. irValue *d = ir_emit_struct_ev(proc, right, 1);
  3808. irValue *real = nullptr;
  3809. irValue *imag = nullptr;
  3810. switch (op) {
  3811. case Token_Add:
  3812. real = ir_emit_arith(proc, Token_Add, a, c, ft);
  3813. imag = ir_emit_arith(proc, Token_Add, b, d, ft);
  3814. break;
  3815. case Token_Sub:
  3816. real = ir_emit_arith(proc, Token_Sub, a, c, ft);
  3817. imag = ir_emit_arith(proc, Token_Sub, b, d, ft);
  3818. break;
  3819. case Token_Mul: {
  3820. irValue *x = ir_emit_arith(proc, Token_Mul, a, c, ft);
  3821. irValue *y = ir_emit_arith(proc, Token_Mul, b, d, ft);
  3822. real = ir_emit_arith(proc, Token_Sub, x, y, ft);
  3823. irValue *z = ir_emit_arith(proc, Token_Mul, b, c, ft);
  3824. irValue *w = ir_emit_arith(proc, Token_Mul, a, d, ft);
  3825. imag = ir_emit_arith(proc, Token_Add, z, w, ft);
  3826. break;
  3827. }
  3828. }
  3829. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), real);
  3830. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), imag);
  3831. return ir_emit_load(proc, res);
  3832. }
  3833. if (is_type_quaternion(t_left)) {
  3834. ir_emit_comment(proc, str_lit("complex.arith.begin"));
  3835. defer (ir_emit_comment(proc, str_lit("complex.arith.end")));
  3836. right = ir_emit_conv(proc, right, t_left);
  3837. Type *ft = base_complex_elem_type(t_left);
  3838. if (op == Token_Add || op == Token_Sub) {
  3839. irValue *res = ir_add_local_generated(proc, type, false); // NOTE: initialized in full later
  3840. irValue *x0 = ir_emit_struct_ev(proc, left, 0);
  3841. irValue *x1 = ir_emit_struct_ev(proc, left, 1);
  3842. irValue *x2 = ir_emit_struct_ev(proc, left, 2);
  3843. irValue *x3 = ir_emit_struct_ev(proc, left, 3);
  3844. irValue *y0 = ir_emit_struct_ev(proc, right, 0);
  3845. irValue *y1 = ir_emit_struct_ev(proc, right, 1);
  3846. irValue *y2 = ir_emit_struct_ev(proc, right, 2);
  3847. irValue *y3 = ir_emit_struct_ev(proc, right, 3);
  3848. irValue *z0 = ir_emit_arith(proc, op, x0, y0, ft);
  3849. irValue *z1 = ir_emit_arith(proc, op, x1, y1, ft);
  3850. irValue *z2 = ir_emit_arith(proc, op, x2, y2, ft);
  3851. irValue *z3 = ir_emit_arith(proc, op, x3, y3, ft);
  3852. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), z0);
  3853. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), z1);
  3854. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 2), z2);
  3855. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 3), z3);
  3856. return ir_emit_load(proc, res);
  3857. } else if (op == Token_Mul) {
  3858. auto args = array_make<irValue *>(permanent_allocator(), 2);
  3859. args[0] = left;
  3860. args[1] = right;
  3861. switch (8*type_size_of(ft)) {
  3862. case 32: return ir_emit_runtime_call(proc, "mul_quaternion128", args);
  3863. case 64: return ir_emit_runtime_call(proc, "mul_quaternion256", args);
  3864. default: GB_PANIC("Unknown float type"); break;
  3865. }
  3866. } else if (op == Token_Quo) {
  3867. auto args = array_make<irValue *>(permanent_allocator(), 2);
  3868. args[0] = left;
  3869. args[1] = right;
  3870. switch (8*type_size_of(ft)) {
  3871. case 32: return ir_emit_runtime_call(proc, "quo_quaternion128", args);
  3872. case 64: return ir_emit_runtime_call(proc, "quo_quaternion256", args);
  3873. default: GB_PANIC("Unknown float type"); break;
  3874. }
  3875. }
  3876. }
  3877. #if 0
  3878. if (op == Token_Add) {
  3879. if (is_type_pointer(t_left)) {
  3880. irValue *ptr = ir_emit_conv(proc, left, type);
  3881. irValue *offset = right;
  3882. return ir_emit_ptr_offset(proc, ptr, offset);
  3883. } else if (is_type_pointer(ir_type(right))) {
  3884. irValue *ptr = ir_emit_conv(proc, right, type);
  3885. irValue *offset = left;
  3886. return ir_emit_ptr_offset(proc, ptr, offset);
  3887. }
  3888. } else if (op == Token_Sub) {
  3889. if (is_type_pointer(t_left) && is_type_integer(t_right)) {
  3890. // ptr - int
  3891. irValue *ptr = ir_emit_conv(proc, left, type);
  3892. irValue *offset = ir_emit_unary_arith(proc, Token_Sub, right, t_int);
  3893. return ir_emit_ptr_offset(proc, ptr, offset);
  3894. } else if (is_type_pointer(t_left) && is_type_pointer(t_right)) {
  3895. GB_ASSERT(is_type_integer(type));
  3896. irModule *m = proc->module;
  3897. Type *ptr_type = base_type(t_left);
  3898. GB_ASSERT(!is_type_rawptr(ptr_type));
  3899. irValue *elem_size = ir_const_int(type_size_of(ptr_type->Pointer.elem));
  3900. irValue *x = ir_emit_conv(proc, ir_emit_conv(proc, left, t_uintptr), type);
  3901. irValue *y = ir_emit_conv(proc, ir_emit_conv(proc, right, t_uintptr), type);
  3902. irValue *diff = ir_emit_arith(proc, op, x, y, type);
  3903. return ir_emit_arith(proc, Token_Quo, diff, elem_size, type);
  3904. }
  3905. }
  3906. #endif
  3907. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  3908. switch (op) {
  3909. case Token_AndNot:
  3910. case Token_And:
  3911. case Token_Or:
  3912. case Token_Xor:
  3913. goto handle_op;
  3914. }
  3915. Type *platform_type = integer_endian_type_to_platform_type(type);
  3916. irValue *x = ir_emit_conv(proc, left, integer_endian_type_to_platform_type(t_left));
  3917. irValue *y = ir_emit_conv(proc, right, integer_endian_type_to_platform_type(t_right));
  3918. irValue *res = ir_emit_arith(proc, op, x, y, platform_type);
  3919. return ir_emit_byte_swap(proc, res, type);
  3920. }
  3921. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  3922. Type *platform_type = integer_endian_type_to_platform_type(type);
  3923. irValue *x = ir_emit_conv(proc, left, integer_endian_type_to_platform_type(t_left));
  3924. irValue *y = ir_emit_conv(proc, right, integer_endian_type_to_platform_type(t_right));
  3925. irValue *res = ir_emit_arith(proc, op, x, y, platform_type);
  3926. return ir_emit_byte_swap(proc, res, type);
  3927. }
  3928. handle_op:
  3929. switch (op) {
  3930. case Token_Shl:
  3931. {
  3932. left = ir_emit_conv(proc, left, type);
  3933. right = ir_emit_conv(proc, right, type);
  3934. ir_emit(proc, ir_instr_binary_op(proc, op, left, right, type));
  3935. irValue *bits = right;
  3936. irValue *max = ir_value_constant(type, exact_value_i64(8*type_size_of(type) - 1));
  3937. irValue *less_equal_width = ir_emit(proc, ir_instr_binary_op(proc, Token_LtEq, bits, max, t_llvm_bool));
  3938. irValue *zero = ir_value_constant(type, exact_value_i64(0));
  3939. irValue *res = ir_emit(proc, ir_instr_binary_op(proc, op, left, bits, type));
  3940. return ir_emit_select(proc, less_equal_width, res, zero);
  3941. }
  3942. case Token_Shr:
  3943. {
  3944. left = ir_emit_conv(proc, left, type);
  3945. right = ir_emit_conv(proc, right, type);
  3946. bool is_unsigned = is_type_unsigned(ir_type(left));
  3947. irValue *bits = right;
  3948. irValue *max = ir_value_constant(type, exact_value_i64(8*type_size_of(type) - 1));
  3949. irValue *less_equal_width = ir_emit(proc, ir_instr_binary_op(proc, Token_LtEq, bits, max, t_llvm_bool));
  3950. bits = ir_emit_select(proc, less_equal_width, bits, max);
  3951. return ir_emit(proc, ir_instr_binary_op(proc, op, left, bits, type));
  3952. }
  3953. case Token_AndNot: {
  3954. // NOTE(bill): x &~ y == x & (~y) == x & (y ~ -1)
  3955. // NOTE(bill): "not" 'x' == 'x' "xor" '-1'
  3956. irValue *neg = ir_add_module_constant(proc->module, type, exact_value_i64(-1));
  3957. op = Token_Xor;
  3958. right = ir_emit_arith(proc, op, right, neg, type);
  3959. GB_ASSERT(right->Instr.kind == irInstr_BinaryOp);
  3960. right->Instr.BinaryOp.type = type;
  3961. op = Token_And;
  3962. } /* fallthrough */
  3963. case Token_Add:
  3964. case Token_Sub:
  3965. case Token_Mul:
  3966. case Token_Quo:
  3967. case Token_Mod:
  3968. case Token_ModMod:
  3969. case Token_And:
  3970. case Token_Or:
  3971. case Token_Xor:
  3972. left = ir_emit_conv(proc, left, type);
  3973. right = ir_emit_conv(proc, right, type);
  3974. break;
  3975. }
  3976. if (op == Token_ModMod) {
  3977. if (is_type_unsigned(type)) {
  3978. op = Token_Mod;
  3979. } else {
  3980. irValue *a = ir_emit_arith(proc, Token_Mod, left, right, type);
  3981. irValue *b = ir_emit_arith(proc, Token_Add, a, right, type);
  3982. return ir_emit_arith(proc, Token_Mod, b, right, type);
  3983. }
  3984. }
  3985. return ir_emit(proc, ir_instr_binary_op(proc, op, left, right, type));
  3986. }
  3987. irValue *ir_emit_union_tag_ptr(irProcedure *proc, irValue *u) {
  3988. Type *t = ir_type(u);
  3989. GB_ASSERT_MSG(is_type_pointer(t) &&
  3990. is_type_union(type_deref(t)), "%s", type_to_string(t));
  3991. irValue *tag_ptr = ir_emit(proc, ir_instr_union_tag_ptr(proc, u));
  3992. return tag_ptr;
  3993. }
  3994. irValue *ir_emit_union_tag_value(irProcedure *proc, irValue *u) {
  3995. Type *t = ir_type(u);
  3996. GB_ASSERT(is_type_union(t));
  3997. GB_ASSERT(are_types_identical(t, ir_type(u)));
  3998. return ir_emit(proc, ir_instr_union_tag_value(proc, u));
  3999. }
  4000. irValue *ir_emit_comp_against_nil(irProcedure *proc, TokenKind op_kind, irValue *x) {
  4001. Type *t = ir_type(x);
  4002. if (is_type_pointer(t)) {
  4003. return ir_emit_comp(proc, op_kind, x, v_raw_nil);
  4004. } else if (is_type_cstring(t)) {
  4005. irValue *ptr = ir_emit_conv(proc, x, t_u8_ptr);
  4006. return ir_emit_comp(proc, op_kind, ptr, v_raw_nil);
  4007. } else if (is_type_any(t)) {
  4008. // TODO(bill): is this correct behaviour for nil comparison for any?
  4009. irValue *data = ir_emit_struct_ev(proc, x, 0);
  4010. irValue *ti = ir_emit_struct_ev(proc, x, 1);
  4011. if (op_kind == Token_CmpEq) {
  4012. irValue *a = ir_emit_comp(proc, Token_CmpEq, data, v_raw_nil);
  4013. irValue *b = ir_emit_comp(proc, Token_CmpEq, ti, v_raw_nil);
  4014. return ir_emit_arith(proc, Token_Or, a, b, t_bool);
  4015. } else if (op_kind == Token_NotEq) {
  4016. irValue *a = ir_emit_comp(proc, Token_NotEq, data, v_raw_nil);
  4017. irValue *b = ir_emit_comp(proc, Token_NotEq, ti, v_raw_nil);
  4018. return ir_emit_arith(proc, Token_And, a, b, t_bool);
  4019. }
  4020. } else if (is_type_slice(t)) {
  4021. irValue *len = ir_emit_struct_ev(proc, x, 1);
  4022. return ir_emit_comp(proc, op_kind, len, v_zero);
  4023. } else if (is_type_dynamic_array(t)) {
  4024. irValue *cap = ir_emit_struct_ev(proc, x, 2);
  4025. return ir_emit_comp(proc, op_kind, cap, v_zero);
  4026. } else if (is_type_map(t)) {
  4027. irValue *cap = ir_map_cap(proc, x);
  4028. return ir_emit_comp(proc, op_kind, cap, v_zero);
  4029. } else if (is_type_union(t)) {
  4030. if (type_size_of(t) == 0) {
  4031. return ir_emit_comp(proc, op_kind, v_zero, v_zero);
  4032. } else if (is_type_union_maybe_pointer(t)) {
  4033. Type *bt = base_type(t);
  4034. irValue *ptr = ir_address_from_load_or_generate_local(proc, x);
  4035. ptr = ir_emit_bitcast(proc, ptr, alloc_type_pointer(bt->Union.variants[0]));
  4036. irValue *data = ir_emit_load(proc, ptr);
  4037. return ir_emit_comp_against_nil(proc, op_kind, data);
  4038. } else {
  4039. irValue *tag = ir_emit_union_tag_value(proc, x);
  4040. return ir_emit_comp(proc, op_kind, tag, v_zero);
  4041. }
  4042. } else if (is_type_typeid(t)) {
  4043. irValue *invalid_typeid = ir_value_constant(t_typeid, exact_value_i64(0));
  4044. return ir_emit_comp(proc, op_kind, x, invalid_typeid);
  4045. } else if (is_type_bit_field(t)) {
  4046. auto args = array_make<irValue *>(permanent_allocator(), 2);
  4047. irValue *lhs = ir_address_from_load_or_generate_local(proc, x);
  4048. args[0] = ir_emit_conv(proc, lhs, t_rawptr);
  4049. args[1] = ir_const_int(type_size_of(t));
  4050. irValue *val = ir_emit_runtime_call(proc, "memory_compare_zero", args);
  4051. irValue *res = ir_emit_comp(proc, op_kind, val, v_zero);
  4052. return ir_emit_conv(proc, res, t_bool);
  4053. } else if (is_type_soa_struct(t)) {
  4054. Type *bt = base_type(t);
  4055. if (bt->Struct.soa_kind == StructSoa_Slice) {
  4056. ir_emit_comment(proc, str_lit("soa-slice-nil-comp"));
  4057. irValue *len = ir_soa_struct_len(proc, x);
  4058. return ir_emit_comp(proc, op_kind, len, v_zero);
  4059. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  4060. ir_emit_comment(proc, str_lit("soa-dynamic-array-nil-comp"));
  4061. irValue *cap = ir_soa_struct_cap(proc, x);
  4062. return ir_emit_comp(proc, op_kind, cap, v_zero);
  4063. }
  4064. } else if (is_type_struct(t) && type_has_nil(t)) {
  4065. auto args = array_make<irValue *>(permanent_allocator(), 2);
  4066. irValue *lhs = ir_address_from_load_or_generate_local(proc, x);
  4067. args[0] = ir_emit_conv(proc, lhs, t_rawptr);
  4068. args[1] = ir_const_int(type_size_of(t));
  4069. irValue *val = ir_emit_runtime_call(proc, "memory_compare_zero", args);
  4070. irValue *res = ir_emit_comp(proc, op_kind, val, v_zero);
  4071. return ir_emit_conv(proc, res, t_bool);
  4072. }
  4073. return nullptr;
  4074. }
  4075. irValue *ir_get_equal_proc_for_type(irModule *m, Type *type) {
  4076. Type *original_type = type;
  4077. type = base_type(type);
  4078. Type *pt = alloc_type_pointer(type);
  4079. auto key = hash_type(type);
  4080. irValue **found = map_get(&m->equal_procs, key);
  4081. if (found) {
  4082. return *found;
  4083. }
  4084. static u32 proc_index = 0;
  4085. char buf[16] = {};
  4086. isize n = gb_snprintf(buf, 16, "__$equal%u", ++proc_index);
  4087. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  4088. String proc_name = make_string_c(str);
  4089. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  4090. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(proc_name), t_equal_proc, 0);
  4091. e->Procedure.link_name = proc_name;
  4092. irValue *p = ir_value_procedure(m, e, t_equal_proc, nullptr, body, proc_name);
  4093. map_set(&m->values, hash_entity(e), p);
  4094. string_map_set(&m->members, proc_name, p);
  4095. map_set(&m->equal_procs, key, p);
  4096. irProcedure *proc = &p->Proc;
  4097. proc->is_startup = true;
  4098. proc->ignore_dead_instr = true;
  4099. ir_begin_procedure_body(proc);
  4100. // ir_start_block(proc, proc->decl_block);
  4101. GB_ASSERT(proc->curr_block != nullptr);
  4102. irValue *x = proc->params[0];
  4103. irValue *y = proc->params[1];
  4104. irValue *lhs = ir_emit_conv(proc, x, pt);
  4105. irValue *rhs = ir_emit_conv(proc, y, pt);
  4106. irBlock *block_same_ptr = ir_new_block(proc, nullptr, "same_ptr");
  4107. irBlock *block_diff_ptr = ir_new_block(proc, nullptr, "diff_ptr");
  4108. irValue *same_ptr = ir_emit_comp(proc, Token_CmpEq, lhs, rhs);
  4109. ir_emit_if(proc, same_ptr, block_same_ptr, block_diff_ptr);
  4110. ir_start_block(proc, block_same_ptr);
  4111. ir_emit(proc, ir_instr_return(proc, ir_const_bool(true)));
  4112. ir_start_block(proc, block_diff_ptr);
  4113. if (type->kind == Type_Struct) {
  4114. type_set_offsets(type);
  4115. irBlock *done = ir_new_block(proc, nullptr, "done"); // NOTE(bill): Append later
  4116. irBlock *block_false = ir_new_block(proc, nullptr, "bfalse");
  4117. for_array(i, type->Struct.fields) {
  4118. irBlock *next_block = ir_new_block(proc, nullptr, "btrue");
  4119. irValue *pleft = ir_emit_struct_ep(proc, lhs, cast(i32)i);
  4120. irValue *pright = ir_emit_struct_ep(proc, rhs, cast(i32)i);
  4121. irValue *left = ir_emit_load(proc, pleft);
  4122. irValue *right = ir_emit_load(proc, pright);
  4123. irValue *ok = ir_emit_comp(proc, Token_CmpEq, left, right);
  4124. ir_emit_if(proc, ok, next_block, block_false);
  4125. ir_emit_jump(proc, next_block);
  4126. ir_start_block(proc, next_block);
  4127. }
  4128. ir_emit_jump(proc, done);
  4129. ir_start_block(proc, block_false);
  4130. ir_emit(proc, ir_instr_return(proc, ir_const_bool(false)));
  4131. ir_emit_jump(proc, done);
  4132. ir_start_block(proc, done);
  4133. ir_emit(proc, ir_instr_return(proc, ir_const_bool(true)));
  4134. } else {
  4135. irValue *left = ir_emit_load(proc, lhs);
  4136. irValue *right = ir_emit_load(proc, rhs);
  4137. irValue *ok = ir_emit_comp(proc, Token_CmpEq, left, right);
  4138. ok = ir_emit_conv(proc, ok, t_bool);
  4139. ir_emit(proc, ir_instr_return(proc, ok));
  4140. }
  4141. ir_end_procedure_body(proc);
  4142. return p;
  4143. }
  4144. irValue *ir_simple_compare_hash(irProcedure *p, Type *type, irValue *data, irValue *seed) {
  4145. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  4146. i64 sz = type_size_of(type);
  4147. if (1 <= sz && sz <= 16) {
  4148. char name[20] = {};
  4149. gb_snprintf(name, 20, "default_hasher%d", cast(i32)sz);
  4150. auto args = array_make<irValue *>(permanent_allocator(), 2);
  4151. args[0] = data;
  4152. args[1] = seed;
  4153. return ir_emit_runtime_call(p, name, args);
  4154. }
  4155. auto args = array_make<irValue *>(permanent_allocator(), 3);
  4156. args[0] = data;
  4157. args[1] = seed;
  4158. args[2] = ir_const_int(type_size_of(type));
  4159. return ir_emit_runtime_call(p, "default_hasher_n", args);
  4160. }
  4161. irValue *ir_get_hasher_proc_for_type(irModule *m, Type *type) {
  4162. Type *original_type = type;
  4163. type = core_type(type);
  4164. Type *pt = alloc_type_pointer(type);
  4165. GB_ASSERT(is_type_valid_for_keys(type));
  4166. auto key = hash_type(type);
  4167. irValue **found = map_get(&m->hasher_procs, key);
  4168. if (found) {
  4169. return *found;
  4170. }
  4171. static u32 proc_index = 0;
  4172. char buf[16] = {};
  4173. isize n = gb_snprintf(buf, 16, "__$hasher%u", ++proc_index);
  4174. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  4175. String proc_name = make_string_c(str);
  4176. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  4177. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(proc_name), t_hasher_proc, 0);
  4178. e->Procedure.link_name = proc_name;
  4179. irValue *p = ir_value_procedure(m, e, t_hasher_proc, nullptr, body, proc_name);
  4180. map_set(&m->values, hash_entity(e), p);
  4181. string_map_set(&m->members, proc_name, p);
  4182. map_set(&m->hasher_procs, key, p);
  4183. irProcedure *proc = &p->Proc;
  4184. proc->is_startup = true;
  4185. proc->ignore_dead_instr = true;
  4186. ir_begin_procedure_body(proc);
  4187. defer (ir_end_procedure_body(proc));
  4188. // ir_start_block(proc, proc->decl_block);
  4189. GB_ASSERT(proc->curr_block != nullptr);
  4190. irValue *data = proc->params[0];
  4191. irValue *seed = proc->params[1];
  4192. if (is_type_simple_compare(type)) {
  4193. irValue *res = ir_simple_compare_hash(proc, type, data, seed);
  4194. ir_emit(proc, ir_instr_return(proc, res));
  4195. return p;
  4196. }
  4197. if (is_type_cstring(type)) {
  4198. auto args = array_make<irValue *>(permanent_allocator(), 2);
  4199. args[0] = data;
  4200. args[1] = seed;
  4201. irValue *res = ir_emit_runtime_call(proc, "default_hasher_cstring", args);
  4202. ir_emit(proc, ir_instr_return(proc, res));
  4203. } else if (is_type_string(type)) {
  4204. auto args = array_make<irValue *>(permanent_allocator(), 2);
  4205. args[0] = data;
  4206. args[1] = seed;
  4207. irValue *res = ir_emit_runtime_call(proc, "default_hasher_string", args);
  4208. ir_emit(proc, ir_instr_return(proc, res));
  4209. } else if (type->kind == Type_Struct) {
  4210. type_set_offsets(type);
  4211. data = ir_emit_conv(proc, data, t_u8_ptr);
  4212. auto args = array_make<irValue *>(permanent_allocator(), 2);
  4213. for_array(i, type->Struct.fields) {
  4214. i64 offset = type->Struct.offsets[i];
  4215. Entity *field = type->Struct.fields[i];
  4216. irValue *field_hasher = ir_get_hasher_proc_for_type(m, field->type);
  4217. irValue *ptr = ir_emit_ptr_offset(proc, data, ir_const_uintptr(offset));
  4218. args[0] = ptr;
  4219. args[1] = seed;
  4220. seed = ir_emit_call(proc, field_hasher, args);
  4221. }
  4222. ir_emit(proc, ir_instr_return(proc, seed));
  4223. } else if (type->kind == Type_Array) {
  4224. irValue *pres = ir_add_local_generated(proc, t_uintptr, false);
  4225. ir_emit_store(proc, pres, seed);
  4226. auto args = array_make<irValue *>(permanent_allocator(), 2);
  4227. irValue *elem_hasher = ir_get_hasher_proc_for_type(m, type->Array.elem);
  4228. auto loop_data = ir_loop_start(proc, type->Array.count, t_i32);
  4229. data = ir_emit_conv(proc, data, pt);
  4230. irValue *ptr = ir_emit_array_ep(proc, data, loop_data.idx);
  4231. args[0] = ptr;
  4232. args[1] = ir_emit_load(proc, pres);
  4233. irValue *new_seed = ir_emit_call(proc, elem_hasher, args);
  4234. ir_emit_store(proc, pres, new_seed);
  4235. ir_loop_end(proc, loop_data);
  4236. irValue *res = ir_emit_load(proc, pres);
  4237. ir_emit(proc, ir_instr_return(proc, res));
  4238. } else if (type->kind == Type_EnumeratedArray) {
  4239. irValue *pres = ir_add_local_generated(proc, t_uintptr, false);
  4240. ir_emit_store(proc, pres, seed);
  4241. auto args = array_make<irValue *>(permanent_allocator(), 2);
  4242. irValue *elem_hasher = ir_get_hasher_proc_for_type(m, type->Array.elem);
  4243. auto loop_data = ir_loop_start(proc, type->Array.count, t_i32);
  4244. data = ir_emit_conv(proc, data, pt);
  4245. irValue *ptr = ir_emit_array_ep(proc, data, loop_data.idx);
  4246. args[0] = ptr;
  4247. args[1] = ir_emit_load(proc, pres);
  4248. irValue *new_seed = ir_emit_call(proc, elem_hasher, args);
  4249. ir_emit_store(proc, pres, new_seed);
  4250. ir_loop_end(proc, loop_data);
  4251. irValue *res = ir_emit_load(proc, pres);
  4252. ir_emit(proc, ir_instr_return(proc, res));
  4253. } else {
  4254. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  4255. }
  4256. return p;
  4257. }
  4258. irValue *ir_emit_comp(irProcedure *proc, TokenKind op_kind, irValue *left, irValue *right) {
  4259. Type *a = base_type(ir_type(left));
  4260. Type *b = base_type(ir_type(right));
  4261. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  4262. irValue *nil_check = nullptr;
  4263. if (left->kind == irValue_Nil) {
  4264. nil_check = ir_emit_comp_against_nil(proc, op_kind, right);
  4265. } else if (right->kind == irValue_Nil) {
  4266. nil_check = ir_emit_comp_against_nil(proc, op_kind, left);
  4267. }
  4268. if (nil_check != nullptr) {
  4269. return nil_check;
  4270. }
  4271. if (are_types_identical(a, b)) {
  4272. // NOTE(bill): No need for a conversion
  4273. } else if (left->kind == irValue_Constant || left->kind == irValue_Nil) {
  4274. left = ir_emit_conv(proc, left, ir_type(right));
  4275. } else if (right->kind == irValue_Constant || right->kind == irValue_Nil) {
  4276. right = ir_emit_conv(proc, right, ir_type(left));
  4277. } else {
  4278. gbAllocator a = ir_allocator();
  4279. Type *lt = ir_type(left);
  4280. Type *rt = ir_type(right);
  4281. if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  4282. Type *blt = base_type(lt);
  4283. Type *brt = base_type(rt);
  4284. GB_ASSERT(is_type_bit_field_value(blt));
  4285. GB_ASSERT(is_type_bit_field_value(brt));
  4286. i64 bits = gb_max(blt->BitFieldValue.bits, brt->BitFieldValue.bits);
  4287. i64 bytes = bits / 8;
  4288. switch (bytes) {
  4289. case 1:
  4290. left = ir_emit_conv(proc, left, t_u8);
  4291. right = ir_emit_conv(proc, right, t_u8);
  4292. break;
  4293. case 2:
  4294. left = ir_emit_conv(proc, left, t_u16);
  4295. right = ir_emit_conv(proc, right, t_u16);
  4296. break;
  4297. case 4:
  4298. left = ir_emit_conv(proc, left, t_u32);
  4299. right = ir_emit_conv(proc, right, t_u32);
  4300. break;
  4301. case 8:
  4302. left = ir_emit_conv(proc, left, t_u64);
  4303. right = ir_emit_conv(proc, right, t_u64);
  4304. break;
  4305. default: GB_PANIC("Unknown integer size"); break;
  4306. }
  4307. }
  4308. lt = ir_type(left);
  4309. rt = ir_type(right);
  4310. i64 ls = type_size_of(lt);
  4311. i64 rs = type_size_of(rt);
  4312. if (ls < rs) {
  4313. left = ir_emit_conv(proc, left, rt);
  4314. } else if (ls > rs) {
  4315. right = ir_emit_conv(proc, right, lt);
  4316. } else {
  4317. right = ir_emit_conv(proc, right, lt);
  4318. }
  4319. }
  4320. if (is_type_array(a)) {
  4321. ir_emit_comment(proc, str_lit("array.comp.begin"));
  4322. defer (ir_emit_comment(proc, str_lit("array.comp.end")));
  4323. Type *tl = base_type(a);
  4324. irValue *lhs = ir_address_from_load_or_generate_local(proc, left);
  4325. irValue *rhs = ir_address_from_load_or_generate_local(proc, right);
  4326. TokenKind cmp_op = Token_And;
  4327. irValue *res = v_true;
  4328. if (op_kind == Token_NotEq) {
  4329. res = v_false;
  4330. cmp_op = Token_Or;
  4331. } else if (op_kind == Token_CmpEq) {
  4332. res = v_true;
  4333. cmp_op = Token_And;
  4334. }
  4335. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  4336. i32 count = cast(i32)tl->Array.count;
  4337. if (inline_array_arith) {
  4338. // inline
  4339. irValue *val = ir_add_local_generated(proc, t_bool, false);
  4340. ir_emit_store(proc, val, res);
  4341. for (i32 i = 0; i < count; i++) {
  4342. irValue *x = ir_emit_load(proc, ir_emit_array_epi(proc, lhs, i));
  4343. irValue *y = ir_emit_load(proc, ir_emit_array_epi(proc, rhs, i));
  4344. irValue *cmp = ir_emit_comp(proc, op_kind, x, y);
  4345. irValue *new_res = ir_emit_arith(proc, cmp_op, ir_emit_load(proc, val), cmp, t_bool);
  4346. ir_emit_store(proc, val, ir_emit_conv(proc, new_res, t_bool));
  4347. }
  4348. return ir_emit_load(proc, val);
  4349. } else {
  4350. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  4351. // TODO(bill): Test to see if this is actually faster!!!!
  4352. auto args = array_make<irValue *>(permanent_allocator(), 3);
  4353. args[0] = ir_emit_conv(proc, lhs, t_rawptr);
  4354. args[1] = ir_emit_conv(proc, rhs, t_rawptr);
  4355. args[2] = ir_const_int(type_size_of(tl));
  4356. irValue *val = ir_emit_runtime_call(proc, "memory_compare", args);
  4357. irValue *res = ir_emit_comp(proc, op_kind, val, v_zero);
  4358. return ir_emit_conv(proc, res, t_bool);
  4359. } else {
  4360. irValue *val = ir_add_local_generated(proc, t_bool, false);
  4361. ir_emit_store(proc, val, res);
  4362. auto loop_data = ir_loop_start(proc, count, t_i32);
  4363. {
  4364. irValue *i = loop_data.idx;
  4365. irValue *x = ir_emit_load(proc, ir_emit_array_ep(proc, lhs, i));
  4366. irValue *y = ir_emit_load(proc, ir_emit_array_ep(proc, rhs, i));
  4367. irValue *cmp = ir_emit_comp(proc, op_kind, x, y);
  4368. irValue *new_res = ir_emit_arith(proc, cmp_op, ir_emit_load(proc, val), cmp, t_bool);
  4369. ir_emit_store(proc, val, ir_emit_conv(proc, new_res, t_bool));
  4370. }
  4371. ir_loop_end(proc, loop_data);
  4372. return ir_emit_load(proc, val);
  4373. }
  4374. }
  4375. }
  4376. if (is_type_struct(a) && is_type_comparable(a)) {
  4377. irValue *left_ptr = ir_address_from_load_or_generate_local(proc, left);
  4378. irValue *right_ptr = ir_address_from_load_or_generate_local(proc, right);
  4379. irValue *res = {};
  4380. if (is_type_simple_compare(a)) {
  4381. // TODO(bill): Test to see if this is actually faster!!!!
  4382. auto args = array_make<irValue *>(permanent_allocator(), 3);
  4383. args[0] = ir_emit_conv(proc, left_ptr, t_rawptr);
  4384. args[1] = ir_emit_conv(proc, right_ptr, t_rawptr);
  4385. args[2] = ir_const_int(type_size_of(a));
  4386. res = ir_emit_runtime_call(proc, "memory_equal", args);
  4387. } else {
  4388. irValue *value = ir_get_equal_proc_for_type(proc->module, a);
  4389. auto args = array_make<irValue *>(permanent_allocator(), 2);
  4390. args[0] = ir_emit_conv(proc, left_ptr, t_rawptr);
  4391. args[1] = ir_emit_conv(proc, right_ptr, t_rawptr);
  4392. res = ir_emit_call(proc, value, args);
  4393. }
  4394. if (op_kind == Token_NotEq) {
  4395. res = ir_emit_unary_arith(proc, Token_Not, res, ir_type(res));
  4396. }
  4397. return res;
  4398. }
  4399. if (is_type_string(a)) {
  4400. if (is_type_cstring(a)) {
  4401. left = ir_emit_conv(proc, left, t_string);
  4402. right = ir_emit_conv(proc, right, t_string);
  4403. }
  4404. char const *runtime_proc = nullptr;
  4405. switch (op_kind) {
  4406. case Token_CmpEq: runtime_proc = "string_eq"; break;
  4407. case Token_NotEq: runtime_proc = "string_ne"; break;
  4408. case Token_Lt: runtime_proc = "string_lt"; break;
  4409. case Token_Gt: runtime_proc = "string_gt"; break;
  4410. case Token_LtEq: runtime_proc = "string_le"; break;
  4411. case Token_GtEq: runtime_proc = "string_gt"; break;
  4412. }
  4413. GB_ASSERT(runtime_proc != nullptr);
  4414. auto args = array_make<irValue *>(ir_allocator(), 2);
  4415. args[0] = left;
  4416. args[1] = right;
  4417. return ir_emit_runtime_call(proc, runtime_proc, args);
  4418. }
  4419. if (is_type_complex(a)) {
  4420. char const *runtime_proc = "";
  4421. i64 sz = 8*type_size_of(a);
  4422. switch (sz) {
  4423. case 64:
  4424. switch (op_kind) {
  4425. case Token_CmpEq: runtime_proc = "complex64_eq"; break;
  4426. case Token_NotEq: runtime_proc = "complex64_ne"; break;
  4427. }
  4428. break;
  4429. case 128:
  4430. switch (op_kind) {
  4431. case Token_CmpEq: runtime_proc = "complex128_eq"; break;
  4432. case Token_NotEq: runtime_proc = "complex128_ne"; break;
  4433. }
  4434. break;
  4435. }
  4436. GB_ASSERT(runtime_proc != nullptr);
  4437. auto args = array_make<irValue *>(ir_allocator(), 2);
  4438. args[0] = left;
  4439. args[1] = right;
  4440. return ir_emit_runtime_call(proc, runtime_proc, args);
  4441. }
  4442. if (is_type_quaternion(a)) {
  4443. char const *runtime_proc = "";
  4444. i64 sz = 8*type_size_of(a);
  4445. switch (sz) {
  4446. case 128:
  4447. switch (op_kind) {
  4448. case Token_CmpEq: runtime_proc = "quaternion128_eq"; break;
  4449. case Token_NotEq: runtime_proc = "quaternion128_ne"; break;
  4450. }
  4451. break;
  4452. case 256:
  4453. switch (op_kind) {
  4454. case Token_CmpEq: runtime_proc = "quaternion256_eq"; break;
  4455. case Token_NotEq: runtime_proc = "quaternion256_ne"; break;
  4456. }
  4457. break;
  4458. }
  4459. GB_ASSERT(runtime_proc != nullptr);
  4460. auto args = array_make<irValue *>(ir_allocator(), 2);
  4461. args[0] = left;
  4462. args[1] = right;
  4463. return ir_emit_runtime_call(proc, runtime_proc, args);
  4464. }
  4465. if (is_type_bit_set(a)) {
  4466. switch (op_kind) {
  4467. case Token_Lt:
  4468. case Token_LtEq:
  4469. case Token_Gt:
  4470. case Token_GtEq:
  4471. {
  4472. Type *it = bit_set_to_int(a);
  4473. irValue *lhs = ir_emit_bitcast(proc, left, it);
  4474. irValue *rhs = ir_emit_bitcast(proc, right, it);
  4475. irValue *res = ir_emit_arith(proc, Token_And, lhs, rhs, it);
  4476. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  4477. // (lhs & rhs) == lhs
  4478. res = ir_emit(proc, ir_instr_binary_op(proc, Token_CmpEq, res, lhs, t_llvm_bool));
  4479. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  4480. // (lhs & rhs) == rhs
  4481. res = ir_emit(proc, ir_instr_binary_op(proc, Token_CmpEq, res, rhs, t_llvm_bool));
  4482. }
  4483. // NOTE(bill): Strict subsets
  4484. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  4485. // res &~ (lhs == rhs)
  4486. irValue *eq = ir_emit(proc, ir_instr_binary_op(proc, Token_CmpEq, lhs, rhs, t_llvm_bool));
  4487. res = ir_emit_arith(proc, Token_AndNot, res, eq, t_llvm_bool);
  4488. }
  4489. return res;
  4490. }
  4491. }
  4492. }
  4493. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  4494. Type *t = ir_type(left);
  4495. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  4496. Type *platform_type = integer_endian_type_to_platform_type(t);
  4497. irValue *x = ir_emit_byte_swap(proc, left, platform_type);
  4498. irValue *y = ir_emit_byte_swap(proc, right, platform_type);
  4499. return ir_emit(proc, ir_instr_binary_op(proc, op_kind, x, y, t_llvm_bool));
  4500. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  4501. Type *platform_type = integer_endian_type_to_platform_type(t);
  4502. irValue *x = ir_emit_conv(proc, left, platform_type);
  4503. irValue *y = ir_emit_conv(proc, right, platform_type);
  4504. return ir_emit(proc, ir_instr_binary_op(proc, op_kind, x, y, t_llvm_bool));
  4505. }
  4506. }
  4507. return ir_emit(proc, ir_instr_binary_op(proc, op_kind, left, right, t_llvm_bool));
  4508. }
  4509. irValue *ir_emit_array_ep(irProcedure *proc, irValue *s, irValue *index) {
  4510. GB_ASSERT(index != nullptr);
  4511. Type *t = ir_type(s);
  4512. GB_ASSERT(is_type_pointer(t));
  4513. Type *st = base_type(type_deref(t));
  4514. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  4515. // NOTE(bill): For some weird legacy reason in LLVM, structure elements must be accessed as an i32
  4516. index = ir_emit_conv(proc, index, t_i32);
  4517. return ir_emit(proc, ir_instr_array_element_ptr(proc, s, index));
  4518. }
  4519. irValue *ir_emit_array_epi(irProcedure *proc, irValue *s, i32 index) {
  4520. return ir_emit_array_ep(proc, s, ir_const_i32(index));
  4521. }
  4522. irValue *ir_emit_struct_ep(irProcedure *proc, irValue *s, i32 index) {
  4523. gbAllocator a = ir_allocator();
  4524. GB_ASSERT(is_type_pointer(ir_type(s)));
  4525. Type *t = base_type(type_deref(ir_type(s)));
  4526. Type *result_type = nullptr;
  4527. if (t->kind == Type_Opaque) {
  4528. t = t->Opaque.elem;
  4529. }
  4530. if (is_type_relative_pointer(t)) {
  4531. s = ir_addr_get_ptr(proc, ir_addr(s));
  4532. }
  4533. if (is_type_struct(t)) {
  4534. result_type = alloc_type_pointer(t->Struct.fields[index]->type);
  4535. } else if (is_type_union(t)) {
  4536. GB_ASSERT(index == -1);
  4537. return ir_emit_union_tag_ptr(proc, s);
  4538. } else if (is_type_tuple(t)) {
  4539. GB_ASSERT(t->Tuple.variables.count > 0);
  4540. result_type = alloc_type_pointer(t->Tuple.variables[index]->type);
  4541. } else if (is_type_complex(t)) {
  4542. Type *ft = base_complex_elem_type(t);
  4543. switch (index) {
  4544. case 0: result_type = alloc_type_pointer(ft); break;
  4545. case 1: result_type = alloc_type_pointer(ft); break;
  4546. }
  4547. } else if (is_type_quaternion(t)) {
  4548. Type *ft = base_complex_elem_type(t);
  4549. switch (index) {
  4550. case 0: result_type = alloc_type_pointer(ft); break;
  4551. case 1: result_type = alloc_type_pointer(ft); break;
  4552. case 2: result_type = alloc_type_pointer(ft); break;
  4553. case 3: result_type = alloc_type_pointer(ft); break;
  4554. }
  4555. } else if (is_type_slice(t)) {
  4556. switch (index) {
  4557. case 0: result_type = alloc_type_pointer(alloc_type_pointer(t->Slice.elem)); break;
  4558. case 1: result_type = alloc_type_pointer(t_int); break;
  4559. }
  4560. } else if (is_type_string(t)) {
  4561. switch (index) {
  4562. case 0: result_type = alloc_type_pointer(t_u8_ptr); break;
  4563. case 1: result_type = alloc_type_pointer(t_int); break;
  4564. }
  4565. } else if (is_type_any(t)) {
  4566. switch (index) {
  4567. case 0: result_type = alloc_type_pointer(t_rawptr); break;
  4568. case 1: result_type = alloc_type_pointer(t_typeid); break;
  4569. }
  4570. } else if (is_type_dynamic_array(t)) {
  4571. switch (index) {
  4572. case 0: result_type = alloc_type_pointer(alloc_type_pointer(t->DynamicArray.elem)); break;
  4573. case 1: result_type = t_int_ptr; break;
  4574. case 2: result_type = t_int_ptr; break;
  4575. case 3: result_type = t_allocator_ptr; break;
  4576. }
  4577. } else if (is_type_map(t)) {
  4578. init_map_internal_types(t);
  4579. Type *itp = alloc_type_pointer(t->Map.internal_type);
  4580. s = ir_emit_transmute(proc, s, itp);
  4581. Type *gst = t->Map.internal_type;
  4582. GB_ASSERT(gst->kind == Type_Struct);
  4583. switch (index) {
  4584. case 0: result_type = alloc_type_pointer(gst->Struct.fields[0]->type); break;
  4585. case 1: result_type = alloc_type_pointer(gst->Struct.fields[1]->type); break;
  4586. }
  4587. } else if (is_type_array(t)) {
  4588. return ir_emit_array_epi(proc, s, index);
  4589. } else if (is_type_relative_slice(t)) {
  4590. switch (index) {
  4591. case 0: result_type = alloc_type_pointer(t->RelativeSlice.base_integer); break;
  4592. case 1: result_type = alloc_type_pointer(t->RelativeSlice.base_integer); break;
  4593. }
  4594. } else {
  4595. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(ir_type(s)), index);
  4596. }
  4597. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  4598. return ir_emit(proc, ir_instr_struct_element_ptr(proc, s, index, result_type));
  4599. }
  4600. irValue *ir_emit_struct_ev(irProcedure *proc, irValue *s, i32 index) {
  4601. // NOTE(bill): For some weird legacy reason in LLVM, structure elements must be accessed as an i32
  4602. if (s->kind == irValue_Instr) {
  4603. if (s->Instr.kind == irInstr_Load) {
  4604. irValue *addr = s->Instr.Load.address;
  4605. irValue *ptr = ir_emit_struct_ep(proc, addr, index);
  4606. return ir_emit_load(proc, ptr);
  4607. }
  4608. }
  4609. gbAllocator a = ir_allocator();
  4610. Type *t = base_type(ir_type(s));
  4611. Type *result_type = nullptr;
  4612. switch (t->kind) {
  4613. case Type_Basic:
  4614. switch (t->Basic.kind) {
  4615. case Basic_string:
  4616. switch (index) {
  4617. case 0: result_type = t_u8_ptr; break;
  4618. case 1: result_type = t_int; break;
  4619. }
  4620. break;
  4621. case Basic_any:
  4622. switch (index) {
  4623. case 0: result_type = t_rawptr; break;
  4624. case 1: result_type = t_typeid; break;
  4625. }
  4626. break;
  4627. case Basic_complex64: case Basic_complex128:
  4628. {
  4629. Type *ft = base_complex_elem_type(t);
  4630. switch (index) {
  4631. case 0: result_type = ft; break;
  4632. case 1: result_type = ft; break;
  4633. }
  4634. break;
  4635. }
  4636. case Basic_quaternion128: case Basic_quaternion256:
  4637. {
  4638. Type *ft = base_complex_elem_type(t);
  4639. switch (index) {
  4640. case 0: result_type = ft; break;
  4641. case 1: result_type = ft; break;
  4642. case 2: result_type = ft; break;
  4643. case 3: result_type = ft; break;
  4644. }
  4645. break;
  4646. }
  4647. }
  4648. break;
  4649. case Type_Struct:
  4650. result_type = t->Struct.fields[index]->type;
  4651. break;
  4652. case Type_Union:
  4653. GB_ASSERT(index == -1);
  4654. return ir_emit_union_tag_value(proc, s);
  4655. case Type_Tuple:
  4656. GB_ASSERT(t->Tuple.variables.count > 0);
  4657. result_type = t->Tuple.variables[index]->type;
  4658. break;
  4659. case Type_Slice:
  4660. switch (index) {
  4661. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  4662. case 1: result_type = t_int; break;
  4663. }
  4664. break;
  4665. case Type_DynamicArray:
  4666. switch (index) {
  4667. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  4668. case 1: result_type = t_int; break;
  4669. case 2: result_type = t_int; break;
  4670. case 3: result_type = t_allocator; break;
  4671. }
  4672. break;
  4673. case Type_Map:
  4674. {
  4675. init_map_internal_types(t);
  4676. Type *gst = t->Map.generated_struct_type;
  4677. switch (index) {
  4678. case 0: result_type = gst->Struct.fields[0]->type; break;
  4679. case 1: result_type = gst->Struct.fields[1]->type; break;
  4680. }
  4681. }
  4682. break;
  4683. case Type_Array:
  4684. result_type = t->Array.elem;
  4685. break;
  4686. default:
  4687. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(ir_type(s)), index);
  4688. break;
  4689. }
  4690. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(ir_type(s)), index);
  4691. return ir_emit(proc, ir_instr_struct_extract_value(proc, s, index, result_type));
  4692. }
  4693. irValue *ir_emit_deep_field_gep(irProcedure *proc, irValue *e, Selection sel) {
  4694. GB_ASSERT(sel.index.count > 0);
  4695. Type *type = type_deref(ir_type(e));
  4696. gbAllocator a = ir_allocator();
  4697. for_array(i, sel.index) {
  4698. i32 index = cast(i32)sel.index[i];
  4699. if (is_type_pointer(type)) {
  4700. type = type_deref(type);
  4701. e = ir_emit_load(proc, e);
  4702. // e = ir_emit_ptr_offset(proc, e, v_zero); // TODO(bill): Do I need these copies?
  4703. }
  4704. type = core_type(type);
  4705. if (type->kind == Type_Opaque) {
  4706. type = type->Opaque.elem;
  4707. }
  4708. if (is_type_quaternion(type)) {
  4709. e = ir_emit_struct_ep(proc, e, index);
  4710. } else if (is_type_raw_union(type)) {
  4711. type = type->Struct.fields[index]->type;
  4712. GB_ASSERT(is_type_pointer(ir_type(e)));
  4713. e = ir_emit_bitcast(proc, e, alloc_type_pointer(type));
  4714. } else if (is_type_struct(type)) {
  4715. type = type->Struct.fields[index]->type;
  4716. e = ir_emit_struct_ep(proc, e, index);
  4717. } else if (type->kind == Type_Union) {
  4718. GB_ASSERT(index == -1);
  4719. type = t_type_info_ptr;
  4720. e = ir_emit_struct_ep(proc, e, index);
  4721. } else if (type->kind == Type_Tuple) {
  4722. type = type->Tuple.variables[index]->type;
  4723. e = ir_emit_struct_ep(proc, e, index);
  4724. } else if (type->kind == Type_Basic) {
  4725. switch (type->Basic.kind) {
  4726. case Basic_any: {
  4727. if (index == 0) {
  4728. type = t_rawptr;
  4729. } else if (index == 1) {
  4730. type = t_type_info_ptr;
  4731. }
  4732. e = ir_emit_struct_ep(proc, e, index);
  4733. break;
  4734. }
  4735. case Basic_string:
  4736. e = ir_emit_struct_ep(proc, e, index);
  4737. break;
  4738. default:
  4739. GB_PANIC("un-gep-able type");
  4740. break;
  4741. }
  4742. } else if (type->kind == Type_Slice) {
  4743. e = ir_emit_struct_ep(proc, e, index);
  4744. } else if (type->kind == Type_DynamicArray) {
  4745. e = ir_emit_struct_ep(proc, e, index);
  4746. } else if (type->kind == Type_Array) {
  4747. e = ir_emit_array_epi(proc, e, index);
  4748. } else if (type->kind == Type_Map) {
  4749. e = ir_emit_struct_ep(proc, e, index);
  4750. } else if (type->kind == Type_RelativePointer) {
  4751. e = ir_emit_struct_ep(proc, e, index);
  4752. } else {
  4753. GB_PANIC("un-gep-able type %s", type_to_string(type));
  4754. }
  4755. }
  4756. return e;
  4757. }
  4758. irValue *ir_emit_deep_field_ev(irProcedure *proc, irValue *e, Selection sel) {
  4759. GB_ASSERT(sel.index.count > 0);
  4760. if (e->kind == irValue_Instr) {
  4761. if (e->Instr.kind == irInstr_Load) {
  4762. irValue *addr = e->Instr.Load.address;
  4763. irValue *ptr = ir_emit_deep_field_gep(proc, addr, sel);
  4764. return ir_emit_load(proc, ptr);
  4765. }
  4766. }
  4767. Type *type = ir_type(e);
  4768. for_array(i, sel.index) {
  4769. i32 index = cast(i32)sel.index[i];
  4770. if (is_type_pointer(type)) {
  4771. type = type_deref(type);
  4772. e = ir_emit_load(proc, e);
  4773. e = ir_emit_ptr_offset(proc, e, v_zero); // TODO(bill): Do I need these copies?
  4774. }
  4775. type = base_type(type);
  4776. if (is_type_raw_union(type)) {
  4777. GB_PANIC("TODO(bill): IS THIS EVEN CORRECT?");
  4778. type = type->Struct.fields[index]->type;
  4779. e = ir_emit_conv(proc, e, type);
  4780. } else if (type->kind == Type_Map) {
  4781. e = ir_emit_struct_ev(proc, e, 1);
  4782. switch (index) {
  4783. case 0: e = ir_emit_struct_ev(proc, e, 1); break; // count
  4784. case 1: e = ir_emit_struct_ev(proc, e, 2); break; // capacity
  4785. case 2: e = ir_emit_struct_ev(proc, e, 3); break; // allocator
  4786. }
  4787. } else {
  4788. e = ir_emit_struct_ev(proc, e, index);
  4789. }
  4790. }
  4791. return e;
  4792. }
  4793. irValue *ir_array_elem(irProcedure *proc, irValue *array) {
  4794. return ir_emit_array_ep(proc, array, v_zero32);
  4795. }
  4796. irValue *ir_array_len(irProcedure *proc, irValue *array) {
  4797. Type *t = base_type(ir_type(array));
  4798. GB_ASSERT(t->kind == Type_Array);
  4799. return ir_const_int(t->Array.count);
  4800. }
  4801. irValue *ir_slice_elem(irProcedure *proc, irValue *slice) {
  4802. GB_ASSERT(is_type_slice(ir_type(slice)));
  4803. return ir_emit_struct_ev(proc, slice, 0);
  4804. }
  4805. irValue *ir_slice_len(irProcedure *proc, irValue *slice) {
  4806. GB_ASSERT(is_type_slice(ir_type(slice)));
  4807. return ir_emit_struct_ev(proc, slice, 1);
  4808. }
  4809. irValue *ir_dynamic_array_elem(irProcedure *proc, irValue *da) {
  4810. GB_ASSERT(is_type_dynamic_array(ir_type(da)));
  4811. return ir_emit_struct_ev(proc, da, 0);
  4812. }
  4813. irValue *ir_dynamic_array_len(irProcedure *proc, irValue *da) {
  4814. GB_ASSERT(is_type_dynamic_array(ir_type(da)));
  4815. return ir_emit_struct_ev(proc, da, 1);
  4816. }
  4817. irValue *ir_dynamic_array_cap(irProcedure *proc, irValue *da) {
  4818. GB_ASSERT(is_type_dynamic_array(ir_type(da)));
  4819. return ir_emit_struct_ev(proc, da, 2);
  4820. }
  4821. irValue *ir_dynamic_array_allocator(irProcedure *proc, irValue *da) {
  4822. GB_ASSERT(is_type_dynamic_array(ir_type(da)));
  4823. return ir_emit_struct_ev(proc, da, 3);
  4824. }
  4825. irValue *ir_string_elem(irProcedure *proc, irValue *string) {
  4826. Type *t = base_type(ir_type(string));
  4827. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  4828. return ir_emit_struct_ev(proc, string, 0);
  4829. }
  4830. irValue *ir_string_len(irProcedure *proc, irValue *string) {
  4831. Type *t = base_type(ir_type(string));
  4832. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  4833. return ir_emit_struct_ev(proc, string, 1);
  4834. }
  4835. irValue *ir_cstring_len(irProcedure *proc, irValue *value) {
  4836. GB_ASSERT(is_type_cstring(ir_type(value)));
  4837. auto args = array_make<irValue *>(ir_allocator(), 1);
  4838. args[0] = ir_emit_conv(proc, value, t_cstring);
  4839. return ir_emit_runtime_call(proc, "cstring_len", args);
  4840. }
  4841. void ir_fill_slice(irProcedure *proc, irValue *slice_ptr, irValue *data, irValue *len) {
  4842. Type *t = ir_type(slice_ptr);
  4843. GB_ASSERT(is_type_pointer(t));
  4844. t = type_deref(t);
  4845. GB_ASSERT(is_type_slice(t));
  4846. ir_emit_store(proc, ir_emit_struct_ep(proc, slice_ptr, 0), data);
  4847. ir_emit_store(proc, ir_emit_struct_ep(proc, slice_ptr, 1), len);
  4848. }
  4849. void ir_fill_string(irProcedure *proc, irValue *string_ptr, irValue *data, irValue *len) {
  4850. Type *t = ir_type(string_ptr);
  4851. GB_ASSERT(is_type_pointer(t));
  4852. t = type_deref(t);
  4853. GB_ASSERT(is_type_string(t));
  4854. ir_emit_store(proc, ir_emit_struct_ep(proc, string_ptr, 0), data);
  4855. ir_emit_store(proc, ir_emit_struct_ep(proc, string_ptr, 1), len);
  4856. }
  4857. irValue *ir_emit_string(irProcedure *proc, irValue *elem, irValue *len) {
  4858. irValue *str = ir_add_local_generated(proc, t_string, false);
  4859. ir_fill_string(proc, str, elem, len);
  4860. return ir_emit_load(proc, str);
  4861. }
  4862. irValue *ir_add_local_slice(irProcedure *proc, Type *slice_type, irValue *base, irValue *low, irValue *high) {
  4863. // TODO(bill): array bounds checking for slice creation
  4864. // TODO(bill): check that low < high <= max
  4865. gbAllocator a = ir_allocator();
  4866. Type *bt = base_type(ir_type(base));
  4867. if (low == nullptr) {
  4868. low = v_zero;
  4869. }
  4870. if (high == nullptr) {
  4871. switch (bt->kind) {
  4872. case Type_Array: high = ir_array_len(proc, base); break;
  4873. case Type_Slice: high = ir_slice_len(proc, base); break;
  4874. case Type_Pointer: high = v_one; break;
  4875. }
  4876. }
  4877. irValue *len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  4878. irValue *elem = nullptr;
  4879. switch (bt->kind) {
  4880. case Type_Array: elem = ir_array_elem(proc, base); break;
  4881. case Type_Slice: elem = ir_slice_elem(proc, base); break;
  4882. case Type_Pointer: elem = ir_emit_load(proc, base); break;
  4883. }
  4884. elem = ir_emit_ptr_offset(proc, elem, low);
  4885. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  4886. ir_fill_slice(proc, slice, elem, len);
  4887. return slice;
  4888. }
  4889. irValue *ir_find_or_add_entity_string(irModule *m, String str) {
  4890. StringHashKey key = string_hash_string(str);
  4891. irValue **found = string_map_get(&m->const_strings, key);
  4892. if (found != nullptr) {
  4893. return *found;
  4894. }
  4895. irValue *v = ir_value_constant(t_string, exact_value_string(str));
  4896. string_map_set(&m->const_strings, key, v);
  4897. return v;
  4898. }
  4899. irValue *ir_find_or_add_entity_string_byte_slice(irModule *m, String str) {
  4900. StringHashKey key = string_hash_string(str);
  4901. irValue **found = string_map_get(&m->const_string_byte_slices, key);
  4902. if (found != nullptr) {
  4903. return *found;
  4904. }
  4905. Type *t = t_u8_slice;
  4906. irValue *v = ir_value_constant(t, exact_value_string(str));
  4907. string_map_set(&m->const_string_byte_slices, key, v);
  4908. return v;
  4909. }
  4910. irValue *ir_const_union_tag(Type *u, Type *v) {
  4911. return ir_value_constant(union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  4912. }
  4913. String ir_lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  4914. Type *prev_src = src;
  4915. // Type *prev_dst = dst;
  4916. src = base_type(type_deref(src));
  4917. // dst = base_type(type_deref(dst));
  4918. bool src_is_ptr = src != prev_src;
  4919. // bool dst_is_ptr = dst != prev_dst;
  4920. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  4921. for_array(i, src->Struct.fields) {
  4922. Entity *f = src->Struct.fields[i];
  4923. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  4924. if (are_types_identical(dst, f->type)) {
  4925. return f->token.string;
  4926. }
  4927. if (src_is_ptr && is_type_pointer(dst)) {
  4928. if (are_types_identical(type_deref(dst), f->type)) {
  4929. return f->token.string;
  4930. }
  4931. }
  4932. if (is_type_struct(f->type)) {
  4933. String name = ir_lookup_subtype_polymorphic_field(info, dst, f->type);
  4934. if (name.len > 0) {
  4935. return name;
  4936. }
  4937. }
  4938. }
  4939. }
  4940. return str_lit("");
  4941. }
  4942. irValue *ir_emit_ptr_to_uintptr(irProcedure *proc, irValue *value, Type *t, bool allow_type_type = false) {
  4943. Type *vt = core_type(ir_type(value));
  4944. GB_ASSERT(is_type_pointer(vt));
  4945. if (allow_type_type) {
  4946. GB_ASSERT(is_type_uintptr(core_type(t)));
  4947. } else {
  4948. GB_ASSERT(is_type_uintptr(core_type(t)));
  4949. }
  4950. return ir_emit(proc, ir_instr_conv(proc, irConv_ptrtoint, value, vt, t));
  4951. }
  4952. irValue *ir_emit_uintptr_to_ptr(irProcedure *proc, irValue *value, Type *t) {
  4953. Type *vt = core_type(ir_type(value));
  4954. GB_ASSERT(is_type_uintptr(vt));
  4955. GB_ASSERT(is_type_pointer(core_type(t)));
  4956. return ir_emit(proc, ir_instr_conv(proc, irConv_inttoptr, value, vt, t));
  4957. }
  4958. irValue *ir_emit_byte_swap(irProcedure *proc, irValue *value, Type *t) {
  4959. Type *vt = core_type(ir_type(value));
  4960. if (is_type_untyped(vt)) {
  4961. return value;
  4962. }
  4963. GB_ASSERT(type_size_of(vt) == type_size_of(t));
  4964. if (is_type_float(t)) {
  4965. i64 sz = type_size_of(t);
  4966. auto args = array_make<irValue *>(ir_allocator(), 1);
  4967. args[0] = value;
  4968. char const *proc_name = nullptr;
  4969. switch (sz*8) {
  4970. case 32: proc_name = "bswap_f32"; break;
  4971. case 64: proc_name = "bswap_f64"; break;
  4972. }
  4973. GB_ASSERT(proc_name != nullptr);
  4974. String name = make_string_c(proc_name);
  4975. AstPackage *p = proc->module->info->runtime_package;
  4976. Entity *e = scope_lookup_current(p->scope, name);
  4977. irValue **found = map_get(&proc->module->values, hash_entity(e));
  4978. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(name));
  4979. irValue *gp = *found;
  4980. return ir_emit(proc, ir_instr_call(proc, gp, nullptr, args, t, nullptr, ProcInlining_none));
  4981. }
  4982. return ir_emit(proc, ir_instr_conv(proc, irConv_byteswap, value, vt, t));
  4983. }
  4984. void ir_emit_store_union_variant(irProcedure *proc, irValue *parent, irValue *variant, Type *variant_type) {
  4985. gbAllocator a = ir_allocator();
  4986. irValue *underlying = ir_emit_conv(proc, parent, alloc_type_pointer(variant_type));
  4987. ir_emit_store(proc, underlying, variant);
  4988. Type *t = type_deref(ir_type(parent));
  4989. if (is_type_union_maybe_pointer(t)) {
  4990. // No tag needed!
  4991. } else {
  4992. irValue *tag_ptr = ir_emit_union_tag_ptr(proc, parent);
  4993. ir_emit_store(proc, tag_ptr, ir_const_union_tag(t, variant_type));
  4994. }
  4995. }
  4996. irValue *ir_emit_conv(irProcedure *proc, irValue *value, Type *t) {
  4997. Type *src_type = ir_type(value);
  4998. if (are_types_identical(t, src_type)) {
  4999. return value;
  5000. }
  5001. Type *src = core_type(src_type);
  5002. Type *dst = core_type(t);
  5003. // if (is_type_untyped_nil(src) && type_has_nil(dst)) {
  5004. if (is_type_untyped_nil(src)) {
  5005. return ir_value_nil(t);
  5006. }
  5007. if (is_type_untyped_undef(src)) {
  5008. return ir_value_undef(t);
  5009. }
  5010. if (value->kind == irValue_Constant) {
  5011. if (is_type_any(dst)) {
  5012. irValue *default_value = ir_add_local_generated(proc, default_type(src_type), false);
  5013. ir_emit_store(proc, default_value, value);
  5014. return ir_emit_conv(proc, ir_emit_load(proc, default_value), t_any);
  5015. } else if (dst->kind == Type_Basic) {
  5016. ExactValue ev = value->Constant.value;
  5017. if (is_type_float(dst)) {
  5018. ev = exact_value_to_float(ev);
  5019. } else if (is_type_complex(dst)) {
  5020. ev = exact_value_to_complex(ev);
  5021. } else if (is_type_quaternion(dst)) {
  5022. ev = exact_value_to_quaternion(ev);
  5023. } else if (is_type_string(dst)) {
  5024. // Handled elsewhere
  5025. GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  5026. } else if (is_type_integer(dst)) {
  5027. ev = exact_value_to_integer(ev);
  5028. } else if (is_type_pointer(dst)) {
  5029. // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  5030. irValue *i = ir_add_module_constant(proc->module, t_uintptr, ev);
  5031. return ir_emit(proc, ir_instr_conv(proc, irConv_inttoptr, i, t_uintptr, dst));
  5032. }
  5033. return ir_add_module_constant(proc->module, t, ev);
  5034. }
  5035. }
  5036. if (are_types_identical(src, dst)) {
  5037. if (!are_types_identical(src_type, t)) {
  5038. return ir_emit_transmute(proc, value, t);
  5039. }
  5040. return value;
  5041. }
  5042. // bool <-> llvm bool
  5043. if (is_type_boolean(src) && dst == t_llvm_bool) {
  5044. return ir_emit(proc, ir_instr_conv(proc, irConv_trunc, value, src_type, t));
  5045. }
  5046. if (src == t_llvm_bool && is_type_boolean(dst)) {
  5047. return ir_emit(proc, ir_instr_conv(proc, irConv_zext, value, src_type, t));
  5048. }
  5049. // integer -> integer
  5050. if (is_type_integer(src) && is_type_integer(dst)) {
  5051. GB_ASSERT(src->kind == Type_Basic &&
  5052. dst->kind == Type_Basic);
  5053. i64 sz = type_size_of(default_type(src));
  5054. i64 dz = type_size_of(default_type(dst));
  5055. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  5056. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5057. value = ir_emit_byte_swap(proc, value, platform_src_type);
  5058. }
  5059. irConvKind kind = irConv_trunc;
  5060. if (dz < sz) {
  5061. kind = irConv_trunc;
  5062. } else if (dz == sz) {
  5063. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  5064. // NOTE(bill): Copy the value just for type correctness
  5065. kind = irConv_bitcast;
  5066. } else if (dz > sz) {
  5067. if (is_type_unsigned(src)) {
  5068. kind = irConv_zext; // zero extent
  5069. } else {
  5070. kind = irConv_sext; // sign extent
  5071. }
  5072. }
  5073. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  5074. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5075. irValue *res = ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, platform_dst_type));
  5076. return ir_emit_byte_swap(proc, res, t);
  5077. } else {
  5078. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  5079. }
  5080. }
  5081. // boolean -> boolean/integer
  5082. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  5083. irValue *b = ir_emit(proc, ir_instr_binary_op(proc, Token_NotEq, value, v_zero, t_llvm_bool));
  5084. return ir_emit(proc, ir_instr_conv(proc, irConv_zext, b, t_llvm_bool, t));
  5085. }
  5086. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  5087. return ir_emit_bitcast(proc, value, dst);
  5088. }
  5089. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  5090. return ir_emit_bitcast(proc, value, dst);
  5091. }
  5092. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  5093. return ir_emit_bitcast(proc, value, dst);
  5094. }
  5095. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  5096. return ir_emit_bitcast(proc, value, dst);
  5097. }
  5098. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  5099. irValue *c = ir_emit_conv(proc, value, t_cstring);
  5100. auto args = array_make<irValue *>(ir_allocator(), 1);
  5101. args[0] = c;
  5102. irValue *s = ir_emit_runtime_call(proc, "cstring_to_string", args);
  5103. return ir_emit_conv(proc, s, dst);
  5104. }
  5105. // integer -> boolean
  5106. if (is_type_integer(src) && is_type_boolean(dst)) {
  5107. return ir_emit_comp(proc, Token_NotEq, value, v_zero);
  5108. }
  5109. // float -> float
  5110. if (is_type_float(src) && is_type_float(dst)) {
  5111. GB_ASSERT(!are_types_identical(src, dst));
  5112. gbAllocator a = ir_allocator();
  5113. i64 sz = type_size_of(src);
  5114. i64 dz = type_size_of(dst);
  5115. irConvKind kind = irConv_fptrunc;
  5116. if (dz == sz) {
  5117. if (types_have_same_internal_endian(src, dst)) {
  5118. return ir_emit_transmute(proc, value, t);
  5119. } else {
  5120. return ir_emit_byte_swap(proc, value, t);
  5121. }
  5122. }
  5123. if (dz >= sz) {
  5124. kind = irConv_fpext;
  5125. }
  5126. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  5127. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5128. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5129. irValue *res = nullptr;
  5130. res = ir_emit_conv(proc, value, platform_src_type);
  5131. res = ir_emit_conv(proc, res, platform_dst_type);
  5132. if (is_type_different_to_arch_endianness(dst)) {
  5133. res = ir_emit_byte_swap(proc, res, t);
  5134. }
  5135. return ir_emit_conv(proc, res, t);
  5136. }
  5137. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  5138. }
  5139. if (is_type_complex(src) && is_type_complex(dst)) {
  5140. Type *ft = base_complex_elem_type(dst);
  5141. irValue *gen = ir_add_local_generated(proc, dst, false);
  5142. irValue *real = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 0), ft);
  5143. irValue *imag = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 1), ft);
  5144. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), real);
  5145. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 1), imag);
  5146. return ir_emit_load(proc, gen);
  5147. }
  5148. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  5149. // @QuaternionLayout
  5150. Type *ft = base_complex_elem_type(dst);
  5151. irValue *gen = ir_add_local_generated(proc, dst, false);
  5152. irValue *q0 = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 0), ft);
  5153. irValue *q1 = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 1), ft);
  5154. irValue *q2 = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 2), ft);
  5155. irValue *q3 = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 3), ft);
  5156. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), q0);
  5157. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 1), q1);
  5158. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 2), q2);
  5159. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 3), q3);
  5160. return ir_emit_load(proc, gen);
  5161. }
  5162. if (is_type_float(src) && is_type_complex(dst)) {
  5163. Type *ft = base_complex_elem_type(dst);
  5164. irValue *gen = ir_add_local_generated(proc, dst, true);
  5165. irValue *real = ir_emit_conv(proc, value, ft);
  5166. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), real);
  5167. return ir_emit_load(proc, gen);
  5168. }
  5169. if (is_type_float(src) && is_type_quaternion(dst)) {
  5170. Type *ft = base_complex_elem_type(dst);
  5171. irValue *gen = ir_add_local_generated(proc, dst, true);
  5172. irValue *real = ir_emit_conv(proc, value, ft);
  5173. // @QuaternionLayout
  5174. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 3), real);
  5175. return ir_emit_load(proc, gen);
  5176. }
  5177. if (is_type_complex(src) && is_type_quaternion(dst)) {
  5178. Type *ft = base_complex_elem_type(dst);
  5179. irValue *gen = ir_add_local_generated(proc, dst, true);
  5180. irValue *real = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 0), ft);
  5181. irValue *imag = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 1), ft);
  5182. // @QuaternionLayout
  5183. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 3), real);
  5184. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), imag);
  5185. return ir_emit_load(proc, gen);
  5186. }
  5187. // float <-> integer
  5188. if (is_type_float(src) && is_type_integer(dst)) {
  5189. irConvKind kind = irConv_fptosi;
  5190. if (is_type_unsigned(dst)) {
  5191. kind = irConv_fptoui;
  5192. }
  5193. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  5194. }
  5195. if (is_type_integer(src) && is_type_float(dst)) {
  5196. irConvKind kind = irConv_sitofp;
  5197. if (is_type_unsigned(src)) {
  5198. kind = irConv_uitofp;
  5199. }
  5200. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  5201. }
  5202. // Pointer <-> uintptr
  5203. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5204. return ir_emit_ptr_to_uintptr(proc, value, t);
  5205. }
  5206. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5207. return ir_emit_uintptr_to_ptr(proc, value, t);
  5208. }
  5209. if (is_type_union(dst)) {
  5210. for_array(i, dst->Union.variants) {
  5211. Type *vt = dst->Union.variants[i];
  5212. if (are_types_identical(vt, src_type)) {
  5213. ir_emit_comment(proc, str_lit("union - child to parent"));
  5214. gbAllocator a = ir_allocator();
  5215. irValue *parent = ir_add_local_generated(proc, t, true);
  5216. ir_emit_store_union_variant(proc, parent, value, vt);
  5217. return ir_emit_load(proc, parent);
  5218. }
  5219. }
  5220. }
  5221. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  5222. // subtype polymorphism casting
  5223. if (check_is_assignable_to_using_subtype(src_type, t)) {
  5224. Type *st = type_deref(src_type);
  5225. Type *pst = st;
  5226. st = type_deref(st);
  5227. bool st_is_ptr = is_type_pointer(src_type);
  5228. st = base_type(st);
  5229. Type *dt = t;
  5230. bool dt_is_ptr = type_deref(dt) != dt;
  5231. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  5232. String field_name = ir_lookup_subtype_polymorphic_field(proc->module->info, t, src_type);
  5233. if (field_name.len > 0) {
  5234. // NOTE(bill): It can be casted
  5235. Selection sel = lookup_field(st, field_name, false, true);
  5236. if (sel.entity != nullptr) {
  5237. ir_emit_comment(proc, str_lit("cast - polymorphism"));
  5238. if (st_is_ptr) {
  5239. irValue *res = ir_emit_deep_field_gep(proc, value, sel);
  5240. Type *rt = ir_type(res);
  5241. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5242. res = ir_emit_load(proc, res);
  5243. }
  5244. return res;
  5245. } else {
  5246. if (is_type_pointer(ir_type(value))) {
  5247. Type *rt = ir_type(value);
  5248. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5249. value = ir_emit_load(proc, value);
  5250. } else {
  5251. value = ir_emit_deep_field_gep(proc, value, sel);
  5252. return ir_emit_load(proc, value);
  5253. }
  5254. }
  5255. return ir_emit_deep_field_ev(proc, value, sel);
  5256. }
  5257. } else {
  5258. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  5259. }
  5260. }
  5261. }
  5262. // Pointer <-> Pointer
  5263. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5264. return ir_emit_bitcast(proc, value, t);
  5265. }
  5266. // proc <-> proc
  5267. if (is_type_proc(src) && is_type_proc(dst)) {
  5268. return ir_emit_bitcast(proc, value, t);
  5269. }
  5270. // pointer -> proc
  5271. if (is_type_pointer(src) && is_type_proc(dst)) {
  5272. return ir_emit_bitcast(proc, value, t);
  5273. }
  5274. // proc -> pointer
  5275. if (is_type_proc(src) && is_type_pointer(dst)) {
  5276. return ir_emit_bitcast(proc, value, t);
  5277. }
  5278. // []byte/[]u8 <-> string
  5279. if (is_type_u8_slice(src) && is_type_string(dst)) {
  5280. irValue *elem = ir_slice_elem(proc, value);
  5281. irValue *len = ir_slice_len(proc, value);
  5282. return ir_emit_string(proc, elem, len);
  5283. }
  5284. if (is_type_string(src) && is_type_u8_slice(dst)) {
  5285. irValue *elem = ir_string_elem(proc, value);
  5286. irValue *elem_ptr = ir_add_local_generated(proc, ir_type(elem), false);
  5287. ir_emit_store(proc, elem_ptr, elem);
  5288. irValue *len = ir_string_len(proc, value);
  5289. irValue *slice = ir_add_local_slice(proc, t, elem_ptr, v_zero, len);
  5290. return ir_emit_load(proc, slice);
  5291. }
  5292. if (is_type_array(dst)) {
  5293. Type *elem = dst->Array.elem;
  5294. irValue *e = ir_emit_conv(proc, value, elem);
  5295. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5296. irValue *v = ir_add_local_generated(proc, t, false);
  5297. isize index_count = cast(isize)dst->Array.count;
  5298. for (i32 i = 0; i < index_count; i++) {
  5299. irValue *elem = ir_emit_array_epi(proc, v, i);
  5300. ir_emit_store(proc, elem, e);
  5301. }
  5302. return ir_emit_load(proc, v);
  5303. }
  5304. if (is_type_any(dst)) {
  5305. irValue *result = ir_add_local_generated(proc, t_any, true);
  5306. if (is_type_untyped_nil(src)) {
  5307. return ir_emit_load(proc, result);
  5308. }
  5309. Type *st = default_type(src_type);
  5310. irValue *data = ir_address_from_load_or_generate_local(proc, value);
  5311. GB_ASSERT_MSG(is_type_pointer(ir_type(data)), type_to_string(ir_type(data)));
  5312. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  5313. data = ir_emit_conv(proc, data, t_rawptr);
  5314. irValue *id = ir_typeid(proc->module, st);
  5315. ir_emit_store(proc, ir_emit_struct_ep(proc, result, 0), data);
  5316. ir_emit_store(proc, ir_emit_struct_ep(proc, result, 1), id);
  5317. return ir_emit_load(proc, result);
  5318. }
  5319. if (is_type_untyped(src)) {
  5320. if (is_type_string(src) && is_type_string(dst)) {
  5321. irValue *result = ir_add_local_generated(proc, t, false);
  5322. ir_emit_store(proc, result, value);
  5323. return ir_emit_load(proc, result);
  5324. }
  5325. }
  5326. gb_printf_err("ir_emit_conv: src -> dst\n");
  5327. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  5328. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  5329. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  5330. type_to_string(src_type), type_to_string(t),
  5331. LIT(proc->name));
  5332. return nullptr;
  5333. }
  5334. bool ir_is_type_aggregate(Type *t) {
  5335. t = base_type(t);
  5336. switch (t->kind) {
  5337. case Type_Basic:
  5338. switch (t->Basic.kind) {
  5339. case Basic_string:
  5340. case Basic_any:
  5341. return true;
  5342. // case Basic_complex32:
  5343. case Basic_complex64:
  5344. case Basic_complex128:
  5345. case Basic_quaternion128:
  5346. case Basic_quaternion256:
  5347. return true;
  5348. }
  5349. break;
  5350. case Type_Pointer:
  5351. return false;
  5352. case Type_Array:
  5353. case Type_Slice:
  5354. case Type_Struct:
  5355. case Type_Union:
  5356. case Type_Tuple:
  5357. case Type_DynamicArray:
  5358. case Type_Map:
  5359. case Type_BitField:
  5360. case Type_SimdVector:
  5361. return true;
  5362. case Type_Named:
  5363. return ir_is_type_aggregate(t->Named.base);
  5364. }
  5365. return false;
  5366. }
  5367. irValue *ir_emit_transmute(irProcedure *proc, irValue *value, Type *t) {
  5368. Type *src_type = ir_type(value);
  5369. if (are_types_identical(t, src_type)) {
  5370. return value;
  5371. }
  5372. Type *src = base_type(src_type);
  5373. Type *dst = base_type(t);
  5374. irModule *m = proc->module;
  5375. i64 sz = type_size_of(src);
  5376. i64 dz = type_size_of(dst);
  5377. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  5378. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  5379. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5380. return ir_emit_uintptr_to_ptr(proc, value, t);
  5381. }
  5382. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5383. return ir_emit_ptr_to_uintptr(proc, value, t);
  5384. }
  5385. if (is_type_uintptr(src) && is_type_proc(dst)) {
  5386. irValue *ptr = ir_emit_uintptr_to_ptr(proc, value, t_rawptr);
  5387. return ir_emit_bitcast(proc, ptr, dst);
  5388. }
  5389. if (is_type_proc(src) && is_type_uintptr(dst)) {
  5390. irValue *ptr = ir_emit_uintptr_to_ptr(proc, value, t_rawptr);
  5391. return ir_emit_bitcast(proc, ptr, dst);
  5392. }
  5393. if (is_type_float(src) && is_type_float(dst)) {
  5394. return ir_emit_bitcast(proc, value, t);
  5395. }
  5396. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  5397. Type *vt = core_type(ir_type(value));
  5398. return ir_emit(proc, ir_instr_conv(proc, irConv_inttoptr, value, vt, t));
  5399. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  5400. Type *vt = core_type(ir_type(value));
  5401. return ir_emit(proc, ir_instr_conv(proc, irConv_ptrtoint, value, vt, t));
  5402. }
  5403. if (ir_is_type_aggregate(src) || ir_is_type_aggregate(dst)) {
  5404. irValue *s = ir_address_from_load_or_generate_local(proc, value);
  5405. irValue *d = ir_emit_bitcast(proc, s, alloc_type_pointer(t));
  5406. return ir_emit_load(proc, d);
  5407. }
  5408. // TODO(bill): Actually figure out what the conversion needs to be correctly 'cause LLVM
  5409. return ir_emit_bitcast(proc, value, t);
  5410. }
  5411. irValue *ir_emit_union_cast(irProcedure *proc, irValue *value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  5412. gbAllocator a = ir_allocator();
  5413. Type *src_type = ir_type(value);
  5414. bool is_ptr = is_type_pointer(src_type);
  5415. bool is_tuple = true;
  5416. Type *tuple = type;
  5417. if (type->kind != Type_Tuple) {
  5418. is_tuple = false;
  5419. tuple = make_optional_ok_type(type);
  5420. }
  5421. irValue *v = ir_add_local_generated(proc, tuple, true);
  5422. if (is_ptr) {
  5423. value = ir_emit_load(proc, value);
  5424. }
  5425. Type *src = base_type(type_deref(src_type));
  5426. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  5427. Type *dst = tuple->Tuple.variables[0]->type;
  5428. irValue *value_ = ir_address_from_load_or_generate_local(proc, value);
  5429. irValue *tag = nullptr;
  5430. irValue *dst_tag = nullptr;
  5431. irValue *cond = nullptr;
  5432. irValue *data = nullptr;
  5433. irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
  5434. irValue *gep1 = ir_emit_struct_ep(proc, v, 1);
  5435. if (is_type_union_maybe_pointer(src)) {
  5436. data = ir_emit_load(proc, ir_emit_conv(proc, value_, ir_type(gep0)));
  5437. } else {
  5438. tag = ir_emit_load(proc, ir_emit_union_tag_ptr(proc, value_));
  5439. dst_tag = ir_const_union_tag(src, dst);
  5440. }
  5441. irBlock *ok_block = ir_new_block(proc, nullptr, "union_cast.ok");
  5442. irBlock *end_block = ir_new_block(proc, nullptr, "union_cast.end");
  5443. if (data != nullptr) {
  5444. GB_ASSERT(is_type_union_maybe_pointer(src));
  5445. cond = ir_emit_comp_against_nil(proc, Token_NotEq, data);
  5446. } else {
  5447. cond = ir_emit_comp(proc, Token_CmpEq, tag, dst_tag);
  5448. }
  5449. ir_emit_if(proc, cond, ok_block, end_block);
  5450. ir_start_block(proc, ok_block);
  5451. if (data == nullptr) {
  5452. data = ir_emit_load(proc, ir_emit_conv(proc, value_, ir_type(gep0)));
  5453. }
  5454. ir_emit_store(proc, gep0, data);
  5455. ir_emit_store(proc, gep1, v_true);
  5456. ir_emit_jump(proc, end_block);
  5457. ir_start_block(proc, end_block);
  5458. if (!is_tuple) {
  5459. if (do_conversion_check) {
  5460. // NOTE(bill): Panic on invalid conversion
  5461. Type *dst_type = tuple->Tuple.variables[0]->type;
  5462. irValue *ok = ir_emit_load(proc, ir_emit_struct_ep(proc, v, 1));
  5463. auto args = array_make<irValue *>(ir_allocator(), 6);
  5464. args[0] = ok;
  5465. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  5466. args[2] = ir_const_int(pos.line);
  5467. args[3] = ir_const_int(pos.column);
  5468. args[4] = ir_typeid(proc->module, src_type);
  5469. args[5] = ir_typeid(proc->module, dst_type);
  5470. ir_emit_runtime_call(proc, "type_assertion_check", args);
  5471. }
  5472. return ir_emit_load(proc, ir_emit_struct_ep(proc, v, 0));
  5473. }
  5474. return ir_emit_load(proc, v);
  5475. }
  5476. irAddr ir_emit_any_cast_addr(irProcedure *proc, irValue *value, Type *type, TokenPos pos) {
  5477. gbAllocator a = ir_allocator();
  5478. Type *src_type = ir_type(value);
  5479. if (is_type_pointer(src_type)) {
  5480. value = ir_emit_load(proc, value);
  5481. }
  5482. bool is_tuple = true;
  5483. Type *tuple = type;
  5484. if (type->kind != Type_Tuple) {
  5485. is_tuple = false;
  5486. tuple = make_optional_ok_type(type);
  5487. }
  5488. Type *dst_type = tuple->Tuple.variables[0]->type;
  5489. irValue *v = ir_add_local_generated(proc, tuple, true);
  5490. irValue *dst_typeid = ir_typeid(proc->module, dst_type);
  5491. irValue *any_typeid = ir_emit_struct_ev(proc, value, 1);
  5492. irBlock *ok_block = ir_new_block(proc, nullptr, "any_cast.ok");
  5493. irBlock *end_block = ir_new_block(proc, nullptr, "any_cast.end");
  5494. irValue *cond = ir_emit_comp(proc, Token_CmpEq, any_typeid, dst_typeid);
  5495. ir_emit_if(proc, cond, ok_block, end_block);
  5496. ir_start_block(proc, ok_block);
  5497. irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
  5498. irValue *gep1 = ir_emit_struct_ep(proc, v, 1);
  5499. irValue *any_data = ir_emit_struct_ev(proc, value, 0);
  5500. irValue *ptr = ir_emit_conv(proc, any_data, alloc_type_pointer(dst_type));
  5501. ir_emit_store(proc, gep0, ir_emit_load(proc, ptr));
  5502. ir_emit_store(proc, gep1, v_true);
  5503. ir_emit_jump(proc, end_block);
  5504. ir_start_block(proc, end_block);
  5505. if (!is_tuple) {
  5506. // NOTE(bill): Panic on invalid conversion
  5507. irValue *ok = ir_emit_load(proc, ir_emit_struct_ep(proc, v, 1));
  5508. auto args = array_make<irValue *>(ir_allocator(), 6);
  5509. args[0] = ok;
  5510. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  5511. args[2] = ir_const_int(pos.line);
  5512. args[3] = ir_const_int(pos.column);
  5513. args[4] = any_typeid;
  5514. args[5] = dst_typeid;
  5515. ir_emit_runtime_call(proc, "type_assertion_check", args);
  5516. return ir_addr(ir_emit_struct_ep(proc, v, 0));
  5517. }
  5518. return ir_addr(v);
  5519. }
  5520. irValue *ir_emit_any_cast(irProcedure *proc, irValue *value, Type *type, TokenPos pos) {
  5521. return ir_addr_load(proc, ir_emit_any_cast_addr(proc, value, type, pos));
  5522. }
  5523. // TODO(bill): Try and make a lot of this constant aggregate literals in LLVM IR
  5524. gb_global irValue *ir_global_type_info_data = nullptr;
  5525. gb_global irValue *ir_global_type_info_member_types = nullptr;
  5526. gb_global irValue *ir_global_type_info_member_names = nullptr;
  5527. gb_global irValue *ir_global_type_info_member_offsets = nullptr;
  5528. gb_global irValue *ir_global_type_info_member_usings = nullptr;
  5529. gb_global irValue *ir_global_type_info_member_tags = nullptr;
  5530. gb_global i32 ir_global_type_info_data_index = 0;
  5531. gb_global i32 ir_global_type_info_member_types_index = 0;
  5532. gb_global i32 ir_global_type_info_member_names_index = 0;
  5533. gb_global i32 ir_global_type_info_member_offsets_index = 0;
  5534. gb_global i32 ir_global_type_info_member_usings_index = 0;
  5535. gb_global i32 ir_global_type_info_member_tags_index = 0;
  5536. isize ir_type_info_count(CheckerInfo *info) {
  5537. return info->minimum_dependency_type_info_set.entries.count+1;
  5538. }
  5539. isize ir_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  5540. isize index = type_info_index(info, type, false);
  5541. if (index >= 0) {
  5542. auto *set = &info->minimum_dependency_type_info_set;
  5543. for_array(i, set->entries) {
  5544. if (set->entries[i].ptr == index) {
  5545. return i+1;
  5546. }
  5547. }
  5548. }
  5549. if (err_on_not_found) {
  5550. GB_PANIC("NOT FOUND ir_type_info_index %s @ index %td", type_to_string(type), index);
  5551. }
  5552. return -1;
  5553. }
  5554. irValue *ir_type_info(irProcedure *proc, Type *type) {
  5555. CheckerInfo *info = proc->module->info;
  5556. type = default_type(type);
  5557. i32 id = cast(i32)ir_type_info_index(info, type);
  5558. GB_ASSERT(id >= 0);
  5559. return ir_emit_array_ep(proc, ir_global_type_info_data, ir_const_i32(id));
  5560. }
  5561. irValue *ir_typeid(irModule *m, Type *type) {
  5562. type = default_type(type);
  5563. u64 id = cast(u64)ir_type_info_index(m->info, type);
  5564. GB_ASSERT(id >= 0);
  5565. u64 kind = Typeid_Invalid;
  5566. u64 named = is_type_named(type) && type->kind != Type_Basic;
  5567. u64 special = 0;
  5568. u64 reserved = 0;
  5569. Type *bt = base_type(type);
  5570. TypeKind tk = bt->kind;
  5571. switch (tk) {
  5572. case Type_Basic: {
  5573. u32 flags = bt->Basic.flags;
  5574. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  5575. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  5576. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  5577. if (flags & BasicFlag_Float) kind = Typeid_Float;
  5578. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  5579. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  5580. if (flags & BasicFlag_String) kind = Typeid_String;
  5581. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  5582. } break;
  5583. case Type_Pointer: kind = Typeid_Pointer; break;
  5584. case Type_Array: kind = Typeid_Array; break;
  5585. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  5586. case Type_Slice: kind = Typeid_Slice; break;
  5587. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  5588. case Type_Map: kind = Typeid_Map; break;
  5589. case Type_Struct: kind = Typeid_Struct; break;
  5590. case Type_Enum: kind = Typeid_Enum; break;
  5591. case Type_Union: kind = Typeid_Union; break;
  5592. case Type_Tuple: kind = Typeid_Tuple; break;
  5593. case Type_Proc: kind = Typeid_Procedure; break;
  5594. case Type_BitField: kind = Typeid_Bit_Field; break;
  5595. case Type_BitSet: kind = Typeid_Bit_Set; break;
  5596. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  5597. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  5598. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  5599. }
  5600. if (is_type_cstring(type)) {
  5601. special = 1;
  5602. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  5603. special = 1;
  5604. }
  5605. u64 data = 0;
  5606. if (build_context.word_size == 4) {
  5607. data |= (id &~ (1u<<24)) << 0u; // index
  5608. data |= (kind &~ (1u<<5)) << 24u; // kind
  5609. data |= (named &~ (1u<<1)) << 29u; // kind
  5610. data |= (special &~ (1u<<1)) << 30u; // kind
  5611. data |= (reserved &~ (1u<<1)) << 31u; // kind
  5612. } else {
  5613. GB_ASSERT(build_context.word_size == 8);
  5614. data |= (id &~ (1ull<<56)) << 0ul; // index
  5615. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  5616. data |= (named &~ (1ull<<1)) << 61ull; // kind
  5617. data |= (special &~ (1ull<<1)) << 62ull; // kind
  5618. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  5619. }
  5620. return ir_value_constant(t_typeid, exact_value_u64(data));
  5621. }
  5622. irValue *ir_emit_logical_binary_expr(irProcedure *proc, TokenKind op, Ast *left, Ast *right, Type *type) {
  5623. irBlock *rhs = ir_new_block(proc, nullptr, "logical.cmp.rhs");
  5624. irBlock *done = ir_new_block(proc, nullptr, "logical.cmp.done");
  5625. type = default_type(type);
  5626. irValue *short_circuit = nullptr;
  5627. if (op == Token_CmpAnd) {
  5628. ir_build_cond(proc, left, rhs, done);
  5629. short_circuit = v_false;
  5630. } else if (op == Token_CmpOr) {
  5631. ir_build_cond(proc, left, done, rhs);
  5632. short_circuit = v_true;
  5633. }
  5634. if (rhs->preds.count == 0) {
  5635. ir_start_block(proc, done);
  5636. return short_circuit;
  5637. }
  5638. if (done->preds.count == 0) {
  5639. ir_start_block(proc, rhs);
  5640. return ir_build_expr(proc, right);
  5641. }
  5642. auto edges = array_make<irValue *>(ir_allocator(), 0, done->preds.count+1);
  5643. for_array(i, done->preds) {
  5644. irValue *edge = ir_emit_conv(proc, short_circuit, type);
  5645. array_add(&edges, edge);
  5646. }
  5647. ir_start_block(proc, rhs);
  5648. irValue *edge = ir_emit_conv(proc, ir_build_expr(proc, right), type);
  5649. array_add(&edges, edge);
  5650. ir_emit_jump(proc, done);
  5651. ir_start_block(proc, done);
  5652. return ir_emit(proc, ir_instr_phi(proc, edges, type));
  5653. }
  5654. irValue *ir_emit_logical_binary_expr(irProcedure *proc, Ast *expr) {
  5655. ast_node(be, BinaryExpr, expr);
  5656. Type *type = type_of_expr(expr);
  5657. type = default_type(type);
  5658. return ir_emit_logical_binary_expr(proc, be->op.kind, be->left, be->right, type);
  5659. }
  5660. void ir_emit_bounds_check(irProcedure *proc, Token token, irValue *index, irValue *len) {
  5661. if (build_context.no_bounds_check) {
  5662. return;
  5663. }
  5664. if ((proc->module->state_flags & StateFlag_no_bounds_check) != 0) {
  5665. return;
  5666. }
  5667. index = ir_emit_conv(proc, index, t_int);
  5668. len = ir_emit_conv(proc, len, t_int);
  5669. gbAllocator a = ir_allocator();
  5670. irValue *file = ir_find_or_add_entity_string(proc->module, token.pos.file);
  5671. irValue *line = ir_const_int(token.pos.line);
  5672. irValue *column = ir_const_int(token.pos.column);
  5673. auto args = array_make<irValue *>(ir_allocator(), 5);
  5674. args[0] = file;
  5675. args[1] = line;
  5676. args[2] = column;
  5677. args[3] = index;
  5678. args[4] = len;
  5679. ir_emit_runtime_call(proc, "bounds_check_error", args);
  5680. }
  5681. void ir_emit_slice_bounds_check(irProcedure *proc, Token token, irValue *low, irValue *high, irValue *len, bool lower_value_used) {
  5682. if (build_context.no_bounds_check) {
  5683. return;
  5684. }
  5685. if ((proc->module->state_flags & StateFlag_no_bounds_check) != 0) {
  5686. return;
  5687. }
  5688. gbAllocator a = ir_allocator();
  5689. irValue *file = ir_find_or_add_entity_string(proc->module, token.pos.file);
  5690. irValue *line = ir_const_int(token.pos.line);
  5691. irValue *column = ir_const_int(token.pos.column);
  5692. high = ir_emit_conv(proc, high, t_int);
  5693. if (!lower_value_used) {
  5694. auto args = array_make<irValue *>(ir_allocator(), 5);
  5695. args[0] = file;
  5696. args[1] = line;
  5697. args[2] = column;
  5698. args[3] = high;
  5699. args[4] = len;
  5700. ir_emit_runtime_call(proc, "slice_expr_error_hi", args);
  5701. } else {
  5702. // No need to convert unless used
  5703. low = ir_emit_conv(proc, low, t_int);
  5704. auto args = array_make<irValue *>(ir_allocator(), 6);
  5705. args[0] = file;
  5706. args[1] = line;
  5707. args[2] = column;
  5708. args[3] = low;
  5709. args[4] = high;
  5710. args[5] = len;
  5711. ir_emit_runtime_call(proc, "slice_expr_error_lo_hi", args);
  5712. }
  5713. }
  5714. void ir_emit_dynamic_array_bounds_check(irProcedure *proc, Token token, irValue *low, irValue *high, irValue *max) {
  5715. if (build_context.no_bounds_check) {
  5716. return;
  5717. }
  5718. if ((proc->module->state_flags & StateFlag_no_bounds_check) != 0) {
  5719. return;
  5720. }
  5721. gbAllocator a = ir_allocator();
  5722. irValue *file = ir_find_or_add_entity_string(proc->module, token.pos.file);
  5723. irValue *line = ir_const_int(token.pos.line);
  5724. irValue *column = ir_const_int(token.pos.column);
  5725. low = ir_emit_conv(proc, low, t_int);
  5726. high = ir_emit_conv(proc, high, t_int);
  5727. auto args = array_make<irValue *>(ir_allocator(), 6);
  5728. args[0] = file;
  5729. args[1] = line;
  5730. args[2] = column;
  5731. args[3] = low;
  5732. args[4] = high;
  5733. args[5] = max;
  5734. ir_emit_runtime_call(proc, "dynamic_array_expr_error", args);
  5735. }
  5736. ////////////////////////////////////////////////////////////////
  5737. //
  5738. // @Build
  5739. //
  5740. ////////////////////////////////////////////////////////////////
  5741. String ir_mangle_name(irGen *s, Entity *e) {
  5742. irModule *m = &s->module;
  5743. CheckerInfo *info = m->info;
  5744. gbAllocator a = ir_allocator();
  5745. String name = e->token.string;
  5746. AstPackage *pkg = e->pkg;
  5747. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  5748. String pkgn = pkg->name;
  5749. GB_ASSERT(!rune_is_digit(pkgn[0]));
  5750. if (pkgn == "llvm") {
  5751. pkgn = str_lit("llvm$");
  5752. }
  5753. isize max_len = pkgn.len + 1 + name.len + 1;
  5754. bool require_suffix_id = is_type_polymorphic(e->type, true);
  5755. if (e->flags & EntityFlag_NotExported) {
  5756. require_suffix_id = true;
  5757. }
  5758. if (require_suffix_id) {
  5759. max_len += 21;
  5760. }
  5761. u8 *new_name = gb_alloc_array(a, u8, max_len);
  5762. isize new_name_len = gb_snprintf(
  5763. cast(char *)new_name, max_len,
  5764. "%.*s.%.*s", LIT(pkgn), LIT(name)
  5765. );
  5766. if (require_suffix_id) {
  5767. char *str = cast(char *)new_name + new_name_len-1;
  5768. isize len = max_len-new_name_len;
  5769. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  5770. new_name_len += extra-1;
  5771. }
  5772. return make_string(new_name, new_name_len-1);
  5773. }
  5774. void ir_mangle_add_sub_type_name(irModule *m, Entity *field, String parent) {
  5775. if (field->kind != Entity_TypeName) {
  5776. return;
  5777. }
  5778. if (is_type_proc(field->type)) {
  5779. set_procedure_abi_types(field->type);
  5780. }
  5781. String cn = field->token.string;
  5782. isize max_len = parent.len + 1 + 16 + 1 + cn.len;
  5783. bool require_suffix_id = is_type_polymorphic(field->type, true);
  5784. if (require_suffix_id) {
  5785. max_len += 21;
  5786. }
  5787. u8 *new_name = gb_alloc_array(ir_allocator(), u8, max_len);
  5788. isize new_name_len = gb_snprintf(cast(char *)new_name, max_len,
  5789. "%.*s.%.*s", LIT(parent), LIT(cn));
  5790. if (require_suffix_id) {
  5791. char *str = cast(char *)new_name + new_name_len-1;
  5792. isize len = max_len-new_name_len;
  5793. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)field->id);
  5794. new_name_len += extra-1;
  5795. }
  5796. String child = {new_name, new_name_len-1};
  5797. GB_ASSERT(child.len > 0);
  5798. ir_add_entity_name(m, field, child);
  5799. ir_gen_global_type_name(m, field, child);
  5800. }
  5801. irBranchBlocks ir_lookup_branch_blocks(irProcedure *proc, Ast *ident) {
  5802. GB_ASSERT(ident->kind == Ast_Ident);
  5803. Entity *e = entity_of_node(ident);
  5804. GB_ASSERT(e->kind == Entity_Label);
  5805. for_array(i, proc->branch_blocks) {
  5806. irBranchBlocks *b = &proc->branch_blocks[i];
  5807. if (b->label == e->Label.node) {
  5808. return *b;
  5809. }
  5810. }
  5811. GB_PANIC("Unreachable");
  5812. irBranchBlocks empty = {};
  5813. return empty;
  5814. }
  5815. irTargetList *ir_push_target_list(irProcedure *proc, Ast *label, irBlock *break_, irBlock *continue_, irBlock *fallthrough_) {
  5816. irTargetList *tl = gb_alloc_item(ir_allocator(), irTargetList);
  5817. tl->prev = proc->target_list;
  5818. tl->break_ = break_;
  5819. tl->continue_ = continue_;
  5820. tl->fallthrough_ = fallthrough_;
  5821. proc->target_list = tl;
  5822. if (label != nullptr) { // Set label blocks
  5823. GB_ASSERT(label->kind == Ast_Label);
  5824. for_array(i, proc->branch_blocks) {
  5825. irBranchBlocks *b = &proc->branch_blocks[i];
  5826. GB_ASSERT(b->label != nullptr && label != nullptr);
  5827. GB_ASSERT(b->label->kind == Ast_Label);
  5828. if (b->label == label) {
  5829. b->break_ = break_;
  5830. b->continue_ = continue_;
  5831. return tl;
  5832. }
  5833. }
  5834. GB_PANIC("ir_set_label_blocks: Unreachable");
  5835. }
  5836. return tl;
  5837. }
  5838. void ir_pop_target_list(irProcedure *proc) {
  5839. proc->target_list = proc->target_list->prev;
  5840. }
  5841. irValue *ir_gen_anonymous_proc_lit(irModule *m, String prefix_name, Ast *expr, irProcedure *proc) {
  5842. auto *found = map_get(&m->anonymous_proc_lits, hash_pointer(expr));
  5843. if (found != nullptr) {
  5844. return *found;
  5845. }
  5846. ast_node(pl, ProcLit, expr);
  5847. // NOTE(bill): Generate a new name
  5848. // parent$count
  5849. isize name_len = prefix_name.len + 1 + 8 + 1;
  5850. u8 *name_text = gb_alloc_array(ir_allocator(), u8, name_len);
  5851. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  5852. name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  5853. String name = make_string(name_text, name_len-1);
  5854. Type *type = type_of_expr(expr);
  5855. set_procedure_abi_types(type);
  5856. irValue *value = ir_value_procedure(m, nullptr, type, pl->type, pl->body, name);
  5857. value->Proc.tags = pl->tags;
  5858. value->Proc.inlining = pl->inlining;
  5859. value->Proc.parent = proc;
  5860. array_add(&m->procs_to_generate, value);
  5861. if (proc != nullptr) {
  5862. array_add(&proc->children, &value->Proc);
  5863. } else {
  5864. string_map_set(&m->members, name, value);
  5865. }
  5866. map_set(&m->anonymous_proc_lits, hash_pointer(expr), value);
  5867. return value;
  5868. }
  5869. void ir_gen_global_type_name(irModule *m, Entity *e, String name) {
  5870. if (e->type == nullptr) return;
  5871. if (e->kind == Entity_TypeName && e->type->kind == Type_Named) {
  5872. if (e != e->type->Named.type_name) {
  5873. // NOTE(bill): Is alias
  5874. return;
  5875. }
  5876. }
  5877. Type *bt = base_type(e->type);
  5878. bool is_poly = is_type_polymorphic(bt);
  5879. if (!is_poly) {
  5880. if (bt->kind == Type_Struct &&
  5881. bt->Struct.is_polymorphic &&
  5882. !bt->Struct.is_poly_specialized) {
  5883. is_poly = true;
  5884. }
  5885. }
  5886. if (is_poly) {
  5887. auto found = map_get(&m->info->gen_types, hash_pointer(e->type));
  5888. if (found != nullptr) {
  5889. for_array(i, *found) {
  5890. Entity *sub = (*found)[i];
  5891. // gb_printf_err("--> %.*s %p\n", LIT(sub->token.string), sub);
  5892. if (ir_min_dep_entity(m, sub)) {
  5893. ir_mangle_add_sub_type_name(m, sub, name);
  5894. }
  5895. }
  5896. }
  5897. return;
  5898. }
  5899. if (!ir_min_dep_entity(m, e)) {
  5900. return;
  5901. }
  5902. if (is_type_proc(e->type)) {
  5903. return;
  5904. }
  5905. irValue *t = ir_value_type_name(name, e->type);
  5906. ir_module_add_value(m, e, t);
  5907. string_map_set(&m->members, name, t);
  5908. // if (bt->kind == Type_Struct) {
  5909. // Scope *s = bt->Struct.scope;
  5910. // if (s != nullptr) {
  5911. // for_array(i, s->elements.entries) {
  5912. // Entity *e = s->elements.entries[i].value;
  5913. // if (e->kind == Entity_TypeName) {
  5914. // ir_mangle_add_sub_type_name(m, e, name);
  5915. // }
  5916. // }
  5917. // }
  5918. // }
  5919. }
  5920. void ir_build_defer_stmt(irProcedure *proc, irDefer d) {
  5921. irBlock *b = ir_new_block(proc, nullptr, "defer");
  5922. // NOTE(bill): The prev block may defer injection before it's terminator
  5923. irInstr *last_instr = ir_get_last_instr(proc->curr_block);
  5924. if (last_instr == nullptr || !ir_is_instr_terminating(last_instr)) {
  5925. ir_emit_jump(proc, b);
  5926. }
  5927. ir_start_block(proc, b);
  5928. ir_emit_comment(proc, str_lit("defer"));
  5929. if (d.kind == irDefer_Node) {
  5930. ir_build_stmt(proc, d.stmt);
  5931. } else if (d.kind == irDefer_Instr) {
  5932. // NOTE(bill): Need to make a new copy
  5933. irValue *instr = cast(irValue *)gb_alloc_copy(ir_allocator(), d.instr, gb_size_of(irValue));
  5934. ir_emit(proc, instr);
  5935. } else if (d.kind == irDefer_Proc) {
  5936. ir_emit_call(proc, d.proc.deferred, d.proc.result_as_args);
  5937. }
  5938. }
  5939. irValue *ir_emit_min(irProcedure *proc, Type *t, irValue *x, irValue *y) {
  5940. x = ir_emit_conv(proc, x, t);
  5941. y = ir_emit_conv(proc, y, t);
  5942. if (is_type_float(t)) {
  5943. gbAllocator a = ir_allocator();
  5944. i64 sz = 8*type_size_of(t);
  5945. auto args = array_make<irValue *>(ir_allocator(), 2);
  5946. args[0] = x;
  5947. args[1] = y;
  5948. switch (sz) {
  5949. case 32: return ir_emit_runtime_call(proc, "min_f32", args);
  5950. case 64: return ir_emit_runtime_call(proc, "min_f64", args);
  5951. }
  5952. GB_PANIC("Unknown float type");
  5953. }
  5954. return ir_emit_select(proc, ir_emit_comp(proc, Token_Lt, x, y), x, y);
  5955. }
  5956. irValue *ir_emit_max(irProcedure *proc, Type *t, irValue *x, irValue *y) {
  5957. x = ir_emit_conv(proc, x, t);
  5958. y = ir_emit_conv(proc, y, t);
  5959. if (is_type_float(t)) {
  5960. gbAllocator a = ir_allocator();
  5961. i64 sz = 8*type_size_of(t);
  5962. auto args = array_make<irValue *>(ir_allocator(), 2);
  5963. args[0] = x;
  5964. args[1] = y;
  5965. switch (sz) {
  5966. case 32: return ir_emit_runtime_call(proc, "max_f32", args);
  5967. case 64: return ir_emit_runtime_call(proc, "max_f64", args);
  5968. }
  5969. GB_PANIC("Unknown float type");
  5970. }
  5971. return ir_emit_select(proc, ir_emit_comp(proc, Token_Gt, x, y), x, y);
  5972. }
  5973. irValue *ir_emit_clamp(irProcedure *proc, Type *t, irValue *x, irValue *min, irValue *max) {
  5974. ir_emit_comment(proc, str_lit("clamp"));
  5975. irValue *z = nullptr;
  5976. z = ir_emit_max(proc, t, x, min);
  5977. z = ir_emit_min(proc, t, z, max);
  5978. return z;
  5979. }
  5980. irValue *ir_find_global_variable(irProcedure *proc, String name) {
  5981. AstPackage *pkg = proc->module->info->runtime_package;
  5982. Entity *e = scope_lookup_current(pkg->scope, name);
  5983. irValue **value = map_get(&proc->module->values, hash_entity(e));
  5984. GB_ASSERT_MSG(value != nullptr, "Unable to find global variable '%.*s'", LIT(name));
  5985. return *value;
  5986. }
  5987. void ir_build_stmt_list(irProcedure *proc, Slice<Ast *> stmts);
  5988. void ir_build_assign_op(irProcedure *proc, irAddr const &lhs, irValue *value, TokenKind op);
  5989. bool is_double_pointer(Type *t) {
  5990. if (!is_type_pointer(t)) {
  5991. return false;
  5992. }
  5993. Type *td = type_deref(t);
  5994. if (td == nullptr || td == t) {
  5995. return false;
  5996. }
  5997. return is_type_pointer(td);
  5998. }
  5999. irValue *ir_emit_source_code_location(irProcedure *proc, String procedure, TokenPos pos) {
  6000. gbAllocator a = ir_allocator();
  6001. irValue *v = ir_alloc_value(irValue_SourceCodeLocation);
  6002. v->SourceCodeLocation.file = ir_find_or_add_entity_string(proc->module, pos.file);
  6003. v->SourceCodeLocation.line = ir_const_int(pos.line);
  6004. v->SourceCodeLocation.column = ir_const_int(pos.column);
  6005. v->SourceCodeLocation.procedure = ir_find_or_add_entity_string(proc->module, procedure);
  6006. return v;
  6007. }
  6008. irValue *ir_emit_source_code_location(irProcedure *proc, Ast *node) {
  6009. String proc_name = {};
  6010. if (proc->entity) {
  6011. proc_name = proc->entity->token.string;
  6012. }
  6013. TokenPos pos = {};
  6014. if (node) {
  6015. pos = ast_token(node).pos;
  6016. }
  6017. return ir_emit_source_code_location(proc, proc_name, pos);
  6018. }
  6019. void ir_emit_increment(irProcedure *proc, irValue *addr) {
  6020. GB_ASSERT(is_type_pointer(ir_type(addr)));
  6021. Type *type = type_deref(ir_type(addr));
  6022. ir_emit_store(proc, addr, ir_emit_arith(proc, Token_Add, ir_emit_load(proc, addr), v_one, type));
  6023. }
  6024. void ir_init_data_with_defaults(irProcedure *proc, irValue *ptr, irValue *count, Ast *expr) {
  6025. Type *elem_type = type_deref(ir_type(ptr));
  6026. GB_ASSERT(is_type_struct(elem_type) || is_type_array(elem_type));
  6027. irValue *index = ir_add_local_generated(proc, t_int, false);
  6028. ir_emit_store(proc, index, ir_const_int(0));
  6029. irBlock *loop = nullptr;
  6030. irBlock *done = nullptr;
  6031. irBlock *body = nullptr;
  6032. loop = ir_new_block(proc, nullptr, "make.init.loop");
  6033. ir_emit_jump(proc, loop);
  6034. ir_start_block(proc, loop);
  6035. body = ir_new_block(proc, nullptr, "make.init.body");
  6036. done = ir_new_block(proc, nullptr, "make.init.done");
  6037. irValue *cond = ir_emit_comp(proc, Token_Lt, ir_emit_load(proc, index), count);
  6038. ir_emit_if(proc, cond, body, done);
  6039. ir_start_block(proc, body);
  6040. irValue *offset_ptr = ir_emit_ptr_offset(proc, ptr, ir_emit_load(proc, index));
  6041. ir_emit(proc, ir_instr_zero_init(proc, offset_ptr)); // Use simple zero for this
  6042. // ir_emit_zero_init(proc, offset_ptr, expr);
  6043. ir_emit_increment(proc, index);
  6044. ir_emit_jump(proc, loop);
  6045. ir_start_block(proc, done);
  6046. }
  6047. irValue *ir_build_builtin_proc(irProcedure *proc, Ast *expr, TypeAndValue tv, BuiltinProcId id) {
  6048. ast_node(ce, CallExpr, expr);
  6049. switch (id) {
  6050. case BuiltinProc_DIRECTIVE: {
  6051. ast_node(bd, BasicDirective, ce->proc);
  6052. String name = bd->name;
  6053. GB_ASSERT(name == "location");
  6054. String procedure = proc->entity->token.string;
  6055. TokenPos pos = ast_token(ce->proc).pos;
  6056. if (ce->args.count > 0) {
  6057. Ast *ident = unselector_expr(ce->args[0]);
  6058. GB_ASSERT(ident->kind == Ast_Ident);
  6059. Entity *e = entity_of_node(ident);
  6060. GB_ASSERT(e != nullptr);
  6061. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  6062. procedure = e->parent_proc_decl->entity->token.string;
  6063. } else {
  6064. procedure = str_lit("");
  6065. }
  6066. pos = e->token.pos;
  6067. }
  6068. return ir_emit_source_code_location(proc, procedure, pos);
  6069. }
  6070. case BuiltinProc_type_info_of: {
  6071. Ast *arg = ce->args[0];
  6072. TypeAndValue tav = type_and_value_of_expr(arg);
  6073. if (tav.mode == Addressing_Type) {
  6074. Type *t = default_type(type_of_expr(arg));
  6075. return ir_type_info(proc, t);
  6076. }
  6077. GB_ASSERT(is_type_typeid(tav.type));
  6078. auto args = array_make<irValue *>(ir_allocator(), 1);
  6079. args[0] = ir_build_expr(proc, arg);
  6080. return ir_emit_runtime_call(proc, "__type_info_of", args);
  6081. }
  6082. case BuiltinProc_typeid_of: {
  6083. Ast *arg = ce->args[0];
  6084. TypeAndValue tav = type_and_value_of_expr(arg);
  6085. if (tav.mode == Addressing_Type) {
  6086. Type *t = default_type(type_of_expr(arg));
  6087. return ir_typeid(proc->module, t);
  6088. }
  6089. Type *t = base_type(tav.type);
  6090. GB_ASSERT(are_types_identical(t, t_type_info_ptr));
  6091. auto args = array_make<irValue *>(ir_allocator(), 1);
  6092. args[0] = ir_emit_conv(proc, ir_build_expr(proc, arg), t_type_info_ptr);
  6093. return ir_emit_runtime_call(proc, "__typeid_of", args);
  6094. }
  6095. case BuiltinProc_len: {
  6096. irValue *v = ir_build_expr(proc, ce->args[0]);
  6097. Type *t = base_type(ir_type(v));
  6098. if (is_type_pointer(t)) {
  6099. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6100. v = ir_emit_load(proc, v);
  6101. t = type_deref(t);
  6102. }
  6103. if (is_type_cstring(t)) {
  6104. return ir_cstring_len(proc, v);
  6105. } else if (is_type_string(t)) {
  6106. return ir_string_len(proc, v);
  6107. } else if (is_type_array(t)) {
  6108. GB_PANIC("Array lengths are constant");
  6109. } else if (is_type_slice(t)) {
  6110. return ir_slice_len(proc, v);
  6111. } else if (is_type_dynamic_array(t)) {
  6112. return ir_dynamic_array_len(proc, v);
  6113. } else if (is_type_map(t)) {
  6114. return ir_map_len(proc, v);
  6115. } else if (is_type_soa_struct(t)) {
  6116. return ir_soa_struct_len(proc, v);
  6117. }
  6118. GB_PANIC("Unreachable");
  6119. break;
  6120. }
  6121. case BuiltinProc_cap: {
  6122. irValue *v = ir_build_expr(proc, ce->args[0]);
  6123. Type *t = base_type(ir_type(v));
  6124. if (is_type_pointer(t)) {
  6125. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6126. v = ir_emit_load(proc, v);
  6127. t = type_deref(t);
  6128. }
  6129. if (is_type_string(t)) {
  6130. GB_PANIC("Unreachable");
  6131. } else if (is_type_array(t)) {
  6132. GB_PANIC("Array lengths are constant");
  6133. } else if (is_type_slice(t)) {
  6134. return ir_slice_len(proc, v);
  6135. } else if (is_type_dynamic_array(t)) {
  6136. return ir_dynamic_array_cap(proc, v);
  6137. } else if (is_type_map(t)) {
  6138. return ir_map_cap(proc, v);
  6139. } else if (is_type_soa_struct(t)) {
  6140. return ir_soa_struct_cap(proc, v);
  6141. }
  6142. GB_PANIC("Unreachable");
  6143. break;
  6144. }
  6145. case BuiltinProc_swizzle: {
  6146. ir_emit_comment(proc, str_lit("swizzle.begin"));
  6147. irAddr addr = ir_build_addr(proc, ce->args[0]);
  6148. isize index_count = ce->args.count-1;
  6149. if (index_count == 0) {
  6150. return ir_addr_load(proc, addr);
  6151. }
  6152. irValue *src = ir_addr_get_ptr(proc, addr);
  6153. // TODO(bill): Should this be zeroed or not?
  6154. irValue *dst = ir_add_local_generated(proc, tv.type, true);
  6155. for (i32 i = 1; i < ce->args.count; i++) {
  6156. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  6157. GB_ASSERT(is_type_integer(tv.type));
  6158. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  6159. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  6160. i32 dst_index = i-1;
  6161. irValue *src_elem = ir_emit_array_epi(proc, src, src_index);
  6162. irValue *dst_elem = ir_emit_array_epi(proc, dst, dst_index);
  6163. ir_emit_store(proc, dst_elem, ir_emit_load(proc, src_elem));
  6164. }
  6165. ir_emit_comment(proc, str_lit("swizzle.end"));
  6166. return ir_emit_load(proc, dst);
  6167. }
  6168. case BuiltinProc_complex: {
  6169. ir_emit_comment(proc, str_lit("complex"));
  6170. irValue *real = ir_build_expr(proc, ce->args[0]);
  6171. irValue *imag = ir_build_expr(proc, ce->args[1]);
  6172. irValue *dst = ir_add_local_generated(proc, tv.type, false);
  6173. Type *ft = base_complex_elem_type(tv.type);
  6174. real = ir_emit_conv(proc, real, ft);
  6175. imag = ir_emit_conv(proc, imag, ft);
  6176. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 0), real);
  6177. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 1), imag);
  6178. return ir_emit_load(proc, dst);
  6179. }
  6180. case BuiltinProc_quaternion: {
  6181. ir_emit_comment(proc, str_lit("quaternion"));
  6182. irValue *real = ir_build_expr(proc, ce->args[0]);
  6183. irValue *imag = ir_build_expr(proc, ce->args[1]);
  6184. irValue *jmag = ir_build_expr(proc, ce->args[2]);
  6185. irValue *kmag = ir_build_expr(proc, ce->args[3]);
  6186. // @QuaternionLayout
  6187. irValue *dst = ir_add_local_generated(proc, tv.type, false);
  6188. Type *ft = base_complex_elem_type(tv.type);
  6189. real = ir_emit_conv(proc, real, ft);
  6190. imag = ir_emit_conv(proc, imag, ft);
  6191. jmag = ir_emit_conv(proc, jmag, ft);
  6192. kmag = ir_emit_conv(proc, kmag, ft);
  6193. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 3), real);
  6194. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 0), imag);
  6195. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 1), jmag);
  6196. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 2), kmag);
  6197. return ir_emit_load(proc, dst);
  6198. }
  6199. case BuiltinProc_real: {
  6200. ir_emit_comment(proc, str_lit("real"));
  6201. irValue *val = ir_build_expr(proc, ce->args[0]);
  6202. if (is_type_complex(ir_type(val))) {
  6203. irValue *real = ir_emit_struct_ev(proc, val, 0);
  6204. return ir_emit_conv(proc, real, tv.type);
  6205. } else if (is_type_quaternion(ir_type(val))) {
  6206. // @QuaternionLayout
  6207. irValue *real = ir_emit_struct_ev(proc, val, 3);
  6208. return ir_emit_conv(proc, real, tv.type);
  6209. }
  6210. GB_PANIC("invalid type for real");
  6211. return nullptr;
  6212. }
  6213. case BuiltinProc_imag: {
  6214. ir_emit_comment(proc, str_lit("imag"));
  6215. irValue *val = ir_build_expr(proc, ce->args[0]);
  6216. if (is_type_complex(ir_type(val))) {
  6217. irValue *imag = ir_emit_struct_ev(proc, val, 1);
  6218. return ir_emit_conv(proc, imag, tv.type);
  6219. } else if (is_type_quaternion(ir_type(val))) {
  6220. // @QuaternionLayout
  6221. irValue *imag = ir_emit_struct_ev(proc, val, 0);
  6222. return ir_emit_conv(proc, imag, tv.type);
  6223. }
  6224. GB_PANIC("invalid type for imag");
  6225. return nullptr;
  6226. }
  6227. case BuiltinProc_jmag: {
  6228. ir_emit_comment(proc, str_lit("jmag"));
  6229. irValue *val = ir_build_expr(proc, ce->args[0]);
  6230. if (is_type_quaternion(ir_type(val))) {
  6231. // @QuaternionLayout
  6232. irValue *imag = ir_emit_struct_ev(proc, val, 1);
  6233. return ir_emit_conv(proc, imag, tv.type);
  6234. }
  6235. GB_PANIC("invalid type for jmag");
  6236. return nullptr;
  6237. }
  6238. case BuiltinProc_kmag: {
  6239. ir_emit_comment(proc, str_lit("kmag"));
  6240. irValue *val = ir_build_expr(proc, ce->args[0]);
  6241. if (is_type_quaternion(ir_type(val))) {
  6242. // @QuaternionLayout
  6243. irValue *imag = ir_emit_struct_ev(proc, val, 2);
  6244. return ir_emit_conv(proc, imag, tv.type);
  6245. }
  6246. GB_PANIC("invalid type for kmag");
  6247. return nullptr;
  6248. }
  6249. case BuiltinProc_conj: {
  6250. ir_emit_comment(proc, str_lit("conj"));
  6251. irValue *val = ir_build_expr(proc, ce->args[0]);
  6252. irValue *res = nullptr;
  6253. Type *t = ir_type(val);
  6254. if (is_type_complex(t)) {
  6255. res = ir_add_local_generated(proc, tv.type, false);
  6256. irValue *real = ir_emit_struct_ev(proc, val, 0);
  6257. irValue *imag = ir_emit_struct_ev(proc, val, 1);
  6258. imag = ir_emit_unary_arith(proc, Token_Sub, imag, ir_type(imag));
  6259. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), real);
  6260. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), imag);
  6261. } else if (is_type_quaternion(t)) {
  6262. // @QuaternionLayout
  6263. res = ir_add_local_generated(proc, tv.type, false);
  6264. irValue *real = ir_emit_struct_ev(proc, val, 3);
  6265. irValue *imag = ir_emit_struct_ev(proc, val, 0);
  6266. irValue *jmag = ir_emit_struct_ev(proc, val, 1);
  6267. irValue *kmag = ir_emit_struct_ev(proc, val, 2);
  6268. imag = ir_emit_unary_arith(proc, Token_Sub, imag, ir_type(imag));
  6269. jmag = ir_emit_unary_arith(proc, Token_Sub, jmag, ir_type(jmag));
  6270. kmag = ir_emit_unary_arith(proc, Token_Sub, kmag, ir_type(kmag));
  6271. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 3), real);
  6272. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), imag);
  6273. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), jmag);
  6274. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 2), kmag);
  6275. }
  6276. return ir_emit_load(proc, res);
  6277. }
  6278. case BuiltinProc_expand_to_tuple: {
  6279. ir_emit_comment(proc, str_lit("expand_to_tuple"));
  6280. irValue *val = ir_build_expr(proc, ce->args[0]);
  6281. Type *t = base_type(ir_type(val));
  6282. if (!is_type_tuple(tv.type)) {
  6283. if (t->kind == Type_Struct) {
  6284. GB_ASSERT(t->Struct.fields.count == 1);
  6285. return ir_emit_struct_ev(proc, val, 0);
  6286. } else if (t->kind == Type_Array) {
  6287. GB_ASSERT(t->Array.count == 1);
  6288. return ir_emit_array_epi(proc, val, 0);
  6289. } else {
  6290. GB_PANIC("Unknown type of expand_to_tuple");
  6291. }
  6292. }
  6293. GB_ASSERT(is_type_tuple(tv.type));
  6294. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  6295. irValue *tuple = ir_add_local_generated(proc, tv.type, false);
  6296. if (t->kind == Type_Struct) {
  6297. for_array(src_index, t->Struct.fields) {
  6298. Entity *field = t->Struct.fields[src_index];
  6299. i32 field_index = field->Variable.field_index;
  6300. irValue *f = ir_emit_struct_ev(proc, val, field_index);
  6301. irValue *ep = ir_emit_struct_ep(proc, tuple, cast(i32)src_index);
  6302. ir_emit_store(proc, ep, f);
  6303. }
  6304. } else if (t->kind == Type_Array) {
  6305. // TODO(bill): Clean-up this code
  6306. irValue *ap = ir_address_from_load_or_generate_local(proc, val);
  6307. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  6308. irValue *f = ir_emit_load(proc, ir_emit_array_epi(proc, ap, i));
  6309. irValue *ep = ir_emit_struct_ep(proc, tuple, i);
  6310. ir_emit_store(proc, ep, f);
  6311. }
  6312. } else {
  6313. GB_PANIC("Unknown type of expand_to_tuple");
  6314. }
  6315. return ir_emit_load(proc, tuple);
  6316. }
  6317. case BuiltinProc_min: {
  6318. ir_emit_comment(proc, str_lit("min"));
  6319. Type *t = type_of_expr(expr);
  6320. if (ce->args.count == 2) {
  6321. return ir_emit_min(proc, t, ir_build_expr(proc, ce->args[0]), ir_build_expr(proc, ce->args[1]));
  6322. } else {
  6323. irValue *x = ir_build_expr(proc, ce->args[0]);
  6324. for (isize i = 1; i < ce->args.count; i++) {
  6325. x = ir_emit_min(proc, t, x, ir_build_expr(proc, ce->args[i]));
  6326. }
  6327. return x;
  6328. }
  6329. }
  6330. case BuiltinProc_max: {
  6331. ir_emit_comment(proc, str_lit("max"));
  6332. Type *t = type_of_expr(expr);
  6333. if (ce->args.count == 2) {
  6334. return ir_emit_max(proc, t, ir_build_expr(proc, ce->args[0]), ir_build_expr(proc, ce->args[1]));
  6335. } else {
  6336. irValue *x = ir_build_expr(proc, ce->args[0]);
  6337. for (isize i = 1; i < ce->args.count; i++) {
  6338. x = ir_emit_max(proc, t, x, ir_build_expr(proc, ce->args[i]));
  6339. }
  6340. return x;
  6341. }
  6342. }
  6343. case BuiltinProc_abs: {
  6344. gbAllocator a = ir_allocator();
  6345. irValue *x = ir_build_expr(proc, ce->args[0]);
  6346. Type *t = ir_type(x);
  6347. if (is_type_unsigned(t)) {
  6348. return x;
  6349. }
  6350. ir_emit_comment(proc, str_lit("abs"));
  6351. if (is_type_quaternion(t)) {
  6352. i64 sz = 8*type_size_of(t);
  6353. auto args = array_make<irValue *>(ir_allocator(), 1);
  6354. args[0] = x;
  6355. switch (sz) {
  6356. case 128: return ir_emit_runtime_call(proc, "abs_quaternion128", args);
  6357. case 256: return ir_emit_runtime_call(proc, "abs_quaternion256", args);
  6358. }
  6359. GB_PANIC("Unknown complex type");
  6360. } else if (is_type_complex(t)) {
  6361. i64 sz = 8*type_size_of(t);
  6362. auto args = array_make<irValue *>(ir_allocator(), 1);
  6363. args[0] = x;
  6364. switch (sz) {
  6365. case 64: return ir_emit_runtime_call(proc, "abs_complex64", args);
  6366. case 128: return ir_emit_runtime_call(proc, "abs_complex128", args);
  6367. }
  6368. GB_PANIC("Unknown complex type");
  6369. } else if (is_type_float(t)) {
  6370. i64 sz = 8*type_size_of(t);
  6371. auto args = array_make<irValue *>(ir_allocator(), 1);
  6372. args[0] = x;
  6373. switch (sz) {
  6374. case 32: return ir_emit_runtime_call(proc, "abs_f32", args);
  6375. case 64: return ir_emit_runtime_call(proc, "abs_f64", args);
  6376. }
  6377. GB_PANIC("Unknown float type");
  6378. }
  6379. irValue *zero = ir_emit_conv(proc, v_zero, t);
  6380. irValue *cond = ir_emit_comp(proc, Token_Lt, x, zero);
  6381. irValue *neg = ir_emit(proc, ir_instr_unary_op(proc, Token_Sub, x, t));
  6382. return ir_emit_select(proc, cond, neg, x);
  6383. }
  6384. case BuiltinProc_clamp:
  6385. ir_emit_comment(proc, str_lit("clamp"));
  6386. return ir_emit_clamp(proc, type_of_expr(expr),
  6387. ir_build_expr(proc, ce->args[0]),
  6388. ir_build_expr(proc, ce->args[1]),
  6389. ir_build_expr(proc, ce->args[2]));
  6390. // "Intrinsics"
  6391. case BuiltinProc_alloca:
  6392. {
  6393. auto args = array_make<irValue *>(permanent_allocator(), 2);
  6394. args[0] = ir_emit_conv(proc, ir_build_expr(proc, ce->args[0]), t_i32);
  6395. args[1] = ir_build_expr(proc, ce->args[1]);
  6396. return ir_emit(proc, ir_instr_inline_code(proc, id, args, t_u8_ptr));
  6397. }
  6398. case BuiltinProc_cpu_relax:
  6399. return ir_emit(proc, ir_instr_inline_code(proc, id, {}, nullptr));
  6400. case BuiltinProc_atomic_fence:
  6401. case BuiltinProc_atomic_fence_acq:
  6402. case BuiltinProc_atomic_fence_rel:
  6403. case BuiltinProc_atomic_fence_acqrel:
  6404. return ir_emit(proc, ir_instr_atomic_fence(proc, id));
  6405. case BuiltinProc_atomic_store:
  6406. case BuiltinProc_atomic_store_rel:
  6407. case BuiltinProc_atomic_store_relaxed:
  6408. case BuiltinProc_atomic_store_unordered: {
  6409. irValue *dst = ir_build_expr(proc, ce->args[0]);
  6410. irValue *val = ir_build_expr(proc, ce->args[1]);
  6411. val = ir_emit_conv(proc, val, type_deref(ir_type(dst)));
  6412. return ir_emit(proc, ir_instr_atomic_store(proc, dst, val, id));
  6413. }
  6414. case BuiltinProc_atomic_load:
  6415. case BuiltinProc_atomic_load_acq:
  6416. case BuiltinProc_atomic_load_relaxed:
  6417. case BuiltinProc_atomic_load_unordered: {
  6418. irValue *dst = ir_build_expr(proc, ce->args[0]);
  6419. return ir_emit(proc, ir_instr_atomic_load(proc, dst, id));
  6420. }
  6421. case BuiltinProc_atomic_add:
  6422. case BuiltinProc_atomic_add_acq:
  6423. case BuiltinProc_atomic_add_rel:
  6424. case BuiltinProc_atomic_add_acqrel:
  6425. case BuiltinProc_atomic_add_relaxed:
  6426. case BuiltinProc_atomic_sub:
  6427. case BuiltinProc_atomic_sub_acq:
  6428. case BuiltinProc_atomic_sub_rel:
  6429. case BuiltinProc_atomic_sub_acqrel:
  6430. case BuiltinProc_atomic_sub_relaxed:
  6431. case BuiltinProc_atomic_and:
  6432. case BuiltinProc_atomic_and_acq:
  6433. case BuiltinProc_atomic_and_rel:
  6434. case BuiltinProc_atomic_and_acqrel:
  6435. case BuiltinProc_atomic_and_relaxed:
  6436. case BuiltinProc_atomic_nand:
  6437. case BuiltinProc_atomic_nand_acq:
  6438. case BuiltinProc_atomic_nand_rel:
  6439. case BuiltinProc_atomic_nand_acqrel:
  6440. case BuiltinProc_atomic_nand_relaxed:
  6441. case BuiltinProc_atomic_or:
  6442. case BuiltinProc_atomic_or_acq:
  6443. case BuiltinProc_atomic_or_rel:
  6444. case BuiltinProc_atomic_or_acqrel:
  6445. case BuiltinProc_atomic_or_relaxed:
  6446. case BuiltinProc_atomic_xor:
  6447. case BuiltinProc_atomic_xor_acq:
  6448. case BuiltinProc_atomic_xor_rel:
  6449. case BuiltinProc_atomic_xor_acqrel:
  6450. case BuiltinProc_atomic_xor_relaxed:
  6451. case BuiltinProc_atomic_xchg:
  6452. case BuiltinProc_atomic_xchg_acq:
  6453. case BuiltinProc_atomic_xchg_rel:
  6454. case BuiltinProc_atomic_xchg_acqrel:
  6455. case BuiltinProc_atomic_xchg_relaxed: {
  6456. irValue *dst = ir_build_expr(proc, ce->args[0]);
  6457. irValue *val = ir_build_expr(proc, ce->args[1]);
  6458. val = ir_emit_conv(proc, val, type_deref(ir_type(dst)));
  6459. return ir_emit(proc, ir_instr_atomic_rmw(proc, dst, val, id));
  6460. }
  6461. case BuiltinProc_atomic_cxchg:
  6462. case BuiltinProc_atomic_cxchg_acq:
  6463. case BuiltinProc_atomic_cxchg_rel:
  6464. case BuiltinProc_atomic_cxchg_acqrel:
  6465. case BuiltinProc_atomic_cxchg_relaxed:
  6466. case BuiltinProc_atomic_cxchg_failrelaxed:
  6467. case BuiltinProc_atomic_cxchg_failacq:
  6468. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  6469. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  6470. case BuiltinProc_atomic_cxchgweak:
  6471. case BuiltinProc_atomic_cxchgweak_acq:
  6472. case BuiltinProc_atomic_cxchgweak_rel:
  6473. case BuiltinProc_atomic_cxchgweak_acqrel:
  6474. case BuiltinProc_atomic_cxchgweak_relaxed:
  6475. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  6476. case BuiltinProc_atomic_cxchgweak_failacq:
  6477. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  6478. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  6479. Type *type = expr->tav.type;
  6480. irValue *address = ir_build_expr(proc, ce->args[0]);
  6481. Type *elem = type_deref(ir_type(address));
  6482. irValue *old_value = ir_build_expr(proc, ce->args[1]);
  6483. irValue *new_value = ir_build_expr(proc, ce->args[2]);
  6484. old_value = ir_emit_conv(proc, old_value, elem);
  6485. new_value = ir_emit_conv(proc, new_value, elem);
  6486. return ir_emit(proc, ir_instr_atomic_cxchg(proc, type, address, old_value, new_value, id));
  6487. }
  6488. case BuiltinProc_type_equal_proc:
  6489. return ir_get_equal_proc_for_type(proc->module, ce->args[0]->tav.type);
  6490. case BuiltinProc_type_hasher_proc:
  6491. return ir_get_hasher_proc_for_type(proc->module, ce->args[0]->tav.type);
  6492. }
  6493. GB_PANIC("Unhandled built-in procedure");
  6494. return nullptr;
  6495. }
  6496. irValue *ir_handle_param_value(irProcedure *proc, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  6497. switch (param_value.kind) {
  6498. case ParameterValue_Constant:
  6499. if (is_type_constant_type(parameter_type)) {
  6500. return ir_value_constant(parameter_type, param_value.value);
  6501. } else {
  6502. ExactValue ev = param_value.value;
  6503. irValue *arg = nullptr;
  6504. Type *type = type_of_expr(param_value.original_ast_expr);
  6505. if (type != nullptr) {
  6506. arg = ir_value_constant(type, ev);
  6507. } else {
  6508. arg = ir_value_constant(parameter_type, param_value.value);
  6509. }
  6510. return ir_emit_conv(proc, arg, parameter_type);
  6511. }
  6512. case ParameterValue_Nil:
  6513. return ir_value_nil(parameter_type);
  6514. case ParameterValue_Location:
  6515. {
  6516. String proc_name = {};
  6517. if (proc->entity != nullptr) {
  6518. proc_name = proc->entity->token.string;
  6519. }
  6520. return ir_emit_source_code_location(proc, proc_name, pos);
  6521. }
  6522. case ParameterValue_Value:
  6523. return ir_build_expr(proc, param_value.ast_value);
  6524. }
  6525. return ir_value_nil(parameter_type);
  6526. }
  6527. irValue *ir_build_expr_internal(irProcedure *proc, Ast *expr);
  6528. irValue *ir_build_expr(irProcedure *proc, Ast *expr) {
  6529. u64 prev_state_flags = proc->module->state_flags;
  6530. defer (proc->module->state_flags = prev_state_flags);
  6531. if (expr->state_flags != 0) {
  6532. u64 in = expr->state_flags;
  6533. u64 out = proc->module->state_flags;
  6534. if (in & StateFlag_bounds_check) {
  6535. out |= StateFlag_bounds_check;
  6536. out &= ~StateFlag_no_bounds_check;
  6537. } else if (in & StateFlag_no_bounds_check) {
  6538. out |= StateFlag_no_bounds_check;
  6539. out &= ~StateFlag_bounds_check;
  6540. }
  6541. proc->module->state_flags = out;
  6542. }
  6543. irValue *v = ir_build_expr_internal(proc, expr);
  6544. return v;
  6545. }
  6546. irValue *ir_build_call_expr(irProcedure *proc, Ast *expr) {
  6547. ast_node(ce, CallExpr, expr);
  6548. TypeAndValue tv = type_and_value_of_expr(expr);
  6549. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  6550. AddressingMode proc_mode = proc_tv.mode;
  6551. if (proc_mode == Addressing_Type) {
  6552. GB_ASSERT(ce->args.count == 1);
  6553. irValue *x = ir_build_expr(proc, ce->args[0]);
  6554. irValue *y = ir_emit_conv(proc, x, tv.type);
  6555. return y;
  6556. }
  6557. Ast *p = unparen_expr(ce->proc);
  6558. if (proc_mode == Addressing_Builtin) {
  6559. Entity *e = entity_of_node(p);
  6560. BuiltinProcId id = BuiltinProc_Invalid;
  6561. if (e != nullptr) {
  6562. id = cast(BuiltinProcId)e->Builtin.id;
  6563. } else {
  6564. id = BuiltinProc_DIRECTIVE;
  6565. }
  6566. return ir_build_builtin_proc(proc, expr, tv, id);
  6567. }
  6568. // NOTE(bill): Regular call
  6569. irValue *value = nullptr;
  6570. Ast *proc_expr = unparen_expr(ce->proc);
  6571. if (proc_expr->tav.mode == Addressing_Constant) {
  6572. ExactValue v = proc_expr->tav.value;
  6573. switch (v.kind) {
  6574. case ExactValue_Integer:
  6575. {
  6576. u64 u = big_int_to_u64(&v.value_integer);
  6577. irValue *x = ir_const_uintptr(u);
  6578. x = ir_emit_conv(proc, x, t_rawptr);
  6579. value = ir_emit_conv(proc, x, proc_expr->tav.type);
  6580. break;
  6581. }
  6582. case ExactValue_Pointer:
  6583. {
  6584. u64 u = cast(u64)v.value_pointer;
  6585. irValue *x = ir_const_uintptr(u);
  6586. x = ir_emit_conv(proc, x, t_rawptr);
  6587. value = ir_emit_conv(proc, x, proc_expr->tav.type);
  6588. break;
  6589. }
  6590. }
  6591. }
  6592. if (value == nullptr) {
  6593. value = ir_build_expr(proc, proc_expr);
  6594. }
  6595. GB_ASSERT(value != nullptr);
  6596. Type *proc_type_ = base_type(ir_type(value));
  6597. GB_ASSERT(proc_type_->kind == Type_Proc);
  6598. TypeProc *pt = &proc_type_->Proc;
  6599. set_procedure_abi_types(proc_type_);
  6600. if (is_call_expr_field_value(ce)) {
  6601. auto args = array_make<irValue *>(ir_allocator(), pt->param_count);
  6602. for_array(arg_index, ce->args) {
  6603. Ast *arg = ce->args[arg_index];
  6604. ast_node(fv, FieldValue, arg);
  6605. GB_ASSERT(fv->field->kind == Ast_Ident);
  6606. String name = fv->field->Ident.token.string;
  6607. isize index = lookup_procedure_parameter(pt, name);
  6608. GB_ASSERT(index >= 0);
  6609. TypeAndValue tav = type_and_value_of_expr(fv->value);
  6610. if (tav.mode == Addressing_Type) {
  6611. args[index] = ir_value_nil(tav.type);
  6612. } else {
  6613. args[index] = ir_build_expr(proc, fv->value);
  6614. }
  6615. }
  6616. TypeTuple *params = &pt->params->Tuple;
  6617. for (isize i = 0; i < args.count; i++) {
  6618. Entity *e = params->variables[i];
  6619. if (e->kind == Entity_TypeName) {
  6620. args[i] = ir_value_nil(e->type);
  6621. } else if (e->kind == Entity_Constant) {
  6622. continue;
  6623. } else {
  6624. GB_ASSERT(e->kind == Entity_Variable);
  6625. if (args[i] == nullptr) {
  6626. args[i] = ir_handle_param_value(proc, e->type, e->Variable.param_value, ast_token(expr).pos);
  6627. } else {
  6628. args[i] = ir_emit_conv(proc, args[i], e->type);
  6629. }
  6630. }
  6631. }
  6632. return ir_emit_call(proc, value, args, ce->inlining, proc->return_ptr_hint_ast == expr);
  6633. }
  6634. isize arg_index = 0;
  6635. isize arg_count = 0;
  6636. for_array(i, ce->args) {
  6637. Ast *arg = ce->args[i];
  6638. TypeAndValue tav = type_and_value_of_expr(arg);
  6639. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  6640. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  6641. Type *at = tav.type;
  6642. if (at->kind == Type_Tuple) {
  6643. arg_count += at->Tuple.variables.count;
  6644. } else {
  6645. arg_count++;
  6646. }
  6647. }
  6648. isize param_count = 0;
  6649. if (pt->params) {
  6650. GB_ASSERT(pt->params->kind == Type_Tuple);
  6651. param_count = pt->params->Tuple.variables.count;
  6652. }
  6653. auto args = array_make<irValue *>(ir_allocator(), cast(isize)gb_max(param_count, arg_count));
  6654. isize variadic_index = pt->variadic_index;
  6655. bool variadic = pt->variadic && variadic_index >= 0;
  6656. bool vari_expand = ce->ellipsis.pos.line != 0;
  6657. bool is_c_vararg = pt->c_vararg;
  6658. TypeTuple *param_tuple = nullptr;
  6659. if (pt->params) {
  6660. GB_ASSERT(pt->params->kind == Type_Tuple);
  6661. param_tuple = &pt->params->Tuple;
  6662. }
  6663. for_array(i, ce->args) {
  6664. Ast *arg = ce->args[i];
  6665. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  6666. if (arg_tv.mode == Addressing_Type) {
  6667. args[arg_index++] = ir_value_nil(arg_tv.type);
  6668. } else {
  6669. irValue *a = ir_build_expr(proc, arg);
  6670. Type *at = ir_type(a);
  6671. if (at->kind == Type_Tuple) {
  6672. for_array(i, at->Tuple.variables) {
  6673. Entity *e = at->Tuple.variables[i];
  6674. irValue *v = ir_emit_struct_ev(proc, a, cast(i32)i);
  6675. args[arg_index++] = v;
  6676. }
  6677. } else {
  6678. args[arg_index++] = a;
  6679. }
  6680. }
  6681. }
  6682. if (param_count > 0) {
  6683. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  6684. GB_ASSERT(param_count < 1000000);
  6685. if (arg_count < param_count) {
  6686. isize end = cast(isize)param_count;
  6687. if (variadic) {
  6688. end = variadic_index;
  6689. }
  6690. while (arg_index < end) {
  6691. Entity *e = param_tuple->variables[arg_index];
  6692. GB_ASSERT(e->kind == Entity_Variable);
  6693. args[arg_index++] = ir_handle_param_value(proc, e->type, e->Variable.param_value, ast_token(expr).pos);
  6694. }
  6695. }
  6696. if (is_c_vararg) {
  6697. GB_ASSERT(variadic);
  6698. GB_ASSERT(!vari_expand);
  6699. isize i = 0;
  6700. for (; i < variadic_index; i++) {
  6701. Entity *e = param_tuple->variables[i];
  6702. if (e->kind == Entity_Variable) {
  6703. args[i] = ir_emit_conv(proc, args[i], e->type);
  6704. }
  6705. }
  6706. Type *variadic_type = param_tuple->variables[i]->type;
  6707. GB_ASSERT(is_type_slice(variadic_type));
  6708. variadic_type = base_type(variadic_type)->Slice.elem;
  6709. if (!is_type_any(variadic_type)) {
  6710. for (; i < arg_count; i++) {
  6711. args[i] = ir_emit_conv(proc, args[i], variadic_type);
  6712. }
  6713. } else {
  6714. for (; i < arg_count; i++) {
  6715. args[i] = ir_emit_conv(proc, args[i], default_type(ir_type(args[i])));
  6716. }
  6717. }
  6718. } else if (variadic) {
  6719. isize i = 0;
  6720. for (; i < variadic_index; i++) {
  6721. Entity *e = param_tuple->variables[i];
  6722. if (e->kind == Entity_Variable) {
  6723. args[i] = ir_emit_conv(proc, args[i], e->type);
  6724. }
  6725. }
  6726. if (!vari_expand) {
  6727. Type *variadic_type = param_tuple->variables[i]->type;
  6728. GB_ASSERT(is_type_slice(variadic_type));
  6729. variadic_type = base_type(variadic_type)->Slice.elem;
  6730. for (; i < arg_count; i++) {
  6731. args[i] = ir_emit_conv(proc, args[i], variadic_type);
  6732. }
  6733. }
  6734. } else {
  6735. for (isize i = 0; i < param_count; i++) {
  6736. Entity *e = param_tuple->variables[i];
  6737. if (e->kind == Entity_Variable) {
  6738. GB_ASSERT(args[i] != nullptr);
  6739. args[i] = ir_emit_conv(proc, args[i], e->type);
  6740. }
  6741. }
  6742. }
  6743. if (variadic && !vari_expand && !is_c_vararg) {
  6744. ir_emit_comment(proc, str_lit("variadic call argument generation"));
  6745. gbAllocator allocator = ir_allocator();
  6746. Type *slice_type = param_tuple->variables[variadic_index]->type;
  6747. Type *elem_type = base_type(slice_type)->Slice.elem;
  6748. irValue *slice = ir_add_local_generated(proc, slice_type, true);
  6749. isize slice_len = arg_count+1 - (variadic_index+1);
  6750. if (slice_len > 0) {
  6751. irValue *base_array = ir_add_local_generated(proc, alloc_type_array(elem_type, slice_len), true);
  6752. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  6753. irValue *addr = ir_emit_array_epi(proc, base_array, cast(i32)j);
  6754. ir_emit_store(proc, addr, args[i]);
  6755. }
  6756. irValue *base_elem = ir_emit_array_epi(proc, base_array, 0);
  6757. irValue *len = ir_const_int(slice_len);
  6758. ir_fill_slice(proc, slice, base_elem, len);
  6759. }
  6760. arg_count = param_count;
  6761. args[variadic_index] = ir_emit_load(proc, slice);
  6762. }
  6763. }
  6764. if (variadic && variadic_index+1 < param_count) {
  6765. for (isize i = variadic_index+1; i < param_count; i++) {
  6766. Entity *e = param_tuple->variables[i];
  6767. args[i] = ir_handle_param_value(proc, e->type, e->Variable.param_value, ast_token(expr).pos);
  6768. }
  6769. }
  6770. isize final_count = param_count;
  6771. if (is_c_vararg) {
  6772. final_count = arg_count;
  6773. }
  6774. auto call_args = array_slice(args, 0, final_count);
  6775. return ir_emit_call(proc, value, call_args, ce->inlining, proc->return_ptr_hint_ast == expr);
  6776. }
  6777. irValue *ir_build_expr_internal(irProcedure *proc, Ast *expr) {
  6778. Ast *original_expr = expr;
  6779. expr = unparen_expr(expr);
  6780. // ir_push_debug_location(proc->module, expr, proc->debug_scope);
  6781. // defer (ir_pop_debug_location(proc->module));
  6782. TypeAndValue tv = type_and_value_of_expr(expr);
  6783. GB_ASSERT(tv.mode != Addressing_Invalid);
  6784. if (tv.mode == Addressing_Type) {
  6785. // HACK TODO(bill): This is hack but it should be safe in virtually all cases
  6786. irValue *v = ir_typeid(proc->module, tv.type);
  6787. return ir_emit_conv(proc, v, t_typeid);
  6788. }
  6789. if (tv.value.kind != ExactValue_Invalid) {
  6790. // NOTE(bill): Edge case
  6791. if (is_type_u8_array(tv.type) && tv.value.kind == ExactValue_String) {
  6792. return ir_add_module_constant(proc->module, tv.type, tv.value);
  6793. } else if (is_type_rune_array(tv.type) && tv.value.kind == ExactValue_String) {
  6794. return ir_add_module_constant(proc->module, tv.type, tv.value);
  6795. } else if (tv.value.kind != ExactValue_Compound &&
  6796. is_type_array(tv.type)) {
  6797. Type *elem = core_array_type(tv.type);
  6798. ExactValue value = convert_exact_value_for_type(tv.value, elem);
  6799. irValue *x = ir_add_module_constant(proc->module, elem, value);
  6800. return ir_emit_conv(proc, x, tv.type);
  6801. }
  6802. if (tv.value.kind == ExactValue_Typeid) {
  6803. irValue *v = ir_typeid(proc->module, tv.value.value_typeid);
  6804. return ir_emit_conv(proc, v, tv.type);
  6805. }
  6806. if (tv.value.kind == ExactValue_Procedure) {
  6807. Ast *expr = tv.value.value_procedure;
  6808. if (expr->kind == Ast_ProcLit) {
  6809. return ir_gen_anonymous_proc_lit(proc->module, str_lit("_proclit"), expr);
  6810. }
  6811. Entity *e = entity_from_expr(expr);
  6812. e = strip_entity_wrapping(e);
  6813. GB_ASSERT(e != nullptr);
  6814. if (e->kind == Entity_Procedure && e->Procedure.is_foreign) {
  6815. // NOTE(bill): There can be duplicates of the foreign procedure; get the main one
  6816. String link_name = e->token.string;
  6817. if (e->Procedure.link_name.len != 0) {
  6818. link_name = e->Procedure.link_name;
  6819. }
  6820. auto *found = string_map_get(&proc->module->members, link_name);
  6821. if (found) {
  6822. return *found;
  6823. }
  6824. }
  6825. auto *found = map_get(&proc->module->values, hash_entity(e));
  6826. if (found) {
  6827. auto v = *found;
  6828. // NOTE(bill): This is because pointers are already pointers in LLVM
  6829. if (is_type_proc(ir_type(v))) {
  6830. return v;
  6831. }
  6832. return ir_emit_load(proc, v);
  6833. } else if (e != nullptr && e->kind == Entity_Variable) {
  6834. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6835. }
  6836. GB_PANIC("Error in: %.*s(%td:%td) %s\n", LIT(proc->name), e->token.pos.line, e->token.pos.column);
  6837. }
  6838. return ir_add_module_constant(proc->module, tv.type, tv.value);
  6839. }
  6840. if (tv.mode == Addressing_Variable) {
  6841. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6842. }
  6843. if (tv.mode == Addressing_Constant) {
  6844. GB_ASSERT(tv.value.kind == ExactValue_Invalid);
  6845. // NOTE(bill): Zero value constant
  6846. return ir_add_module_constant(proc->module, tv.type, tv.value);
  6847. }
  6848. switch (expr->kind) {
  6849. case_ast_node(bl, BasicLit, expr);
  6850. TokenPos pos = bl->token.pos;
  6851. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(token_strings[bl->token.kind]));
  6852. case_end;
  6853. case_ast_node(bd, BasicDirective, expr);
  6854. TokenPos pos = bd->token.pos;
  6855. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name));
  6856. case_end;
  6857. case_ast_node(i, Implicit, expr);
  6858. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6859. case_end;
  6860. case_ast_node(u, Undef, expr);
  6861. return ir_value_undef(tv.type);
  6862. case_end;
  6863. case_ast_node(i, Ident, expr);
  6864. Entity *e = entity_of_node(expr);
  6865. e = strip_entity_wrapping(e);
  6866. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  6867. if (e->kind == Entity_Builtin) {
  6868. Token token = ast_token(expr);
  6869. GB_PANIC("TODO(bill): ir_build_expr Entity_Builtin '%.*s'\n"
  6870. "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name),
  6871. LIT(token.pos.file), token.pos.line, token.pos.column);
  6872. return nullptr;
  6873. } else if (e->kind == Entity_Nil) {
  6874. return ir_value_nil(tv.type);
  6875. }
  6876. irValue **found = map_get(&proc->module->values, hash_entity(e));
  6877. if (found) {
  6878. irValue *v = *found;
  6879. if (v->kind == irValue_Proc) {
  6880. return v;
  6881. }
  6882. // if (e->kind == Entity_Variable && e->Variable.param) {
  6883. // return v;
  6884. // }
  6885. return ir_emit_load(proc, v);
  6886. } else if (e != nullptr && e->kind == Entity_Variable) {
  6887. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6888. }
  6889. GB_PANIC("nullptr value for expression from identifier: %.*s : %s @ %p", LIT(i->token.string), type_to_string(e->type), expr);
  6890. return nullptr;
  6891. case_end;
  6892. case_ast_node(de, DerefExpr, expr);
  6893. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6894. case_end;
  6895. case_ast_node(se, SelectorExpr, expr);
  6896. TypeAndValue tav = type_and_value_of_expr(expr);
  6897. GB_ASSERT(tav.mode != Addressing_Invalid);
  6898. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6899. case_end;
  6900. case_ast_node(ise, ImplicitSelectorExpr, expr);
  6901. TypeAndValue tav = type_and_value_of_expr(expr);
  6902. GB_ASSERT(tav.mode == Addressing_Constant);
  6903. return ir_add_module_constant(proc->module, tv.type, tv.value);
  6904. case_end;
  6905. case_ast_node(se, SelectorCallExpr, expr);
  6906. GB_ASSERT(se->modified_call);
  6907. TypeAndValue tav = type_and_value_of_expr(expr);
  6908. GB_ASSERT(tav.mode != Addressing_Invalid);
  6909. return ir_build_expr(proc, se->call);
  6910. case_end;
  6911. case_ast_node(te, TernaryExpr, expr);
  6912. ir_emit_comment(proc, str_lit("TernaryExpr"));
  6913. auto edges = array_make<irValue *>(ir_allocator(), 0, 2);
  6914. GB_ASSERT(te->y != nullptr);
  6915. irBlock *then = ir_new_block(proc, nullptr, "if.then");
  6916. irBlock *done = ir_new_block(proc, nullptr, "if.done"); // NOTE(bill): Append later
  6917. irBlock *else_ = ir_new_block(proc, nullptr, "if.else");
  6918. irValue *cond = ir_build_cond(proc, te->cond, then, else_);
  6919. ir_start_block(proc, then);
  6920. Type *type = default_type(type_of_expr(expr));
  6921. ir_open_scope(proc);
  6922. array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->x), type));
  6923. ir_close_scope(proc, irDeferExit_Default, nullptr);
  6924. ir_emit_jump(proc, done);
  6925. ir_start_block(proc, else_);
  6926. ir_open_scope(proc);
  6927. array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->y), type));
  6928. ir_close_scope(proc, irDeferExit_Default, nullptr);
  6929. ir_emit_jump(proc, done);
  6930. ir_start_block(proc, done);
  6931. return ir_emit(proc, ir_instr_phi(proc, edges, type));
  6932. case_end;
  6933. case_ast_node(te, TernaryIfExpr, expr);
  6934. ir_emit_comment(proc, str_lit("TernaryIfExpr"));
  6935. auto edges = array_make<irValue *>(ir_allocator(), 0, 2);
  6936. GB_ASSERT(te->y != nullptr);
  6937. irBlock *then = ir_new_block(proc, nullptr, "if.then");
  6938. irBlock *done = ir_new_block(proc, nullptr, "if.done"); // NOTE(bill): Append later
  6939. irBlock *else_ = ir_new_block(proc, nullptr, "if.else");
  6940. irValue *cond = ir_build_cond(proc, te->cond, then, else_);
  6941. ir_start_block(proc, then);
  6942. Type *type = default_type(type_of_expr(expr));
  6943. ir_open_scope(proc);
  6944. array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->x), type));
  6945. ir_close_scope(proc, irDeferExit_Default, nullptr);
  6946. ir_emit_jump(proc, done);
  6947. ir_start_block(proc, else_);
  6948. ir_open_scope(proc);
  6949. array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->y), type));
  6950. ir_close_scope(proc, irDeferExit_Default, nullptr);
  6951. ir_emit_jump(proc, done);
  6952. ir_start_block(proc, done);
  6953. return ir_emit(proc, ir_instr_phi(proc, edges, type));
  6954. case_end;
  6955. case_ast_node(te, TernaryWhenExpr, expr);
  6956. TypeAndValue tav = type_and_value_of_expr(te->cond);
  6957. GB_ASSERT(tav.mode == Addressing_Constant);
  6958. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  6959. if (tav.value.value_bool) {
  6960. return ir_build_expr(proc, te->x);
  6961. } else {
  6962. return ir_build_expr(proc, te->y);
  6963. }
  6964. case_end;
  6965. case_ast_node(ta, TypeAssertion, expr);
  6966. TokenPos pos = ast_token(expr).pos;
  6967. Type *type = tv.type;
  6968. irValue *e = ir_build_expr(proc, ta->expr);
  6969. Type *t = type_deref(ir_type(e));
  6970. if (is_type_union(t)) {
  6971. ir_emit_comment(proc, str_lit("cast - union_cast"));
  6972. return ir_emit_union_cast(proc, e, type, pos);
  6973. } else if (is_type_any(t)) {
  6974. ir_emit_comment(proc, str_lit("cast - any_cast"));
  6975. return ir_emit_any_cast(proc, e, type, pos);
  6976. } else {
  6977. GB_PANIC("TODO(bill): type assertion %s", type_to_string(ir_type(e)));
  6978. }
  6979. case_end;
  6980. case_ast_node(tc, TypeCast, expr);
  6981. irValue *e = ir_build_expr(proc, tc->expr);
  6982. switch (tc->token.kind) {
  6983. case Token_cast:
  6984. return ir_emit_conv(proc, e, tv.type);
  6985. case Token_transmute:
  6986. return ir_emit_transmute(proc, e, tv.type);
  6987. }
  6988. GB_PANIC("Invalid AST TypeCast");
  6989. case_end;
  6990. case_ast_node(ac, AutoCast, expr);
  6991. return ir_build_expr(proc, ac->expr);
  6992. case_end;
  6993. case_ast_node(ue, UnaryExpr, expr);
  6994. switch (ue->op.kind) {
  6995. case Token_And: {
  6996. Ast *ue_expr = unparen_expr(ue->expr);
  6997. if (ue_expr->kind == Ast_CompoundLit) {
  6998. irValue *v = ir_build_expr(proc, ue->expr);
  6999. Type *type = ir_type(v);
  7000. irValue *ptr = nullptr;
  7001. if (proc->is_startup) {
  7002. ptr = ir_add_global_generated(proc->module, type, v);
  7003. } else {
  7004. ptr = ir_add_local_generated(proc, type, false);
  7005. }
  7006. ir_emit_store(proc, ptr, v);
  7007. return ptr;
  7008. } else if (ue_expr->kind == Ast_TypeAssertion) {
  7009. gbAllocator a = ir_allocator();
  7010. GB_ASSERT(is_type_pointer(tv.type));
  7011. ast_node(ta, TypeAssertion, ue_expr);
  7012. TokenPos pos = ast_token(expr).pos;
  7013. Type *type = type_of_expr(ue_expr);
  7014. GB_ASSERT(!is_type_tuple(type));
  7015. irValue *e = ir_build_expr(proc, ta->expr);
  7016. Type *t = type_deref(ir_type(e));
  7017. if (is_type_union(t)) {
  7018. irValue *v = e;
  7019. if (!is_type_pointer(ir_type(v))) {
  7020. v = ir_address_from_load_or_generate_local(proc, v);
  7021. }
  7022. Type *src_type = type_deref(ir_type(v));
  7023. Type *dst_type = type;
  7024. irValue *src_tag = ir_emit_load(proc, ir_emit_union_tag_ptr(proc, v));
  7025. irValue *dst_tag = ir_const_union_tag(src_type, dst_type);
  7026. irValue *ok = ir_emit_comp(proc, Token_CmpEq, src_tag, dst_tag);
  7027. auto args = array_make<irValue *>(ir_allocator(), 6);
  7028. args[0] = ok;
  7029. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  7030. args[2] = ir_const_int(pos.line);
  7031. args[3] = ir_const_int(pos.column);
  7032. args[4] = ir_typeid(proc->module, src_type);
  7033. args[5] = ir_typeid(proc->module, dst_type);
  7034. ir_emit_runtime_call(proc, "type_assertion_check", args);
  7035. irValue *data_ptr = v;
  7036. return ir_emit_conv(proc, data_ptr, tv.type);
  7037. } else if (is_type_any(t)) {
  7038. irValue *v = e;
  7039. if (is_type_pointer(ir_type(v))) {
  7040. v = ir_emit_load(proc, v);
  7041. }
  7042. irValue *data_ptr = ir_emit_struct_ev(proc, v, 0);
  7043. irValue *any_id = ir_emit_struct_ev(proc, v, 1);
  7044. irValue *id = ir_typeid(proc->module, type);
  7045. irValue *ok = ir_emit_comp(proc, Token_CmpEq, any_id, id);
  7046. auto args = array_make<irValue *>(ir_allocator(), 6);
  7047. args[0] = ok;
  7048. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  7049. args[2] = ir_const_int(pos.line);
  7050. args[3] = ir_const_int(pos.column);
  7051. args[4] = any_id;
  7052. args[5] = id;
  7053. ir_emit_runtime_call(proc, "type_assertion_check", args);
  7054. return ir_emit_conv(proc, data_ptr, tv.type);
  7055. } else {
  7056. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  7057. }
  7058. } else if (ue_expr->kind == Ast_IndexExpr) {
  7059. #if 0
  7060. ast_node(ie, IndexExpr, ue_expr);
  7061. if (is_type_slice(ie->expr->tav.type)) {
  7062. auto tav = ie->index->tav;
  7063. if (tav.mode == Addressing_Constant) {
  7064. if (exact_value_to_i64(tav.value) == 0) {
  7065. irValue *s = ir_build_expr(proc, ie->expr);
  7066. if (is_type_pointer(ir_type(s))) {
  7067. s = ir_emit_load(proc, s);
  7068. }
  7069. return ir_slice_elem(proc, s);
  7070. }
  7071. }
  7072. }
  7073. #endif
  7074. }
  7075. bool allow_reference = true;
  7076. irAddr addr = ir_build_addr(proc, ue->expr);
  7077. return ir_addr_get_ptr(proc, addr, allow_reference);
  7078. }
  7079. default:
  7080. return ir_emit_unary_arith(proc, ue->op.kind, ir_build_expr(proc, ue->expr), tv.type);
  7081. }
  7082. case_end;
  7083. case_ast_node(be, BinaryExpr, expr);
  7084. switch (be->op.kind) {
  7085. case Token_Add:
  7086. case Token_Sub:
  7087. case Token_Mul:
  7088. case Token_Quo:
  7089. case Token_Mod:
  7090. case Token_ModMod:
  7091. case Token_And:
  7092. case Token_Or:
  7093. case Token_Xor:
  7094. case Token_AndNot:
  7095. case Token_Shl:
  7096. case Token_Shr: {
  7097. irValue *left = ir_build_expr(proc, be->left);
  7098. Type *type = default_type(tv.type);
  7099. irValue *right = ir_build_expr(proc, be->right);
  7100. return ir_emit_arith(proc, be->op.kind, left, right, type);
  7101. }
  7102. case Token_CmpEq:
  7103. case Token_NotEq:
  7104. case Token_Lt:
  7105. case Token_LtEq:
  7106. case Token_Gt:
  7107. case Token_GtEq: {
  7108. irValue *left = ir_build_expr(proc, be->left);
  7109. Type *type = default_type(tv.type);
  7110. irValue *right = ir_build_expr(proc, be->right);
  7111. irValue *cmp = ir_emit_comp(proc, be->op.kind, left, right);
  7112. return ir_emit_conv(proc, cmp, type);
  7113. }
  7114. case Token_CmpAnd:
  7115. case Token_CmpOr:
  7116. return ir_emit_logical_binary_expr(proc, expr);
  7117. case Token_in:
  7118. case Token_not_in: {
  7119. irValue *left = ir_build_expr(proc, be->left);
  7120. Type *type = default_type(tv.type);
  7121. irValue *right = ir_build_expr(proc, be->right);
  7122. Type *rt = base_type(ir_type(right));
  7123. switch (rt->kind) {
  7124. case Type_Map:
  7125. {
  7126. if (be->op.kind == Token_in) {
  7127. ir_emit_comment(proc, str_lit("map in"));
  7128. } else {
  7129. ir_emit_comment(proc, str_lit("map not_in"));
  7130. }
  7131. irValue *addr = ir_address_from_load_or_generate_local(proc, right);
  7132. irValue *h = ir_gen_map_header(proc, addr, rt);
  7133. irValue *key = ir_gen_map_hash(proc, left, rt->Map.key);
  7134. auto args = array_make<irValue *>(ir_allocator(), 2);
  7135. args[0] = h;
  7136. args[1] = key;
  7137. irValue *ptr = ir_emit_runtime_call(proc, "__dynamic_map_get", args);
  7138. if (be->op.kind == Token_in) {
  7139. return ir_emit_conv(proc, ir_emit_comp(proc, Token_NotEq, ptr, v_raw_nil), t_bool);
  7140. } else {
  7141. return ir_emit_conv(proc, ir_emit_comp(proc, Token_CmpEq, ptr, v_raw_nil), t_bool);
  7142. }
  7143. }
  7144. break;
  7145. case Type_BitSet:
  7146. {
  7147. if (be->op.kind == Token_in) {
  7148. ir_emit_comment(proc, str_lit("bit_set in"));
  7149. } else {
  7150. ir_emit_comment(proc, str_lit("bit_set not_in"));
  7151. }
  7152. Type *key_type = rt->BitSet.elem;
  7153. GB_ASSERT(are_types_identical(ir_type(left), key_type));
  7154. Type *it = bit_set_to_int(rt);
  7155. left = ir_emit_conv(proc, left, it);
  7156. irValue *lower = ir_value_constant(it, exact_value_i64(rt->BitSet.lower));
  7157. irValue *key = ir_emit_arith(proc, Token_Sub, left, lower, it);
  7158. irValue *bit = ir_emit_arith(proc, Token_Shl, v_one, key, it);
  7159. bit = ir_emit_conv(proc, bit, it);
  7160. irValue *old_value = ir_emit_bitcast(proc, right, it);
  7161. irValue *new_value = ir_emit_arith(proc, Token_And, old_value, bit, it);
  7162. if (be->op.kind == Token_in) {
  7163. return ir_emit_conv(proc, ir_emit_comp(proc, Token_NotEq, new_value, v_zero), t_bool);
  7164. } else {
  7165. return ir_emit_conv(proc, ir_emit_comp(proc, Token_CmpEq, new_value, v_zero), t_bool);
  7166. }
  7167. }
  7168. break;
  7169. default:
  7170. GB_PANIC("Invalid 'in' type");
  7171. }
  7172. break;
  7173. }
  7174. default:
  7175. GB_PANIC("Invalid binary expression");
  7176. break;
  7177. }
  7178. case_end;
  7179. case_ast_node(pl, ProcLit, expr);
  7180. return ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
  7181. case_end;
  7182. case_ast_node(cl, CompoundLit, expr);
  7183. return ir_addr_load(proc, ir_build_addr(proc, expr));
  7184. case_end;
  7185. case_ast_node(ce, CallExpr, expr);
  7186. irValue *res = ir_build_call_expr(proc, expr);
  7187. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  7188. GB_ASSERT(is_type_tuple(ir_type(res)));
  7189. GB_ASSERT(ir_type(res)->Tuple.variables.count == 2);
  7190. return ir_emit_struct_ev(proc, res, 0);
  7191. }
  7192. return res;
  7193. case_end;
  7194. case_ast_node(se, SliceExpr, expr);
  7195. return ir_addr_load(proc, ir_build_addr(proc, expr));
  7196. case_end;
  7197. case_ast_node(ie, IndexExpr, expr);
  7198. return ir_addr_load(proc, ir_build_addr(proc, expr));
  7199. case_end;
  7200. }
  7201. GB_PANIC("Unexpected expression: %.*s", LIT(ast_strings[expr->kind]));
  7202. return nullptr;
  7203. }
  7204. irValue *ir_get_using_variable(irProcedure *proc, Entity *e) {
  7205. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  7206. String name = e->token.string;
  7207. Entity *parent = e->using_parent;
  7208. Selection sel = lookup_field(parent->type, name, false);
  7209. GB_ASSERT(sel.entity != nullptr);
  7210. irValue **pv = map_get(&proc->module->values, hash_entity(parent));
  7211. irValue *v = nullptr;
  7212. if (pv != nullptr) {
  7213. v = *pv;
  7214. } else {
  7215. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  7216. v = ir_build_addr_ptr(proc, e->using_expr);
  7217. }
  7218. GB_ASSERT(v != nullptr);
  7219. GB_ASSERT(parent->type == type_deref(ir_type(v)));
  7220. return ir_emit_deep_field_gep(proc, v, sel);
  7221. }
  7222. bool ir_is_elem_const(irModule *m, Ast *elem, Type *elem_type) {
  7223. if (!elem_type_can_be_constant(elem_type)) {
  7224. return false;
  7225. }
  7226. if (elem->kind == Ast_FieldValue) {
  7227. elem = elem->FieldValue.value;
  7228. }
  7229. TypeAndValue tav = type_and_value_of_expr(elem);
  7230. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  7231. return tav.value.kind != ExactValue_Invalid && tav.value.kind != ExactValue_Procedure;
  7232. }
  7233. irAddr ir_build_addr_from_entity(irProcedure *proc, Entity *e, Ast *expr) {
  7234. GB_ASSERT(e != nullptr);
  7235. if (e->kind == Entity_Constant) {
  7236. Type *t = default_type(type_of_expr(expr));
  7237. irValue *v = ir_add_module_constant(proc->module, t, e->Constant.value);
  7238. irValue *g = ir_add_global_generated(proc->module, ir_type(v), v);
  7239. return ir_addr(g);
  7240. }
  7241. irValue *v = nullptr;
  7242. irValue **found = map_get(&proc->module->values, hash_entity(e));
  7243. if (found) {
  7244. v = *found;
  7245. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  7246. // NOTE(bill): Calculate the using variable every time
  7247. v = ir_get_using_variable(proc, e);
  7248. }
  7249. if (v == nullptr) {
  7250. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  7251. LIT(proc->name),
  7252. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  7253. GB_PANIC("Unknown value");
  7254. }
  7255. return ir_addr(v);
  7256. }
  7257. struct irCompoundLitElemTempData {
  7258. Ast *expr;
  7259. irValue *value;
  7260. i32 elem_index;
  7261. irValue *gep;
  7262. };
  7263. irAddr ir_build_addr(irProcedure *proc, Ast *expr) {
  7264. switch (expr->kind) {
  7265. case_ast_node(i, Implicit, expr);
  7266. irValue *v = nullptr;
  7267. switch (i->kind) {
  7268. case Token_context:
  7269. v = ir_find_or_generate_context_ptr(proc);
  7270. break;
  7271. }
  7272. GB_ASSERT(v != nullptr);
  7273. return ir_addr_context(v);
  7274. case_end;
  7275. case_ast_node(i, Ident, expr);
  7276. if (is_blank_ident(expr)) {
  7277. irAddr val = {};
  7278. return val;
  7279. }
  7280. String name = i->token.string;
  7281. Entity *e = entity_of_node(expr);
  7282. // GB_ASSERT(name == e->token.string);
  7283. return ir_build_addr_from_entity(proc, e, expr);
  7284. case_end;
  7285. case_ast_node(pe, ParenExpr, expr);
  7286. return ir_build_addr(proc, unparen_expr(expr));
  7287. case_end;
  7288. case_ast_node(se, SelectorExpr, expr);
  7289. ir_emit_comment(proc, str_lit("SelectorExpr"));
  7290. Ast *sel = unparen_expr(se->selector);
  7291. if (sel->kind == Ast_Ident) {
  7292. String selector = sel->Ident.token.string;
  7293. TypeAndValue tav = type_and_value_of_expr(se->expr);
  7294. if (tav.mode == Addressing_Invalid) {
  7295. // NOTE(bill): Imports
  7296. Entity *imp = entity_of_node(se->expr);
  7297. if (imp != nullptr) {
  7298. GB_ASSERT(imp->kind == Entity_ImportName);
  7299. }
  7300. return ir_build_addr(proc, unparen_expr(se->selector));
  7301. }
  7302. Type *type = base_type(tav.type);
  7303. if (tav.mode == Addressing_Type) { // Addressing_Type
  7304. Selection sel = lookup_field(type, selector, true);
  7305. Entity *e = sel.entity;
  7306. GB_ASSERT(e->kind == Entity_Variable);
  7307. GB_ASSERT(e->flags & EntityFlag_TypeField);
  7308. String name = e->token.string;
  7309. if (name == "names") {
  7310. irValue *ti_ptr = ir_type_info(proc, type);
  7311. irValue *variant = ir_emit_struct_ep(proc, ti_ptr, 2);
  7312. irValue *names_ptr = nullptr;
  7313. if (is_type_enum(type)) {
  7314. irValue *enum_info = ir_emit_conv(proc, variant, t_type_info_enum_ptr);
  7315. names_ptr = ir_emit_struct_ep(proc, enum_info, 1);
  7316. } else if (type->kind == Type_Struct) {
  7317. irValue *struct_info = ir_emit_conv(proc, variant, t_type_info_struct_ptr);
  7318. names_ptr = ir_emit_struct_ep(proc, struct_info, 1);
  7319. }
  7320. return ir_addr(names_ptr);
  7321. } else {
  7322. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  7323. }
  7324. GB_PANIC("Unreachable");
  7325. }
  7326. Selection sel = lookup_field(type, selector, false);
  7327. GB_ASSERT(sel.entity != nullptr);
  7328. if (sel.entity->type->kind == Type_BitFieldValue) {
  7329. irAddr addr = ir_build_addr(proc, se->expr);
  7330. Type *bft = type_deref(ir_addr_type(addr));
  7331. if (sel.index.count == 1) {
  7332. GB_ASSERT(is_type_bit_field(bft));
  7333. i32 index = sel.index[0];
  7334. return ir_addr_bit_field(ir_addr_get_ptr(proc, addr), index);
  7335. } else {
  7336. Selection s = sel;
  7337. s.index.count--;
  7338. i32 index = s.index[s.index.count-1];
  7339. irValue *a = ir_addr_get_ptr(proc, addr);
  7340. a = ir_emit_deep_field_gep(proc, a, s);
  7341. return ir_addr_bit_field(a, index);
  7342. }
  7343. } else {
  7344. irAddr addr = ir_build_addr(proc, se->expr);
  7345. if (addr.kind == irAddr_Context) {
  7346. GB_ASSERT(sel.index.count > 0);
  7347. if (addr.ctx.sel.index.count >= 0) {
  7348. sel = selection_combine(addr.ctx.sel, sel);
  7349. }
  7350. addr.ctx.sel = sel;
  7351. return addr;
  7352. } else if (addr.kind == irAddr_SoaVariable) {
  7353. irValue *index = addr.soa.index;
  7354. i32 first_index = sel.index[0];
  7355. Selection sub_sel = sel;
  7356. sub_sel.index.data += 1;
  7357. sub_sel.index.count -= 1;
  7358. irValue *arr = ir_emit_struct_ep(proc, addr.addr, first_index);
  7359. Type *t = base_type(type_deref(ir_type(addr.addr)));
  7360. GB_ASSERT(is_type_soa_struct(t));
  7361. if (addr.soa.index->kind != irValue_Constant || t->Struct.soa_kind != StructSoa_Fixed) {
  7362. irValue *len = ir_soa_struct_len(proc, addr.addr);
  7363. ir_emit_bounds_check(proc, ast_token(addr.soa.index_expr), addr.soa.index, len);
  7364. }
  7365. irValue *item = nullptr;
  7366. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7367. item = ir_emit_array_ep(proc, arr, index);
  7368. } else {
  7369. item = ir_emit_load(proc, ir_emit_ptr_offset(proc, arr, index));
  7370. }
  7371. if (sub_sel.index.count > 0) {
  7372. item = ir_emit_deep_field_gep(proc, item, sub_sel);
  7373. }
  7374. return ir_addr(item);
  7375. }
  7376. irValue *a = ir_addr_get_ptr(proc, addr);
  7377. a = ir_emit_deep_field_gep(proc, a, sel);
  7378. return ir_addr(a);
  7379. }
  7380. } else {
  7381. GB_PANIC("Unsupported selector expression");
  7382. }
  7383. case_end;
  7384. case_ast_node(se, SelectorCallExpr, expr);
  7385. GB_ASSERT(se->modified_call);
  7386. TypeAndValue tav = type_and_value_of_expr(expr);
  7387. GB_ASSERT(tav.mode != Addressing_Invalid);
  7388. return ir_build_addr(proc, se->call);
  7389. case_end;
  7390. case_ast_node(ta, TypeAssertion, expr);
  7391. gbAllocator a = ir_allocator();
  7392. TokenPos pos = ast_token(expr).pos;
  7393. irValue *e = ir_build_expr(proc, ta->expr);
  7394. Type *t = type_deref(ir_type(e));
  7395. if (is_type_union(t)) {
  7396. Type *type = type_of_expr(expr);
  7397. irValue *v = ir_add_local_generated(proc, type, false);
  7398. ir_emit_comment(proc, str_lit("cast - union_cast"));
  7399. ir_emit_store(proc, v, ir_emit_union_cast(proc, ir_build_expr(proc, ta->expr), type, pos));
  7400. return ir_addr(v);
  7401. } else if (is_type_any(t)) {
  7402. ir_emit_comment(proc, str_lit("cast - any_cast"));
  7403. Type *type = type_of_expr(expr);
  7404. return ir_emit_any_cast_addr(proc, ir_build_expr(proc, ta->expr), type, pos);
  7405. } else {
  7406. GB_PANIC("TODO(bill): type assertion %s", type_to_string(ir_type(e)));
  7407. }
  7408. case_end;
  7409. case_ast_node(ue, UnaryExpr, expr);
  7410. switch (ue->op.kind) {
  7411. case Token_And: {
  7412. return ir_build_addr(proc, ue->expr);
  7413. }
  7414. default:
  7415. GB_PANIC("Invalid unary expression for ir_build_addr");
  7416. }
  7417. case_end;
  7418. case_ast_node(be, BinaryExpr, expr);
  7419. irValue *v = ir_build_expr(proc, expr);
  7420. Type *t = ir_type(v);
  7421. if (is_type_pointer(t)) {
  7422. return ir_addr(v);
  7423. }
  7424. return ir_addr(ir_address_from_load_or_generate_local(proc, v));
  7425. case_end;
  7426. case_ast_node(ie, IndexExpr, expr);
  7427. ir_emit_comment(proc, str_lit("IndexExpr"));
  7428. Type *t = base_type(type_of_expr(ie->expr));
  7429. gbAllocator a = ir_allocator();
  7430. bool deref = is_type_pointer(t);
  7431. t = base_type(type_deref(t));
  7432. if (is_type_soa_struct(t)) {
  7433. // SOA STRUCTURES!!!!
  7434. irValue *val = ir_build_addr_ptr(proc, ie->expr);
  7435. if (deref) {
  7436. val = ir_emit_load(proc, val);
  7437. }
  7438. irValue *index = ir_build_expr(proc, ie->index);
  7439. return ir_addr_soa_variable(val, index, ie->index);
  7440. }
  7441. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  7442. // SOA Structures for slices/dynamic arrays
  7443. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  7444. irValue *field = ir_build_expr(proc, ie->expr);
  7445. irValue *index = ir_build_expr(proc, ie->index);
  7446. if (!build_context.no_bounds_check) {
  7447. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  7448. GB_ASSERT(field->kind == irValue_Instr);
  7449. irInstr *instr = &field->Instr;
  7450. GB_ASSERT(instr->kind == irInstr_Load);
  7451. irValue *a = instr->Load.address;
  7452. GB_ASSERT(a->kind == irValue_Instr);
  7453. irInstr *b = &a->Instr;
  7454. GB_ASSERT(b->kind == irInstr_StructElementPtr);
  7455. irValue *base_struct = b->StructElementPtr.address;
  7456. GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  7457. irValue *len = ir_soa_struct_len(proc, base_struct);
  7458. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  7459. }
  7460. irValue *val = ir_emit_ptr_offset(proc, field, index);
  7461. return ir_addr(val);
  7462. }
  7463. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  7464. if (is_type_map(t)) {
  7465. irValue *map_val = ir_build_addr_ptr(proc, ie->expr);
  7466. if (deref) {
  7467. map_val = ir_emit_load(proc, map_val);
  7468. }
  7469. irValue *key = ir_build_expr(proc, ie->index);
  7470. key = ir_emit_conv(proc, key, t->Map.key);
  7471. Type *result_type = type_of_expr(expr);
  7472. return ir_addr_map(map_val, key, t, result_type);
  7473. }
  7474. switch (t->kind) {
  7475. case Type_Array: {
  7476. irValue *array = nullptr;
  7477. array = ir_build_addr_ptr(proc, ie->expr);
  7478. if (deref) {
  7479. array = ir_emit_load(proc, array);
  7480. }
  7481. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  7482. irValue *elem = ir_emit_array_ep(proc, array, index);
  7483. auto index_tv = type_and_value_of_expr(ie->index);
  7484. if (index_tv.mode != Addressing_Constant) {
  7485. irValue *len = ir_const_int(t->Array.count);
  7486. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  7487. }
  7488. return ir_addr(elem);
  7489. }
  7490. case Type_EnumeratedArray: {
  7491. irValue *array = nullptr;
  7492. array = ir_build_addr_ptr(proc, ie->expr);
  7493. if (deref) {
  7494. array = ir_emit_load(proc, array);
  7495. }
  7496. Type *index_type = t->EnumeratedArray.index;
  7497. auto index_tv = type_and_value_of_expr(ie->index);
  7498. irValue *index = nullptr;
  7499. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  7500. if (index_tv.mode == Addressing_Constant) {
  7501. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  7502. index = ir_value_constant(index_type, idx);
  7503. } else {
  7504. index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  7505. index = ir_emit_arith(proc, Token_Sub, index, ir_value_constant(index_type, t->EnumeratedArray.min_value), index_type);
  7506. }
  7507. } else {
  7508. index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  7509. }
  7510. irValue *elem = ir_emit_array_ep(proc, array, index);
  7511. if (index_tv.mode != Addressing_Constant) {
  7512. irValue *len = ir_const_int(t->EnumeratedArray.count);
  7513. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  7514. }
  7515. return ir_addr(elem);
  7516. }
  7517. case Type_Slice: {
  7518. irValue *slice = nullptr;
  7519. slice = ir_build_expr(proc, ie->expr);
  7520. if (deref) {
  7521. slice = ir_emit_load(proc, slice);
  7522. }
  7523. irValue *elem = ir_slice_elem(proc, slice);
  7524. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  7525. irValue *len = ir_slice_len(proc, slice);
  7526. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  7527. irValue *v = ir_emit_ptr_offset(proc, elem, index);
  7528. return ir_addr(v);
  7529. }
  7530. case Type_RelativeSlice: {
  7531. irAddr addr = ir_build_addr(proc, ie->expr);
  7532. if (deref) {
  7533. addr = ir_addr(ir_addr_load(proc, addr));
  7534. }
  7535. irValue *slice = ir_addr_load(proc, addr);
  7536. irValue *elem = ir_slice_elem(proc, slice);
  7537. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  7538. irValue *len = ir_slice_len(proc, slice);
  7539. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  7540. irValue *v = ir_emit_ptr_offset(proc, elem, index);
  7541. return ir_addr(v);
  7542. }
  7543. case Type_DynamicArray: {
  7544. irValue *dynamic_array = nullptr;
  7545. dynamic_array = ir_build_expr(proc, ie->expr);
  7546. if (deref) {
  7547. dynamic_array = ir_emit_load(proc, dynamic_array);
  7548. }
  7549. irValue *elem = ir_dynamic_array_elem(proc, dynamic_array);
  7550. irValue *len = ir_dynamic_array_len(proc, dynamic_array);
  7551. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  7552. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  7553. irValue *v = ir_emit_ptr_offset(proc, elem, index);
  7554. return ir_addr(v);
  7555. }
  7556. case Type_Basic: { // Basic_string
  7557. irValue *str;
  7558. irValue *elem;
  7559. irValue *len;
  7560. irValue *index;
  7561. str = ir_build_expr(proc, ie->expr);
  7562. if (deref) {
  7563. str = ir_emit_load(proc, str);
  7564. }
  7565. elem = ir_string_elem(proc, str);
  7566. len = ir_string_len(proc, str);
  7567. index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  7568. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  7569. return ir_addr(ir_emit_ptr_offset(proc, elem, index));
  7570. }
  7571. }
  7572. case_end;
  7573. case_ast_node(se, SliceExpr, expr);
  7574. ir_emit_comment(proc, str_lit("SliceExpr"));
  7575. gbAllocator a = ir_allocator();
  7576. irValue *low = v_zero;
  7577. irValue *high = nullptr;
  7578. if (se->low != nullptr) low = ir_build_expr(proc, se->low);
  7579. if (se->high != nullptr) high = ir_build_expr(proc, se->high);
  7580. bool no_indices = se->low == nullptr && se->high == nullptr;
  7581. irAddr addr = ir_build_addr(proc, se->expr);
  7582. irValue *base = ir_addr_load(proc, addr);
  7583. Type *type = base_type(ir_type(base));
  7584. if (is_type_pointer(type)) {
  7585. type = base_type(type_deref(type));
  7586. addr = ir_addr(base);
  7587. base = ir_addr_load(proc, addr);
  7588. }
  7589. // TODO(bill): Cleanup like mad!
  7590. switch (type->kind) {
  7591. case Type_Slice: {
  7592. Type *slice_type = type;
  7593. irValue *len = ir_slice_len(proc, base);
  7594. if (high == nullptr) high = len;
  7595. if (!no_indices) {
  7596. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  7597. }
  7598. irValue *elem = ir_emit_ptr_offset(proc, ir_slice_elem(proc, base), low);
  7599. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7600. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  7601. ir_fill_slice(proc, slice, elem, new_len);
  7602. return ir_addr(slice);
  7603. }
  7604. case Type_DynamicArray: {
  7605. Type *elem_type = type->DynamicArray.elem;
  7606. Type *slice_type = alloc_type_slice(elem_type);
  7607. irValue *len = ir_dynamic_array_len(proc, base);
  7608. if (high == nullptr) high = len;
  7609. if (!no_indices) {
  7610. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  7611. }
  7612. irValue *elem = ir_emit_ptr_offset(proc, ir_dynamic_array_elem(proc, base), low);
  7613. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7614. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  7615. ir_fill_slice(proc, slice, elem, new_len);
  7616. return ir_addr(slice);
  7617. }
  7618. case Type_Array: {
  7619. Type *slice_type = alloc_type_slice(type->Array.elem);
  7620. irValue *len = ir_array_len(proc, base);
  7621. if (high == nullptr) high = len;
  7622. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  7623. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  7624. if (!low_const || !high_const) {
  7625. if (!no_indices) {
  7626. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  7627. }
  7628. }
  7629. irValue *elem = ir_emit_ptr_offset(proc, ir_array_elem(proc, ir_addr_get_ptr(proc, addr)), low);
  7630. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7631. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  7632. ir_fill_slice(proc, slice, elem, new_len);
  7633. return ir_addr(slice);
  7634. }
  7635. case Type_Basic: {
  7636. GB_ASSERT(type == t_string);
  7637. irValue *len = ir_string_len(proc, base);
  7638. if (high == nullptr) high = len;
  7639. if (!no_indices) {
  7640. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  7641. }
  7642. irValue *elem = ir_emit_ptr_offset(proc, ir_string_elem(proc, base), low);
  7643. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7644. irValue *str = ir_add_local_generated(proc, t_string, false);
  7645. ir_fill_string(proc, str, elem, new_len);
  7646. return ir_addr(str);
  7647. }
  7648. case Type_Struct:
  7649. if (is_type_soa_struct(type)) {
  7650. irValue *len = ir_soa_struct_len(proc, ir_addr_get_ptr(proc, addr));
  7651. if (high == nullptr) high = len;
  7652. if (!no_indices) {
  7653. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  7654. }
  7655. irValue *dst = ir_add_local_generated(proc, type_of_expr(expr), true);
  7656. if (type->Struct.soa_kind == StructSoa_Fixed) {
  7657. i32 field_count = cast(i32)type->Struct.fields.count;
  7658. for (i32 i = 0; i < field_count; i++) {
  7659. irValue *field_dst = ir_emit_struct_ep(proc, dst, i);
  7660. irValue *field_src = ir_emit_struct_ep(proc, ir_addr_get_ptr(proc, addr), i);
  7661. field_src = ir_emit_array_ep(proc, field_src, low);
  7662. ir_emit_store(proc, field_dst, field_src);
  7663. }
  7664. irValue *len_dst = ir_emit_struct_ep(proc, dst, field_count);
  7665. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7666. ir_emit_store(proc, len_dst, new_len);
  7667. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  7668. if (no_indices) {
  7669. ir_emit_store(proc, dst, base);
  7670. } else {
  7671. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  7672. for (i32 i = 0; i < field_count; i++) {
  7673. irValue *field_dst = ir_emit_struct_ep(proc, dst, i);
  7674. irValue *field_src = ir_emit_struct_ev(proc, base, i);
  7675. field_src = ir_emit_ptr_offset(proc, field_src, low);
  7676. ir_emit_store(proc, field_dst, field_src);
  7677. }
  7678. irValue *len_dst = ir_emit_struct_ep(proc, dst, field_count);
  7679. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7680. ir_emit_store(proc, len_dst, new_len);
  7681. }
  7682. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  7683. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  7684. for (i32 i = 0; i < field_count; i++) {
  7685. irValue *field_dst = ir_emit_struct_ep(proc, dst, i);
  7686. irValue *field_src = ir_emit_struct_ev(proc, base, i);
  7687. field_src = ir_emit_ptr_offset(proc, field_src, low);
  7688. ir_emit_store(proc, field_dst, field_src);
  7689. }
  7690. irValue *len_dst = ir_emit_struct_ep(proc, dst, field_count);
  7691. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7692. ir_emit_store(proc, len_dst, new_len);
  7693. }
  7694. return ir_addr(dst);
  7695. }
  7696. break;
  7697. }
  7698. GB_PANIC("Unknown slicable type");
  7699. case_end;
  7700. case_ast_node(de, DerefExpr, expr);
  7701. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  7702. irAddr addr = ir_build_addr(proc, de->expr);
  7703. addr.relative.deref = true;
  7704. return addr;
  7705. }
  7706. // TODO(bill): Is a ptr copy needed?
  7707. irValue *addr = ir_build_expr(proc, de->expr);
  7708. addr = ir_emit_ptr_offset(proc, addr, v_zero);
  7709. return ir_addr(addr);
  7710. case_end;
  7711. case_ast_node(ce, CallExpr, expr);
  7712. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  7713. irValue *e = ir_build_expr(proc, expr);
  7714. irValue *v = ir_add_local_generated(proc, ir_type(e), false);
  7715. ir_emit_store(proc, v, e);
  7716. return ir_addr(v);
  7717. case_end;
  7718. case_ast_node(cl, CompoundLit, expr);
  7719. ir_emit_comment(proc, str_lit("CompoundLit"));
  7720. Type *type = type_of_expr(expr);
  7721. Type *bt = base_type(type);
  7722. irValue *v = ir_add_local_generated(proc, type, true);
  7723. Type *et = nullptr;
  7724. switch (bt->kind) {
  7725. case Type_Array: et = bt->Array.elem; break;
  7726. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  7727. case Type_Slice: et = bt->Slice.elem; break;
  7728. case Type_BitSet: et = bt->BitSet.elem; break;
  7729. case Type_SimdVector: et = bt->SimdVector.elem; break;
  7730. }
  7731. String proc_name = {};
  7732. if (proc->entity) {
  7733. proc_name = proc->entity->token.string;
  7734. }
  7735. TokenPos pos = ast_token(expr).pos;
  7736. switch (bt->kind) {
  7737. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  7738. case Type_Struct: {
  7739. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  7740. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  7741. bool is_raw_union = is_type_raw_union(bt);
  7742. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  7743. TypeStruct *st = &bt->Struct;
  7744. if (cl->elems.count > 0) {
  7745. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  7746. for_array(field_index, cl->elems) {
  7747. Ast *elem = cl->elems[field_index];
  7748. irValue *field_expr = nullptr;
  7749. Entity *field = nullptr;
  7750. isize index = field_index;
  7751. if (elem->kind == Ast_FieldValue) {
  7752. ast_node(fv, FieldValue, elem);
  7753. String name = fv->field->Ident.token.string;
  7754. Selection sel = lookup_field(bt, name, false);
  7755. index = sel.index[0];
  7756. elem = fv->value;
  7757. TypeAndValue tav = type_and_value_of_expr(elem);
  7758. } else {
  7759. TypeAndValue tav = type_and_value_of_expr(elem);
  7760. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  7761. index = sel.index[0];
  7762. }
  7763. field = st->fields[index];
  7764. Type *ft = field->type;
  7765. if (!is_raw_union && !is_type_typeid(ft) && ir_is_elem_const(proc->module, elem, ft)) {
  7766. continue;
  7767. }
  7768. field_expr = ir_build_expr(proc, elem);
  7769. GB_ASSERT(ir_type(field_expr)->kind != Type_Tuple);
  7770. Type *fet = ir_type(field_expr);
  7771. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  7772. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  7773. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  7774. irValue *gep = ir_emit_struct_ep(proc, v, cast(i32)index);
  7775. ir_emit_store_union_variant(proc, gep, field_expr, fet);
  7776. } else {
  7777. irValue *fv = ir_emit_conv(proc, field_expr, ft);
  7778. irValue *gep = ir_emit_struct_ep(proc, v, cast(i32)index);
  7779. ir_emit_store(proc, gep, fv);
  7780. }
  7781. }
  7782. }
  7783. break;
  7784. }
  7785. case Type_Map: {
  7786. if (cl->elems.count == 0) {
  7787. break;
  7788. }
  7789. gbAllocator a = ir_allocator();
  7790. {
  7791. auto args = array_make<irValue *>(a, 3);
  7792. args[0] = ir_gen_map_header(proc, v, type);
  7793. args[1] = ir_const_int(2*cl->elems.count);
  7794. args[2] = ir_emit_source_code_location(proc, proc_name, pos);
  7795. ir_emit_runtime_call(proc, "__dynamic_map_reserve", args);
  7796. }
  7797. for_array(field_index, cl->elems) {
  7798. Ast *elem = cl->elems[field_index];
  7799. ast_node(fv, FieldValue, elem);
  7800. irValue *key = ir_build_expr(proc, fv->field);
  7801. irValue *value = ir_build_expr(proc, fv->value);
  7802. ir_insert_dynamic_map_key_and_value(proc, v, type, key, value, elem);
  7803. }
  7804. break;
  7805. }
  7806. case Type_Array: {
  7807. if (cl->elems.count > 0) {
  7808. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  7809. auto temp_data = array_make<irCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  7810. // NOTE(bill): Separate value, gep, store into their own chunks
  7811. for_array(i, cl->elems) {
  7812. Ast *elem = cl->elems[i];
  7813. if (elem->kind == Ast_FieldValue) {
  7814. ast_node(fv, FieldValue, elem);
  7815. if (ir_is_elem_const(proc->module, fv->value, et)) {
  7816. continue;
  7817. }
  7818. if (is_ast_range(fv->field)) {
  7819. ast_node(ie, BinaryExpr, fv->field);
  7820. TypeAndValue lo_tav = ie->left->tav;
  7821. TypeAndValue hi_tav = ie->right->tav;
  7822. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7823. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7824. TokenKind op = ie->op.kind;
  7825. i64 lo = exact_value_to_i64(lo_tav.value);
  7826. i64 hi = exact_value_to_i64(hi_tav.value);
  7827. if (op == Token_Ellipsis) {
  7828. hi += 1;
  7829. }
  7830. irValue *value = ir_build_expr(proc, fv->value);
  7831. for (i64 k = lo; k < hi; k++) {
  7832. irCompoundLitElemTempData data = {};
  7833. data.value = value;
  7834. data.elem_index = cast(i32)k;
  7835. array_add(&temp_data, data);
  7836. }
  7837. } else {
  7838. auto tav = fv->field->tav;
  7839. GB_ASSERT(tav.mode == Addressing_Constant);
  7840. i64 index = exact_value_to_i64(tav.value);
  7841. irCompoundLitElemTempData data = {};
  7842. data.value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et);
  7843. data.expr = fv->value;
  7844. data.elem_index = cast(i32)index;
  7845. array_add(&temp_data, data);
  7846. }
  7847. } else {
  7848. if (ir_is_elem_const(proc->module, elem, et)) {
  7849. continue;
  7850. }
  7851. irCompoundLitElemTempData data = {};
  7852. data.expr = elem;
  7853. data.elem_index = cast(i32)i;
  7854. array_add(&temp_data, data);
  7855. }
  7856. }
  7857. for_array(i, temp_data) {
  7858. temp_data[i].gep = ir_emit_array_epi(proc, v, temp_data[i].elem_index);
  7859. }
  7860. for_array(i, temp_data) {
  7861. auto return_ptr_hint_ast = proc->return_ptr_hint_ast;
  7862. auto return_ptr_hint_value = proc->return_ptr_hint_value;
  7863. auto return_ptr_hint_used = proc->return_ptr_hint_used;
  7864. defer (proc->return_ptr_hint_ast = return_ptr_hint_ast);
  7865. defer (proc->return_ptr_hint_value = return_ptr_hint_value);
  7866. defer (proc->return_ptr_hint_used = return_ptr_hint_used);
  7867. irValue *field_expr = temp_data[i].value;
  7868. Ast *expr = temp_data[i].expr;
  7869. proc->return_ptr_hint_value = temp_data[i].gep;
  7870. proc->return_ptr_hint_ast = unparen_expr(expr);
  7871. if (field_expr == nullptr) {
  7872. field_expr = ir_build_expr(proc, expr);
  7873. }
  7874. Type *t = ir_type(field_expr);
  7875. GB_ASSERT(t->kind != Type_Tuple);
  7876. irValue *ev = ir_emit_conv(proc, field_expr, et);
  7877. if (!proc->return_ptr_hint_used) {
  7878. temp_data[i].value = ev;
  7879. }
  7880. }
  7881. for_array(i, temp_data) {
  7882. if (temp_data[i].value != nullptr) {
  7883. ir_emit_store(proc, temp_data[i].gep, temp_data[i].value, false);
  7884. }
  7885. }
  7886. }
  7887. break;
  7888. }
  7889. case Type_EnumeratedArray: {
  7890. if (cl->elems.count > 0) {
  7891. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  7892. auto temp_data = array_make<irCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  7893. // NOTE(bill): Separate value, gep, store into their own chunks
  7894. for_array(i, cl->elems) {
  7895. Ast *elem = cl->elems[i];
  7896. if (elem->kind == Ast_FieldValue) {
  7897. ast_node(fv, FieldValue, elem);
  7898. if (ir_is_elem_const(proc->module, fv->value, et)) {
  7899. continue;
  7900. }
  7901. if (is_ast_range(fv->field)) {
  7902. ast_node(ie, BinaryExpr, fv->field);
  7903. TypeAndValue lo_tav = ie->left->tav;
  7904. TypeAndValue hi_tav = ie->right->tav;
  7905. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7906. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7907. TokenKind op = ie->op.kind;
  7908. i64 lo = exact_value_to_i64(lo_tav.value);
  7909. i64 hi = exact_value_to_i64(hi_tav.value);
  7910. if (op == Token_Ellipsis) {
  7911. hi += 1;
  7912. }
  7913. irValue *value = ir_build_expr(proc, fv->value);
  7914. for (i64 k = lo; k < hi; k++) {
  7915. irCompoundLitElemTempData data = {};
  7916. data.value = value;
  7917. data.elem_index = cast(i32)k;
  7918. array_add(&temp_data, data);
  7919. }
  7920. } else {
  7921. auto tav = fv->field->tav;
  7922. GB_ASSERT(tav.mode == Addressing_Constant);
  7923. i64 index = exact_value_to_i64(tav.value);
  7924. irCompoundLitElemTempData data = {};
  7925. data.value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et);
  7926. data.expr = fv->value;
  7927. data.elem_index = cast(i32)index;
  7928. array_add(&temp_data, data);
  7929. }
  7930. } else {
  7931. if (ir_is_elem_const(proc->module, elem, et)) {
  7932. continue;
  7933. }
  7934. irCompoundLitElemTempData data = {};
  7935. data.expr = elem;
  7936. data.elem_index = cast(i32)i;
  7937. array_add(&temp_data, data);
  7938. }
  7939. }
  7940. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  7941. for_array(i, temp_data) {
  7942. i32 index = temp_data[i].elem_index - index_offset;
  7943. temp_data[i].gep = ir_emit_array_epi(proc, v, index);
  7944. }
  7945. for_array(i, temp_data) {
  7946. auto return_ptr_hint_ast = proc->return_ptr_hint_ast;
  7947. auto return_ptr_hint_value = proc->return_ptr_hint_value;
  7948. auto return_ptr_hint_used = proc->return_ptr_hint_used;
  7949. defer (proc->return_ptr_hint_ast = return_ptr_hint_ast);
  7950. defer (proc->return_ptr_hint_value = return_ptr_hint_value);
  7951. defer (proc->return_ptr_hint_used = return_ptr_hint_used);
  7952. irValue *field_expr = temp_data[i].value;
  7953. Ast *expr = temp_data[i].expr;
  7954. proc->return_ptr_hint_value = temp_data[i].gep;
  7955. proc->return_ptr_hint_ast = unparen_expr(expr);
  7956. if (field_expr == nullptr) {
  7957. field_expr = ir_build_expr(proc, expr);
  7958. }
  7959. Type *t = ir_type(field_expr);
  7960. GB_ASSERT(t->kind != Type_Tuple);
  7961. irValue *ev = ir_emit_conv(proc, field_expr, et);
  7962. if (!proc->return_ptr_hint_used) {
  7963. temp_data[i].value = ev;
  7964. }
  7965. }
  7966. for_array(i, temp_data) {
  7967. if (temp_data[i].value != nullptr) {
  7968. ir_emit_store(proc, temp_data[i].gep, temp_data[i].value, false);
  7969. }
  7970. }
  7971. }
  7972. break;
  7973. }
  7974. case Type_Slice: {
  7975. if (cl->elems.count > 0) {
  7976. Type *elem_type = bt->Slice.elem;
  7977. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  7978. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  7979. irValue *slice = ir_add_module_constant(proc->module, type, exact_value_compound(expr));
  7980. GB_ASSERT(slice->kind == irValue_ConstantSlice);
  7981. irValue *data = ir_emit_array_ep(proc, slice->ConstantSlice.backing_array, v_zero32);
  7982. auto temp_data = array_make<irCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  7983. for_array(i, cl->elems) {
  7984. Ast *elem = cl->elems[i];
  7985. if (elem->kind == Ast_FieldValue) {
  7986. ast_node(fv, FieldValue, elem);
  7987. if (ir_is_elem_const(proc->module, fv->value, et)) {
  7988. continue;
  7989. }
  7990. if (is_ast_range(fv->field)) {
  7991. ast_node(ie, BinaryExpr, fv->field);
  7992. TypeAndValue lo_tav = ie->left->tav;
  7993. TypeAndValue hi_tav = ie->right->tav;
  7994. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7995. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7996. TokenKind op = ie->op.kind;
  7997. i64 lo = exact_value_to_i64(lo_tav.value);
  7998. i64 hi = exact_value_to_i64(hi_tav.value);
  7999. if (op == Token_Ellipsis) {
  8000. hi += 1;
  8001. }
  8002. irValue *value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et);
  8003. for (i64 k = lo; k < hi; k++) {
  8004. irCompoundLitElemTempData data = {};
  8005. data.value = value;
  8006. data.elem_index = cast(i32)k;
  8007. array_add(&temp_data, data);
  8008. }
  8009. } else {
  8010. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  8011. i64 index = exact_value_to_i64(fv->field->tav.value);
  8012. irValue *field_expr = ir_build_expr(proc, fv->value);
  8013. GB_ASSERT(!is_type_tuple(ir_type(field_expr)));
  8014. irValue *ev = ir_emit_conv(proc, field_expr, et);
  8015. irCompoundLitElemTempData data = {};
  8016. data.value = ev;
  8017. data.elem_index = cast(i32)index;
  8018. array_add(&temp_data, data);
  8019. }
  8020. } else {
  8021. if (ir_is_elem_const(proc->module, elem, et)) {
  8022. continue;
  8023. }
  8024. irValue *field_expr = ir_build_expr(proc, elem);
  8025. GB_ASSERT(!is_type_tuple(ir_type(field_expr)));
  8026. irValue *ev = ir_emit_conv(proc, field_expr, et);
  8027. irCompoundLitElemTempData data = {};
  8028. data.value = ev;
  8029. data.elem_index = cast(i32)i;
  8030. array_add(&temp_data, data);
  8031. }
  8032. }
  8033. for_array(i, temp_data) {
  8034. temp_data[i].gep = ir_emit_ptr_offset(proc, data, ir_const_int(temp_data[i].elem_index));
  8035. }
  8036. for_array(i, temp_data) {
  8037. ir_emit_store(proc, temp_data[i].gep, temp_data[i].value);
  8038. }
  8039. irValue *count = ir_const_int(slice->ConstantSlice.count);
  8040. ir_fill_slice(proc, v, data, count);
  8041. }
  8042. break;
  8043. }
  8044. case Type_DynamicArray: {
  8045. if (cl->elems.count == 0) {
  8046. break;
  8047. }
  8048. Type *et = bt->DynamicArray.elem;
  8049. gbAllocator a = ir_allocator();
  8050. irValue *size = ir_const_int(type_size_of(et));
  8051. irValue *align = ir_const_int(type_align_of(et));
  8052. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  8053. {
  8054. auto args = array_make<irValue *>(a, 5);
  8055. args[0] = ir_emit_conv(proc, v, t_rawptr);
  8056. args[1] = size;
  8057. args[2] = align;
  8058. args[3] = ir_const_int(2*item_count); // TODO(bill): Is this too much waste?
  8059. args[4] = ir_emit_source_code_location(proc, proc_name, pos);
  8060. ir_emit_runtime_call(proc, "__dynamic_array_reserve", args);
  8061. }
  8062. irValue *items = ir_generate_array(proc->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  8063. for_array(i, cl->elems) {
  8064. Ast *elem = cl->elems[i];
  8065. if (elem->kind == Ast_FieldValue) {
  8066. ast_node(fv, FieldValue, elem);
  8067. if (is_ast_range(fv->field)) {
  8068. ast_node(ie, BinaryExpr, fv->field);
  8069. TypeAndValue lo_tav = ie->left->tav;
  8070. TypeAndValue hi_tav = ie->right->tav;
  8071. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  8072. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  8073. TokenKind op = ie->op.kind;
  8074. i64 lo = exact_value_to_i64(lo_tav.value);
  8075. i64 hi = exact_value_to_i64(hi_tav.value);
  8076. if (op == Token_Ellipsis) {
  8077. hi += 1;
  8078. }
  8079. irValue *value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et);
  8080. for (i64 k = lo; k < hi; k++) {
  8081. irValue *ep = ir_emit_array_epi(proc, items, cast(i32)k);
  8082. ir_emit_store(proc, ep, value);
  8083. }
  8084. } else {
  8085. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  8086. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  8087. irValue *ev = ir_build_expr(proc, fv->value);
  8088. irValue *value = ir_emit_conv(proc, ev, et);
  8089. irValue *ep = ir_emit_array_epi(proc, items, cast(i32)field_index);
  8090. ir_emit_store(proc, ep, value);
  8091. }
  8092. } else {
  8093. irValue *value = ir_emit_conv(proc, ir_build_expr(proc, elem), et);
  8094. irValue *ep = ir_emit_array_epi(proc, items, cast(i32)i);
  8095. ir_emit_store(proc, ep, value);
  8096. }
  8097. }
  8098. {
  8099. auto args = array_make<irValue *>(a, 6);
  8100. args[0] = ir_emit_conv(proc, v, t_rawptr);
  8101. args[1] = size;
  8102. args[2] = align;
  8103. args[3] = ir_emit_conv(proc, items, t_rawptr);
  8104. args[4] = ir_const_int(item_count);
  8105. args[5] = ir_emit_source_code_location(proc, proc_name, pos);
  8106. ir_emit_runtime_call(proc, "__dynamic_array_append", args);
  8107. }
  8108. break;
  8109. }
  8110. case Type_Basic: {
  8111. GB_ASSERT(is_type_any(bt));
  8112. if (cl->elems.count > 0) {
  8113. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  8114. String field_names[2] = {
  8115. str_lit("data"),
  8116. str_lit("id"),
  8117. };
  8118. Type *field_types[2] = {
  8119. t_rawptr,
  8120. t_typeid,
  8121. };
  8122. for_array(field_index, cl->elems) {
  8123. Ast *elem = cl->elems[field_index];
  8124. irValue *field_expr = nullptr;
  8125. isize index = field_index;
  8126. if (elem->kind == Ast_FieldValue) {
  8127. ast_node(fv, FieldValue, elem);
  8128. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  8129. index = sel.index[0];
  8130. elem = fv->value;
  8131. } else {
  8132. TypeAndValue tav = type_and_value_of_expr(elem);
  8133. Selection sel = lookup_field(bt, field_names[field_index], false);
  8134. index = sel.index[0];
  8135. }
  8136. field_expr = ir_build_expr(proc, elem);
  8137. GB_ASSERT(ir_type(field_expr)->kind != Type_Tuple);
  8138. Type *ft = field_types[index];
  8139. irValue *fv = ir_emit_conv(proc, field_expr, ft);
  8140. irValue *gep = ir_emit_struct_ep(proc, v, cast(i32)index);
  8141. ir_emit_store(proc, gep, fv);
  8142. }
  8143. }
  8144. break;
  8145. }
  8146. case Type_BitSet: {
  8147. i64 sz = type_size_of(type);
  8148. if (cl->elems.count > 0 && sz > 0) {
  8149. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  8150. irValue *lower = ir_value_constant(t_int, exact_value_i64(bt->BitSet.lower));
  8151. for_array(i, cl->elems) {
  8152. Ast *elem = cl->elems[i];
  8153. GB_ASSERT(elem->kind != Ast_FieldValue);
  8154. if (ir_is_elem_const(proc->module, elem, et)) {
  8155. continue;
  8156. }
  8157. irValue *expr = ir_build_expr(proc, elem);
  8158. GB_ASSERT(ir_type(expr)->kind != Type_Tuple);
  8159. Type *it = bit_set_to_int(bt);
  8160. irValue *e = ir_emit_conv(proc, expr, it);
  8161. e = ir_emit_arith(proc, Token_Sub, e, lower, it);
  8162. e = ir_emit_arith(proc, Token_Shl, v_one, e, it);
  8163. irValue *old_value = ir_emit_bitcast(proc, ir_emit_load(proc, v), it);
  8164. irValue *new_value = ir_emit_arith(proc, Token_Or, old_value, e, it);
  8165. new_value = ir_emit_bitcast(proc, new_value, type);
  8166. ir_emit_store(proc, v, new_value);
  8167. }
  8168. }
  8169. break;
  8170. }
  8171. }
  8172. return ir_addr(v);
  8173. case_end;
  8174. case_ast_node(tc, TypeCast, expr);
  8175. Type *type = type_of_expr(expr);
  8176. irValue *x = ir_build_expr(proc, tc->expr);
  8177. irValue *e = nullptr;
  8178. switch (tc->token.kind) {
  8179. case Token_cast:
  8180. e = ir_emit_conv(proc, x, type);
  8181. break;
  8182. case Token_transmute:
  8183. e = ir_emit_transmute(proc, x, type);
  8184. break;
  8185. default:
  8186. GB_PANIC("Invalid AST TypeCast");
  8187. }
  8188. irValue *v = ir_add_local_generated(proc, type, false);
  8189. ir_emit_store(proc, v, e);
  8190. return ir_addr(v);
  8191. case_end;
  8192. case_ast_node(ac, AutoCast, expr);
  8193. return ir_build_addr(proc, ac->expr);
  8194. case_end;
  8195. }
  8196. TokenPos token_pos = ast_token(expr).pos;
  8197. GB_PANIC("Unexpected address expression\n"
  8198. "\tAst: %.*s @ "
  8199. "%.*s(%td:%td)\n",
  8200. LIT(ast_strings[expr->kind]),
  8201. LIT(token_pos.file), token_pos.line, token_pos.column);
  8202. return ir_addr(nullptr);
  8203. }
  8204. void ir_build_assign_op(irProcedure *proc, irAddr const &lhs, irValue *value, TokenKind op) {
  8205. irValue *old_value = ir_addr_load(proc, lhs);
  8206. Type *type = ir_type(old_value);
  8207. irValue *change = value;
  8208. if (is_type_pointer(type) && is_type_integer(ir_type(value))) {
  8209. change = ir_emit_conv(proc, value, default_type(ir_type(value)));
  8210. } else {
  8211. change = ir_emit_conv(proc, value, type);
  8212. }
  8213. irValue *new_value = ir_emit_arith(proc, op, old_value, change, type);
  8214. ir_addr_store(proc, lhs, new_value);
  8215. }
  8216. irValue *ir_build_cond(irProcedure *proc, Ast *cond, irBlock *true_block, irBlock *false_block) {
  8217. switch (cond->kind) {
  8218. case_ast_node(pe, ParenExpr, cond);
  8219. return ir_build_cond(proc, pe->expr, true_block, false_block);
  8220. case_end;
  8221. case_ast_node(ue, UnaryExpr, cond);
  8222. if (ue->op.kind == Token_Not) {
  8223. return ir_build_cond(proc, ue->expr, false_block, true_block);
  8224. }
  8225. case_end;
  8226. case_ast_node(be, BinaryExpr, cond);
  8227. if (be->op.kind == Token_CmpAnd) {
  8228. irBlock *block = ir_new_block(proc, nullptr, "cmp.and");
  8229. ir_build_cond(proc, be->left, block, false_block);
  8230. ir_start_block(proc, block);
  8231. return ir_build_cond(proc, be->right, true_block, false_block);
  8232. } else if (be->op.kind == Token_CmpOr) {
  8233. irBlock *block = ir_new_block(proc, nullptr, "cmp.or");
  8234. ir_build_cond(proc, be->left, true_block, block);
  8235. ir_start_block(proc, block);
  8236. return ir_build_cond(proc, be->right, true_block, false_block);
  8237. }
  8238. case_end;
  8239. }
  8240. irValue *v = ir_build_expr(proc, cond);
  8241. v = ir_emit_conv(proc, v, t_bool);
  8242. ir_emit_if(proc, v, true_block, false_block);
  8243. return v;
  8244. }
  8245. void ir_build_nested_proc(irProcedure *proc, AstProcLit *pd, Entity *e) {
  8246. GB_ASSERT(pd->body != nullptr);
  8247. if (ir_min_dep_entity(proc->module, e) == false) {
  8248. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  8249. return;
  8250. }
  8251. // NOTE(bill): Generate a new name
  8252. // parent.name-guid
  8253. String original_name = e->token.string;
  8254. String pd_name = original_name;
  8255. if (e->Procedure.link_name.len > 0) {
  8256. pd_name = e->Procedure.link_name;
  8257. }
  8258. isize name_len = proc->name.len + 1 + pd_name.len + 1 + 10 + 1;
  8259. u8 *name_text = gb_alloc_array(ir_allocator(), u8, name_len);
  8260. i32 guid = cast(i32)proc->children.count;
  8261. name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s.%.*s-%d", LIT(proc->name), LIT(pd_name), guid);
  8262. String name = make_string(name_text, name_len-1);
  8263. set_procedure_abi_types(e->type);
  8264. irValue *value = ir_value_procedure(proc->module, e, e->type, pd->type, pd->body, name);
  8265. value->Proc.tags = pd->tags;
  8266. value->Proc.inlining = pd->inlining;
  8267. value->Proc.parent = proc;
  8268. ir_module_add_value(proc->module, e, value);
  8269. array_add(&proc->children, &value->Proc);
  8270. array_add(&proc->module->procs_to_generate, value);
  8271. }
  8272. void ir_build_constant_value_decl(irProcedure *proc, AstValueDecl *vd) {
  8273. if (vd == nullptr || vd->is_mutable) {
  8274. return;
  8275. }
  8276. for_array(i, vd->names) {
  8277. Ast *ident = vd->names[i];
  8278. GB_ASSERT(ident->kind == Ast_Ident);
  8279. Entity *e = entity_of_node(ident);
  8280. GB_ASSERT(e != nullptr);
  8281. switch (e->kind) {
  8282. case Entity_TypeName:
  8283. case Entity_Procedure:
  8284. break;
  8285. default:
  8286. continue;
  8287. }
  8288. if (e->kind == Entity_TypeName) {
  8289. bool polymorphic_struct = false;
  8290. if (e->type != nullptr && e->kind == Entity_TypeName) {
  8291. Type *bt = base_type(e->type);
  8292. if (bt->kind == Type_Struct) {
  8293. polymorphic_struct = bt->Struct.is_polymorphic;
  8294. }
  8295. }
  8296. if (!polymorphic_struct && !ir_min_dep_entity(proc->module, e)) {
  8297. continue;
  8298. }
  8299. // NOTE(bill): Generate a new name
  8300. // parent_proc.name-guid
  8301. String ts_name = e->token.string;
  8302. irModule *m = proc->module;
  8303. isize name_len = proc->name.len + 1 + ts_name.len + 1 + 10 + 1;
  8304. u8 *name_text = gb_alloc_array(ir_allocator(), u8, name_len);
  8305. i32 guid = cast(i32)m->members.entries.count;
  8306. name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s.%.*s-%d", LIT(proc->name), LIT(ts_name), guid);
  8307. String name = make_string(name_text, name_len-1);
  8308. irValue *value = ir_value_type_name(name, e->type);
  8309. ir_add_entity_name(m, e, name);
  8310. ir_gen_global_type_name(m, e, name);
  8311. } else if (e->kind == Entity_Procedure) {
  8312. CheckerInfo *info = proc->module->info;
  8313. DeclInfo *decl = decl_info_of_entity(e);
  8314. ast_node(pl, ProcLit, decl->proc_lit);
  8315. if (pl->body != nullptr) {
  8316. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  8317. if (found) {
  8318. auto procs = *found;
  8319. for_array(i, procs) {
  8320. Entity *e = procs[i];
  8321. if (!ir_min_dep_entity(proc->module, e)) {
  8322. continue;
  8323. }
  8324. DeclInfo *d = decl_info_of_entity(e);
  8325. ir_build_nested_proc(proc, &d->proc_lit->ProcLit, e);
  8326. }
  8327. } else {
  8328. ir_build_nested_proc(proc, pl, e);
  8329. }
  8330. } else {
  8331. // FFI - Foreign function interace
  8332. String original_name = e->token.string;
  8333. String name = original_name;
  8334. if (e->Procedure.is_foreign) {
  8335. ir_add_foreign_library_path(proc->module, e->Procedure.foreign_library);
  8336. }
  8337. if (e->Procedure.link_name.len > 0) {
  8338. name = e->Procedure.link_name;
  8339. }
  8340. StringHashKey key = string_hash_string(name);
  8341. irValue **prev_value = string_map_get(&proc->module->members, key);
  8342. if (prev_value != nullptr) {
  8343. // NOTE(bill): Don't do mutliple declarations in the IR
  8344. return;
  8345. }
  8346. set_procedure_abi_types(e->type);
  8347. irValue *value = ir_value_procedure(proc->module, e, e->type, pl->type, pl->body, name);
  8348. value->Proc.tags = pl->tags;
  8349. value->Proc.inlining = pl->inlining;
  8350. if (value->Proc.is_foreign || value->Proc.is_export) {
  8351. string_map_set(&proc->module->members, key, value);
  8352. } else {
  8353. array_add(&proc->children, &value->Proc);
  8354. }
  8355. ir_module_add_value(proc->module, e, value);
  8356. ir_build_proc(value, proc);
  8357. }
  8358. }
  8359. }
  8360. }
  8361. void ir_build_stmt_list(irProcedure *proc, Slice<Ast *> stmts) {
  8362. // NOTE(bill): Precollect constant entities
  8363. for_array(i, stmts) {
  8364. Ast *stmt = stmts[i];
  8365. switch (stmt->kind) {
  8366. case_ast_node(vd, ValueDecl, stmt);
  8367. ir_build_constant_value_decl(proc, vd);
  8368. case_end;
  8369. case_ast_node(fb, ForeignBlockDecl, stmt);
  8370. ast_node(block, BlockStmt, fb->body);
  8371. ir_build_stmt_list(proc, block->stmts);
  8372. case_end;
  8373. }
  8374. }
  8375. for_array(i, stmts) {
  8376. ir_build_stmt(proc, stmts[i]);
  8377. }
  8378. }
  8379. void ir_build_stmt_internal(irProcedure *proc, Ast *node);
  8380. void ir_build_stmt(irProcedure *proc, Ast *node) {
  8381. Ast *prev_stmt = proc->curr_stmt;
  8382. proc->curr_stmt = node;
  8383. u64 prev_state_flags = proc->module->state_flags;
  8384. defer (proc->module->state_flags = prev_state_flags);
  8385. if (node->state_flags != 0) {
  8386. u64 in = node->state_flags;
  8387. u64 out = proc->module->state_flags;
  8388. if (in & StateFlag_bounds_check) {
  8389. out |= StateFlag_bounds_check;
  8390. out &= ~StateFlag_no_bounds_check;
  8391. } else if (in & StateFlag_no_bounds_check) {
  8392. out |= StateFlag_no_bounds_check;
  8393. out &= ~StateFlag_bounds_check;
  8394. }
  8395. proc->module->state_flags = out;
  8396. }
  8397. ir_push_debug_location(proc->module, node, proc->debug_scope);
  8398. ir_build_stmt_internal(proc, node);
  8399. ir_pop_debug_location(proc->module);
  8400. proc->curr_stmt = prev_stmt;
  8401. }
  8402. void ir_build_when_stmt(irProcedure *proc, AstWhenStmt *ws) {
  8403. irValue *cond = ir_build_expr(proc, ws->cond);
  8404. GB_ASSERT(cond->kind == irValue_Constant &&
  8405. is_type_boolean(ir_type(cond)));
  8406. GB_ASSERT(cond->Constant.value.kind == ExactValue_Bool);
  8407. if (cond->Constant.value.value_bool) {
  8408. ir_build_stmt_list(proc, ws->body->BlockStmt.stmts);
  8409. } else if (ws->else_stmt) {
  8410. switch (ws->else_stmt->kind) {
  8411. case Ast_BlockStmt:
  8412. ir_build_stmt_list(proc, ws->else_stmt->BlockStmt.stmts);
  8413. break;
  8414. case Ast_WhenStmt:
  8415. ir_build_when_stmt(proc, &ws->else_stmt->WhenStmt);
  8416. break;
  8417. default:
  8418. GB_PANIC("Invalid 'else' statement in 'when' statement");
  8419. break;
  8420. }
  8421. }
  8422. }
  8423. void ir_build_range_indexed(irProcedure *proc, irValue *expr, Type *val_type, irValue *count_ptr,
  8424. irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  8425. irValue *count = nullptr;
  8426. Type *expr_type = base_type(type_deref(ir_type(expr)));
  8427. switch (expr_type->kind) {
  8428. case Type_Array:
  8429. count = ir_const_int(expr_type->Array.count);
  8430. break;
  8431. }
  8432. irValue *val = nullptr;
  8433. irValue *idx = nullptr;
  8434. irBlock *loop = nullptr;
  8435. irBlock *done = nullptr;
  8436. irBlock *body = nullptr;
  8437. irValue *index = ir_add_local_generated(proc, t_int, false);
  8438. ir_emit_store(proc, index, ir_const_int(-1));
  8439. loop = ir_new_block(proc, nullptr, "for.index.loop");
  8440. ir_emit_jump(proc, loop);
  8441. ir_start_block(proc, loop);
  8442. irValue *incr = ir_emit_arith(proc, Token_Add, ir_emit_load(proc, index), v_one, t_int);
  8443. ir_emit_store(proc, index, incr);
  8444. body = ir_new_block(proc, nullptr, "for.index.body");
  8445. done = ir_new_block(proc, nullptr, "for.index.done");
  8446. if (count == nullptr) {
  8447. GB_ASSERT(count_ptr != nullptr);
  8448. count = ir_emit_load(proc, count_ptr);
  8449. }
  8450. irValue *cond = ir_emit_comp(proc, Token_Lt, incr, count);
  8451. ir_emit_if(proc, cond, body, done);
  8452. ir_start_block(proc, body);
  8453. idx = ir_emit_load(proc, index);
  8454. switch (expr_type->kind) {
  8455. case Type_Array: {
  8456. if (val_type != nullptr) {
  8457. val = ir_emit_load(proc, ir_emit_array_ep(proc, expr, idx));
  8458. }
  8459. break;
  8460. }
  8461. case Type_EnumeratedArray: {
  8462. if (val_type != nullptr) {
  8463. val = ir_emit_load(proc, ir_emit_array_ep(proc, expr, idx));
  8464. }
  8465. // NOTE(bill): Override the idx value for the enumeration
  8466. Type *index_type =expr_type->EnumeratedArray.index;
  8467. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  8468. idx = ir_emit_arith(proc, Token_Add, idx, ir_value_constant(index_type, expr_type->EnumeratedArray.min_value), index_type);
  8469. }
  8470. idx = ir_emit_conv(proc, idx, expr_type->EnumeratedArray.index);
  8471. break;
  8472. }
  8473. case Type_Slice: {
  8474. if (val_type != nullptr) {
  8475. irValue *elem = ir_slice_elem(proc, expr);
  8476. val = ir_emit_load(proc, ir_emit_ptr_offset(proc, elem, idx));
  8477. }
  8478. break;
  8479. }
  8480. case Type_DynamicArray: {
  8481. if (val_type != nullptr) {
  8482. irValue *elem = ir_emit_struct_ep(proc, expr, 0);
  8483. elem = ir_emit_load(proc, elem);
  8484. val = ir_emit_load(proc, ir_emit_ptr_offset(proc, elem, idx));
  8485. }
  8486. break;
  8487. }
  8488. case Type_Map: {
  8489. irValue *entries = ir_map_entries_ptr(proc, expr);
  8490. irValue *elem = ir_emit_struct_ep(proc, entries, 0);
  8491. elem = ir_emit_load(proc, elem);
  8492. irValue *entry = ir_emit_ptr_offset(proc, elem, idx);
  8493. idx = ir_emit_load(proc, ir_emit_struct_ep(proc, entry, 2));
  8494. val = ir_emit_load(proc, ir_emit_struct_ep(proc, entry, 3));
  8495. break;
  8496. }
  8497. default:
  8498. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  8499. break;
  8500. }
  8501. if (val_) *val_ = val;
  8502. if (idx_) *idx_ = idx;
  8503. if (loop_) *loop_ = loop;
  8504. if (done_) *done_ = done;
  8505. }
  8506. void ir_build_range_string(irProcedure *proc, irValue *expr, Type *val_type,
  8507. irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  8508. irValue *count = v_zero;
  8509. Type *expr_type = base_type(ir_type(expr));
  8510. switch (expr_type->kind) {
  8511. case Type_Basic:
  8512. count = ir_string_len(proc, expr);
  8513. break;
  8514. default:
  8515. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  8516. break;
  8517. }
  8518. irValue *val = nullptr;
  8519. irValue *idx = nullptr;
  8520. irBlock *loop = nullptr;
  8521. irBlock *done = nullptr;
  8522. irBlock *body = nullptr;
  8523. irValue *offset_ = ir_add_local_generated(proc, t_int, false);
  8524. ir_emit_store(proc, offset_, v_zero);
  8525. loop = ir_new_block(proc, nullptr, "for.string.loop");
  8526. ir_emit_jump(proc, loop);
  8527. ir_start_block(proc, loop);
  8528. body = ir_new_block(proc, nullptr, "for.string.body");
  8529. done = ir_new_block(proc, nullptr, "for.string.done");
  8530. irValue *offset = ir_emit_load(proc, offset_);
  8531. irValue *cond = ir_emit_comp(proc, Token_Lt, offset, count);
  8532. ir_emit_if(proc, cond, body, done);
  8533. ir_start_block(proc, body);
  8534. irValue *str_elem = ir_emit_ptr_offset(proc, ir_string_elem(proc, expr), offset);
  8535. irValue *str_len = ir_emit_arith(proc, Token_Sub, count, offset, t_int);
  8536. auto args = array_make<irValue *>(ir_allocator(), 1);
  8537. args[0] = ir_emit_string(proc, str_elem, str_len);
  8538. irValue *rune_and_len = ir_emit_runtime_call(proc, "string_decode_rune", args);
  8539. irValue *len = ir_emit_struct_ev(proc, rune_and_len, 1);
  8540. ir_emit_store(proc, offset_, ir_emit_arith(proc, Token_Add, offset, len, t_int));
  8541. idx = offset;
  8542. if (val_type != nullptr) {
  8543. val = ir_emit_struct_ev(proc, rune_and_len, 0);
  8544. }
  8545. if (val_) *val_ = val;
  8546. if (idx_) *idx_ = idx;
  8547. if (loop_) *loop_ = loop;
  8548. if (done_) *done_ = done;
  8549. }
  8550. void ir_build_range_interval(irProcedure *proc, AstBinaryExpr *node, Type *val_type,
  8551. irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  8552. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  8553. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  8554. irValue *lower = ir_build_expr(proc, node->left);
  8555. irValue *upper = nullptr;
  8556. irValue *val = nullptr;
  8557. irValue *idx = nullptr;
  8558. irBlock *loop = nullptr;
  8559. irBlock *done = nullptr;
  8560. irBlock *body = nullptr;
  8561. if (val_type == nullptr) {
  8562. val_type = ir_type(lower);
  8563. }
  8564. irValue *value = ir_add_local_generated(proc, val_type, false);
  8565. ir_emit_store(proc, value, lower);
  8566. irValue *index = ir_add_local_generated(proc, t_int, false);
  8567. ir_emit_store(proc, index, ir_const_int(0));
  8568. loop = ir_new_block(proc, nullptr, "for.interval.loop");
  8569. ir_emit_jump(proc, loop);
  8570. ir_start_block(proc, loop);
  8571. body = ir_new_block(proc, nullptr, "for.interval.body");
  8572. done = ir_new_block(proc, nullptr, "for.interval.done");
  8573. TokenKind op = Token_Lt;
  8574. switch (node->op.kind) {
  8575. case Token_Ellipsis: op = Token_LtEq; break;
  8576. case Token_RangeHalf: op = Token_Lt; break;
  8577. default: GB_PANIC("Invalid interval operator"); break;
  8578. }
  8579. upper = ir_build_expr(proc, node->right);
  8580. irValue *curr_value = ir_emit_load(proc, value);
  8581. irValue *cond = ir_emit_comp(proc, op, curr_value, upper);
  8582. ir_emit_if(proc, cond, body, done);
  8583. ir_start_block(proc, body);
  8584. if (value != nullptr) {
  8585. val = ir_emit_load(proc, value);
  8586. }
  8587. idx = ir_emit_load(proc, index);
  8588. ir_emit_increment(proc, value);
  8589. ir_emit_increment(proc, index);
  8590. if (val_) *val_ = val;
  8591. if (idx_) *idx_ = idx;
  8592. if (loop_) *loop_ = loop;
  8593. if (done_) *done_ = done;
  8594. }
  8595. void ir_build_range_enum(irProcedure *proc, Type *enum_type, Type *val_type, irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  8596. Type *t = enum_type;
  8597. GB_ASSERT(is_type_enum(t));
  8598. Type *enum_ptr = alloc_type_pointer(t);
  8599. t = base_type(t);
  8600. Type *core_elem = core_type(t);
  8601. GB_ASSERT(t->kind == Type_Enum);
  8602. i64 enum_count = t->Enum.fields.count;
  8603. irValue *max_count = ir_const_int(enum_count);
  8604. irValue *ti = ir_type_info(proc, t);
  8605. irValue *variant = ir_emit_struct_ep(proc, ti, 4);
  8606. irValue *eti_ptr = ir_emit_conv(proc, variant, t_type_info_enum_ptr);
  8607. irValue *values = ir_emit_load(proc, ir_emit_struct_ep(proc, eti_ptr, 2));
  8608. irValue *values_data = ir_slice_elem(proc, values);
  8609. irValue *offset_ = ir_add_local_generated(proc, t_int, false);
  8610. ir_emit_store(proc, offset_, v_zero);
  8611. irBlock *loop = ir_new_block(proc, nullptr, "for.enum.loop");
  8612. ir_emit_jump(proc, loop);
  8613. ir_start_block(proc, loop);
  8614. irBlock *body = ir_new_block(proc, nullptr, "for.enum.body");
  8615. irBlock *done = ir_new_block(proc, nullptr, "for.enum.done");
  8616. irValue *offset = ir_emit_load(proc, offset_);
  8617. irValue *cond = ir_emit_comp(proc, Token_Lt, offset, max_count);
  8618. ir_emit_if(proc, cond, body, done);
  8619. ir_start_block(proc, body);
  8620. irValue *val_ptr = ir_emit_ptr_offset(proc, values_data, offset);
  8621. ir_emit_increment(proc, offset_);
  8622. irValue *val = nullptr;
  8623. if (val_type != nullptr) {
  8624. GB_ASSERT(are_types_identical(enum_type, val_type));
  8625. if (is_type_integer(core_elem)) {
  8626. irValue *i = ir_emit_load(proc, val_ptr);
  8627. val = ir_emit_conv(proc, i, t);
  8628. } else {
  8629. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  8630. }
  8631. }
  8632. if (val_) *val_ = val;
  8633. if (idx_) *idx_ = offset;
  8634. if (loop_) *loop_ = loop;
  8635. if (done_) *done_ = done;
  8636. }
  8637. void ir_build_range_tuple(irProcedure *proc, Ast *expr, Type *val0_type, Type *val1_type,
  8638. irValue **val0_, irValue **val1_, irBlock **loop_, irBlock **done_) {
  8639. irBlock *loop = ir_new_block(proc, nullptr, "for.tuple.loop");
  8640. ir_emit_jump(proc, loop);
  8641. ir_start_block(proc, loop);
  8642. irBlock *body = ir_new_block(proc, nullptr, "for.tuple.body");
  8643. irBlock *done = ir_new_block(proc, nullptr, "for.tuple.done");
  8644. irValue *tuple_value = ir_build_expr(proc, expr);
  8645. Type *tuple = ir_type(tuple_value);
  8646. GB_ASSERT(tuple->kind == Type_Tuple);
  8647. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  8648. i32 cond_index = tuple_count-1;
  8649. irValue *cond = ir_emit_struct_ev(proc, tuple_value, cond_index);
  8650. ir_emit_if(proc, cond, body, done);
  8651. ir_start_block(proc, body);
  8652. irValue *val0 = nullptr;
  8653. if (val0_) *val0_ = ir_emit_struct_ev(proc, tuple_value, 0);
  8654. if (val1_) *val1_ = ir_emit_struct_ev(proc, tuple_value, 1);
  8655. if (loop_) *loop_ = loop;
  8656. if (done_) *done_ = done;
  8657. }
  8658. void ir_store_type_case_implicit(irProcedure *proc, Ast *clause, irValue *value) {
  8659. Entity *e = implicit_entity_of_node(clause);
  8660. GB_ASSERT(e != nullptr);
  8661. if (e->flags & EntityFlag_Value) {
  8662. // by value
  8663. irValue *x = ir_add_local(proc, e, nullptr, false);
  8664. GB_ASSERT(are_types_identical(ir_type(value), e->type));
  8665. ir_emit_store(proc, x, value);
  8666. } else {
  8667. // by reference
  8668. ir_module_add_value(proc->module, e, value);
  8669. }
  8670. }
  8671. irAddr ir_store_range_stmt_val(irProcedure *proc, Ast *stmt_val, irValue *value) {
  8672. Entity *e = entity_of_node(stmt_val);
  8673. if (e == nullptr) {
  8674. return {};
  8675. }
  8676. if ((e->flags & EntityFlag_Value) == 0) {
  8677. if (value->kind == irValue_Instr) {
  8678. if (value->Instr.kind == irInstr_Load) {
  8679. irValue *ptr = value->Instr.Load.address;
  8680. Type *vt = type_deref(ir_type(ptr));
  8681. if (!are_types_identical(vt, e->type)) {
  8682. GB_ASSERT(are_types_identical(base_type(vt), base_type(e->type)));
  8683. ptr = ir_emit_conv(proc, ptr, alloc_type_pointer(e->type));
  8684. }
  8685. ir_module_add_value(proc->module, e, ptr);
  8686. return ir_addr(ptr);
  8687. }
  8688. }
  8689. }
  8690. // by value
  8691. irAddr addr = ir_addr(ir_add_local(proc, e, nullptr, false));
  8692. Type *vt = ir_type(value);
  8693. Type *base_et = base_type(e->type);
  8694. Type *base_vt = base_type(vt);
  8695. if (!are_types_identical(e->type, vt)) {
  8696. if (are_types_identical(base_et, base_vt)) {
  8697. value = ir_emit_conv(proc, value, e->type);
  8698. } else {
  8699. // gb_printf_err("%s\n", expr_to_string(stmt_val));
  8700. // gb_printf_err("Entity: %s -> Value: %s\n", type_to_string(e->type), type_to_string(vt));
  8701. // Token tok = ast_token(stmt_val);
  8702. // gb_printf_err("%.*s(%td:%td)\n", LIT(tok.pos.file), tok.pos.line, tok.pos.column);
  8703. }
  8704. }
  8705. ir_addr_store(proc, addr, value);
  8706. return addr;
  8707. }
  8708. void ir_type_case_body(irProcedure *proc, Ast *label, Ast *clause, irBlock *body, irBlock *done) {
  8709. ast_node(cc, CaseClause, clause);
  8710. ir_push_target_list(proc, label, done, nullptr, nullptr);
  8711. ir_open_scope(proc);
  8712. ir_build_stmt_list(proc, cc->stmts);
  8713. ir_close_scope(proc, irDeferExit_Default, body);
  8714. ir_pop_target_list(proc);
  8715. ir_emit_jump(proc, done);
  8716. }
  8717. void ir_build_stmt_internal(irProcedure *proc, Ast *node) {
  8718. switch (node->kind) {
  8719. case_ast_node(bs, EmptyStmt, node);
  8720. case_end;
  8721. case_ast_node(us, UsingStmt, node);
  8722. case_end;
  8723. case_ast_node(ws, WhenStmt, node);
  8724. ir_build_when_stmt(proc, ws);
  8725. case_end;
  8726. case_ast_node(vd, ValueDecl, node);
  8727. if (vd->is_mutable) {
  8728. irModule *m = proc->module;
  8729. bool is_static = false;
  8730. if (vd->names.count > 0) {
  8731. Entity *e = entity_of_node(vd->names[0]);
  8732. if (e->flags & EntityFlag_Static) {
  8733. // NOTE(bill): If one of the entities is static, they all are
  8734. is_static = true;
  8735. }
  8736. }
  8737. if (is_static) {
  8738. for_array(i, vd->names) {
  8739. irValue *value = nullptr;
  8740. if (vd->values.count > 0) {
  8741. GB_ASSERT(vd->names.count == vd->values.count);
  8742. Ast *ast_value = vd->values[i];
  8743. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  8744. ast_value->tav.mode == Addressing_Invalid);
  8745. value = ir_add_module_constant(m, ast_value->tav.type, ast_value->tav.value);
  8746. }
  8747. Ast *ident = vd->names[i];
  8748. GB_ASSERT(!is_blank_ident(ident));
  8749. Entity *e = entity_of_node(ident);
  8750. GB_ASSERT(e->flags & EntityFlag_Static);
  8751. String name = e->token.string;
  8752. String mangled_name = {};
  8753. {
  8754. gbString str = gb_string_make_length(permanent_allocator(), proc->name.text, proc->name.len);
  8755. str = gb_string_appendc(str, "-");
  8756. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  8757. mangled_name.text = cast(u8 *)str;
  8758. mangled_name.len = gb_string_length(str);
  8759. }
  8760. ir_add_entity_name(m, e, mangled_name);
  8761. irValue *g = ir_value_global(e, value);
  8762. g->Global.name = mangled_name;
  8763. g->Global.is_private = true;
  8764. if (e->Variable.thread_local_model != "") {
  8765. g->Global.thread_local_model = e->Variable.thread_local_model;
  8766. } else {
  8767. g->Global.is_internal = true;
  8768. }
  8769. ir_module_add_value(proc->module, e, g);
  8770. string_map_set(&proc->module->members, mangled_name, g);
  8771. }
  8772. return;
  8773. }
  8774. gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&m->tmp_arena);
  8775. defer (gb_temp_arena_memory_end(tmp));
  8776. if (vd->values.count == 0) { // declared and zero-initialized
  8777. for_array(i, vd->names) {
  8778. Ast *name = vd->names[i];
  8779. if (!is_blank_ident(name)) {
  8780. ir_add_local_for_identifier(proc, name, true);
  8781. }
  8782. }
  8783. } else { // Tuple(s)
  8784. auto lvals = array_make<irAddr>(m->tmp_allocator, 0, vd->names.count);
  8785. auto inits = array_make<irValue *>(m->tmp_allocator, 0, vd->names.count);
  8786. for_array(i, vd->names) {
  8787. Ast *name = vd->names[i];
  8788. irAddr lval = ir_addr(nullptr);
  8789. if (!is_blank_ident(name)) {
  8790. // NOTE(bill, 2020-06-10): This must be zero initialize because of weird LLVM optimization behaviours
  8791. ir_add_local_for_identifier(proc, name, true);
  8792. lval = ir_build_addr(proc, name);
  8793. }
  8794. array_add(&lvals, lval);
  8795. }
  8796. for_array(i, vd->values) {
  8797. irValue *init = ir_build_expr(proc, vd->values[i]);
  8798. Type *t = ir_type(init);
  8799. if (t->kind == Type_Tuple) {
  8800. for_array(i, t->Tuple.variables) {
  8801. Entity *e = t->Tuple.variables[i];
  8802. irValue *v = ir_emit_struct_ev(proc, init, cast(i32)i);
  8803. array_add(&inits, v);
  8804. }
  8805. } else {
  8806. array_add(&inits, init);
  8807. }
  8808. }
  8809. for_array(i, inits) {
  8810. ir_addr_store(proc, lvals[i], inits[i]);
  8811. }
  8812. }
  8813. }
  8814. case_end;
  8815. case_ast_node(as, AssignStmt, node);
  8816. ir_emit_comment(proc, str_lit("AssignStmt"));
  8817. irModule *m = proc->module;
  8818. gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&m->tmp_arena);
  8819. switch (as->op.kind) {
  8820. case Token_Eq: {
  8821. auto lvals = array_make<irAddr>(m->tmp_allocator, 0, as->lhs.count);
  8822. for_array(i, as->lhs) {
  8823. Ast *lhs = as->lhs[i];
  8824. irAddr lval = {};
  8825. if (!is_blank_ident(lhs)) {
  8826. lval = ir_build_addr(proc, lhs);
  8827. }
  8828. array_add(&lvals, lval);
  8829. }
  8830. if (as->lhs.count == as->rhs.count) {
  8831. if (as->lhs.count == 1) {
  8832. Ast *rhs = as->rhs[0];
  8833. irValue *init = ir_build_expr(proc, rhs);
  8834. ir_addr_store(proc, lvals[0], init);
  8835. } else {
  8836. auto inits = array_make<irValue *>(m->tmp_allocator, 0, lvals.count);
  8837. for_array(i, as->rhs) {
  8838. irValue *init = ir_build_expr(proc, as->rhs[i]);
  8839. array_add(&inits, init);
  8840. }
  8841. for_array(i, inits) {
  8842. auto lval = lvals[i];
  8843. ir_addr_store(proc, lval, inits[i]);
  8844. }
  8845. }
  8846. } else {
  8847. auto inits = array_make<irValue *>(m->tmp_allocator, 0, lvals.count);
  8848. for_array(i, as->rhs) {
  8849. irValue *init = ir_build_expr(proc, as->rhs[i]);
  8850. Type *t = ir_type(init);
  8851. // TODO(bill): refactor for code reuse as this is repeated a bit
  8852. if (t->kind == Type_Tuple) {
  8853. for_array(i, t->Tuple.variables) {
  8854. Entity *e = t->Tuple.variables[i];
  8855. irValue *v = ir_emit_struct_ev(proc, init, cast(i32)i);
  8856. array_add(&inits, v);
  8857. }
  8858. } else {
  8859. array_add(&inits, init);
  8860. }
  8861. }
  8862. for_array(i, inits) {
  8863. ir_addr_store(proc, lvals[i], inits[i]);
  8864. }
  8865. }
  8866. break;
  8867. }
  8868. default: {
  8869. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  8870. // +=, -=, etc
  8871. i32 op = cast(i32)as->op.kind;
  8872. op += Token_Add - Token_AddEq; // Convert += to +
  8873. if (op == Token_CmpAnd || op == Token_CmpOr) {
  8874. Type *type = as->lhs[0]->tav.type;
  8875. irValue *new_value = ir_emit_logical_binary_expr(proc, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  8876. irAddr lhs = ir_build_addr(proc, as->lhs[0]);
  8877. ir_addr_store(proc, lhs, new_value);
  8878. } else {
  8879. irAddr lhs = ir_build_addr(proc, as->lhs[0]);
  8880. irValue *value = ir_build_expr(proc, as->rhs[0]);
  8881. ir_build_assign_op(proc, lhs, value, cast(TokenKind)op);
  8882. }
  8883. return;
  8884. }
  8885. }
  8886. case_end;
  8887. case_ast_node(es, ExprStmt, node);
  8888. // NOTE(bill): No need to use return value
  8889. ir_build_expr(proc, es->expr);
  8890. case_end;
  8891. case_ast_node(bs, BlockStmt, node);
  8892. if (bs->label != nullptr) {
  8893. irBlock *done = ir_new_block(proc, node, "block.done");
  8894. irTargetList *tl = ir_push_target_list(proc, bs->label, done, nullptr, nullptr);
  8895. tl->is_block = true;
  8896. ir_open_scope(proc);
  8897. ir_build_stmt_list(proc, bs->stmts);
  8898. ir_close_scope(proc, irDeferExit_Default, nullptr);
  8899. ir_emit_jump(proc, done);
  8900. ir_start_block(proc, done);
  8901. } else {
  8902. ir_open_scope(proc);
  8903. ir_build_stmt_list(proc, bs->stmts);
  8904. ir_close_scope(proc, irDeferExit_Default, nullptr);
  8905. }
  8906. case_end;
  8907. case_ast_node(ds, DeferStmt, node);
  8908. ir_emit_comment(proc, str_lit("DeferStmt"));
  8909. isize scope_index = proc->scope_index;
  8910. // TODO(bill): What was the original rationale behind this line?
  8911. // if (ds->stmt->kind == Ast_BlockStmt) scope_index--;
  8912. ir_add_defer_node(proc, scope_index, ds->stmt);
  8913. case_end;
  8914. case_ast_node(rs, ReturnStmt, node);
  8915. ir_emit_comment(proc, str_lit("ReturnStmt"));
  8916. irValue *v = nullptr;
  8917. TypeTuple *tuple = &proc->type->Proc.results->Tuple;
  8918. isize return_count = proc->type->Proc.result_count;
  8919. isize res_count = rs->results.count;
  8920. if (return_count == 0) {
  8921. // No return values
  8922. } else if (return_count == 1) {
  8923. Entity *e = tuple->variables[0];
  8924. if (res_count == 0) {
  8925. irValue **found = map_get(&proc->module->values, hash_entity(e));
  8926. GB_ASSERT(found);
  8927. v = ir_emit_load(proc, *found);
  8928. } else {
  8929. v = ir_build_expr(proc, rs->results[0]);
  8930. v = ir_emit_conv(proc, v, e->type);
  8931. }
  8932. if (proc->type->Proc.has_named_results) {
  8933. // NOTE(bill): store the named values before returning
  8934. if (e->token.string != "") {
  8935. irValue **found = map_get(&proc->module->values, hash_entity(e));
  8936. GB_ASSERT(found != nullptr);
  8937. ir_emit_store(proc, *found, v);
  8938. }
  8939. }
  8940. } else {
  8941. gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&proc->module->tmp_arena);
  8942. defer (gb_temp_arena_memory_end(tmp));
  8943. auto results = array_make<irValue *>(proc->module->tmp_allocator, 0, return_count);
  8944. if (res_count != 0) {
  8945. for (isize res_index = 0; res_index < res_count; res_index++) {
  8946. irValue *res = ir_build_expr(proc, rs->results[res_index]);
  8947. Type *t = ir_type(res);
  8948. if (t->kind == Type_Tuple) {
  8949. for_array(i, t->Tuple.variables) {
  8950. Entity *e = t->Tuple.variables[i];
  8951. irValue *v = ir_emit_struct_ev(proc, res, cast(i32)i);
  8952. array_add(&results, v);
  8953. }
  8954. } else {
  8955. array_add(&results, res);
  8956. }
  8957. }
  8958. } else {
  8959. for (isize res_index = 0; res_index < return_count; res_index++) {
  8960. Entity *e = tuple->variables[res_index];
  8961. irValue **found = map_get(&proc->module->values, hash_entity(e));
  8962. GB_ASSERT(found);
  8963. irValue *res = ir_emit_load(proc, *found);
  8964. array_add(&results, res);
  8965. }
  8966. }
  8967. GB_ASSERT(results.count == return_count);
  8968. if (proc->type->Proc.has_named_results) {
  8969. // NOTE(bill): store the named values before returning
  8970. for_array(i, tuple->variables) {
  8971. Entity *e = tuple->variables[i];
  8972. if (e->kind != Entity_Variable) {
  8973. continue;
  8974. }
  8975. if (e->token.string == "") {
  8976. continue;
  8977. }
  8978. irValue **found = map_get(&proc->module->values, hash_entity(e));
  8979. GB_ASSERT(found != nullptr);
  8980. ir_emit_store(proc, *found, ir_emit_conv(proc, results[i], e->type));
  8981. }
  8982. }
  8983. Type *ret_type = proc->type->Proc.results;
  8984. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  8985. v = ir_add_local_generated(proc, ret_type, false);
  8986. for_array(i, results) {
  8987. Entity *e = tuple->variables[i];
  8988. irValue *res = ir_emit_conv(proc, results[i], e->type);
  8989. irValue *field = ir_emit_struct_ep(proc, v, cast(i32)i);
  8990. ir_emit_store(proc, field, res);
  8991. }
  8992. v = ir_emit_load(proc, v);
  8993. }
  8994. ir_emit_return(proc, v);
  8995. case_end;
  8996. case_ast_node(is, IfStmt, node);
  8997. ir_emit_comment(proc, str_lit("IfStmt"));
  8998. ir_open_scope(proc); // Scope #1
  8999. if (is->init != nullptr) {
  9000. // TODO(bill): Should this have a separate block to begin with?
  9001. #if 1
  9002. irBlock *init = ir_new_block(proc, node, "if.init");
  9003. ir_emit_jump(proc, init);
  9004. ir_start_block(proc, init);
  9005. #endif
  9006. ir_build_stmt(proc, is->init);
  9007. }
  9008. irBlock *then = ir_new_block(proc, node, "if.then");
  9009. irBlock *done = ir_new_block(proc, node, "if.done");
  9010. irBlock *else_ = done;
  9011. if (is->else_stmt != nullptr) {
  9012. else_ = ir_new_block(proc, is->else_stmt, "if.else");
  9013. }
  9014. ir_build_cond(proc, is->cond, then, else_);
  9015. ir_start_block(proc, then);
  9016. if (is->label != nullptr) {
  9017. irTargetList *tl = ir_push_target_list(proc, is->label, done, nullptr, nullptr);
  9018. tl->is_block = true;
  9019. }
  9020. // ir_open_scope(proc);
  9021. ir_build_stmt(proc, is->body);
  9022. // ir_close_scope(proc, irDeferExit_Default, nullptr);
  9023. ir_emit_jump(proc, done);
  9024. if (is->else_stmt != nullptr) {
  9025. ir_start_block(proc, else_);
  9026. ir_open_scope(proc);
  9027. ir_build_stmt(proc, is->else_stmt);
  9028. ir_close_scope(proc, irDeferExit_Default, nullptr);
  9029. ir_emit_jump(proc, done);
  9030. }
  9031. ir_start_block(proc, done);
  9032. ir_close_scope(proc, irDeferExit_Default, nullptr);
  9033. case_end;
  9034. case_ast_node(fs, ForStmt, node);
  9035. ir_emit_comment(proc, str_lit("ForStmt"));
  9036. ir_open_scope(proc); // Open Scope here
  9037. if (fs->init != nullptr) {
  9038. #if 1
  9039. irBlock *init = ir_new_block(proc, node, "for.init");
  9040. ir_emit_jump(proc, init);
  9041. ir_start_block(proc, init);
  9042. #endif
  9043. ir_build_stmt(proc, fs->init);
  9044. }
  9045. irBlock *body = ir_new_block(proc, node, "for.body");
  9046. irBlock *done = ir_new_block(proc, node, "for.done"); // NOTE(bill): Append later
  9047. irBlock *loop = body;
  9048. if (fs->cond != nullptr) {
  9049. loop = ir_new_block(proc, node, "for.loop");
  9050. }
  9051. irBlock *post = loop;
  9052. if (fs->post != nullptr) {
  9053. post = ir_new_block(proc, node, "for.post");
  9054. }
  9055. ir_emit_jump(proc, loop);
  9056. ir_start_block(proc, loop);
  9057. if (loop != body) {
  9058. ir_build_cond(proc, fs->cond, body, done);
  9059. ir_start_block(proc, body);
  9060. }
  9061. ir_push_target_list(proc, fs->label, done, post, nullptr);
  9062. ir_build_stmt(proc, fs->body);
  9063. ir_close_scope(proc, irDeferExit_Default, nullptr);
  9064. ir_pop_target_list(proc);
  9065. ir_emit_jump(proc, post);
  9066. if (fs->post != nullptr) {
  9067. ir_start_block(proc, post);
  9068. ir_build_stmt(proc, fs->post);
  9069. ir_emit_jump(proc, loop);
  9070. }
  9071. ir_start_block(proc, done);
  9072. case_end;
  9073. case_ast_node(rs, RangeStmt, node);
  9074. ir_emit_comment(proc, str_lit("RangeStmt"));
  9075. ir_open_scope(proc); // Open scope here
  9076. Type *val0_type = nullptr;
  9077. Type *val1_type = nullptr;
  9078. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  9079. val0_type = type_of_expr(rs->val0);
  9080. }
  9081. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  9082. val1_type = type_of_expr(rs->val1);
  9083. }
  9084. if (val0_type != nullptr) {
  9085. ir_add_local_for_identifier(proc, rs->val0, true);
  9086. }
  9087. if (val1_type != nullptr) {
  9088. ir_add_local_for_identifier(proc, rs->val1, true);
  9089. }
  9090. irValue *val = nullptr;
  9091. irValue *key = nullptr;
  9092. irBlock *loop = nullptr;
  9093. irBlock *done = nullptr;
  9094. Ast *expr = unparen_expr(rs->expr);
  9095. bool is_map = false;
  9096. TypeAndValue tav = type_and_value_of_expr(expr);
  9097. if (is_ast_range(expr)) {
  9098. ir_build_range_interval(proc, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  9099. } else if (tav.mode == Addressing_Type) {
  9100. ir_build_range_enum(proc, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  9101. } else {
  9102. Type *expr_type = type_of_expr(expr);
  9103. Type *et = base_type(type_deref(expr_type));
  9104. switch (et->kind) {
  9105. case Type_Map: {
  9106. is_map = true;
  9107. gbAllocator a = ir_allocator();
  9108. irAddr addr = ir_build_addr(proc, expr);
  9109. bool allow_reference = true;
  9110. irValue *map = ir_addr_get_ptr(proc, addr, allow_reference);
  9111. if (is_type_pointer(ir_addr_type(addr))) {
  9112. map = ir_addr_load(proc, addr);
  9113. }
  9114. irValue *entries_ptr = ir_map_entries_ptr(proc, map);
  9115. irValue *count_ptr = ir_emit_struct_ep(proc, entries_ptr, 1);
  9116. ir_build_range_indexed(proc, map, val1_type, count_ptr, &val, &key, &loop, &done);
  9117. break;
  9118. }
  9119. case Type_Array: {
  9120. irValue *count_ptr = nullptr;
  9121. irValue *array = ir_build_addr_ptr(proc, expr);
  9122. if (is_type_pointer(type_deref(ir_type(array)))) {
  9123. array = ir_emit_load(proc, array);
  9124. }
  9125. count_ptr = ir_add_local_generated(proc, t_int, false);
  9126. ir_emit_store(proc, count_ptr, ir_const_int(et->Array.count));
  9127. ir_build_range_indexed(proc, array, val0_type, count_ptr, &val, &key, &loop, &done);
  9128. break;
  9129. }
  9130. case Type_EnumeratedArray: {
  9131. irValue *count_ptr = nullptr;
  9132. irValue *array = ir_build_addr_ptr(proc, expr);
  9133. if (is_type_pointer(type_deref(ir_type(array)))) {
  9134. array = ir_emit_load(proc, array);
  9135. }
  9136. count_ptr = ir_add_local_generated(proc, t_int, false);
  9137. ir_emit_store(proc, count_ptr, ir_const_int(et->EnumeratedArray.count));
  9138. ir_build_range_indexed(proc, array, val0_type, count_ptr, &val, &key, &loop, &done);
  9139. break;
  9140. }
  9141. case Type_DynamicArray: {
  9142. irValue *count_ptr = nullptr;
  9143. irValue *array = ir_build_addr_ptr(proc, expr);
  9144. if (is_type_pointer(type_deref(ir_type(array)))) {
  9145. array = ir_emit_load(proc, array);
  9146. }
  9147. count_ptr = ir_emit_struct_ep(proc, array, 1);
  9148. ir_build_range_indexed(proc, array, val0_type, count_ptr, &val, &key, &loop, &done);
  9149. break;
  9150. }
  9151. case Type_Slice: {
  9152. irValue *count_ptr = nullptr;
  9153. irValue *slice = ir_build_expr(proc, expr);
  9154. if (is_type_pointer(ir_type(slice))) {
  9155. count_ptr = ir_emit_struct_ep(proc, slice, 1);
  9156. slice = ir_emit_load(proc, slice);
  9157. } else {
  9158. count_ptr = ir_add_local_generated(proc, t_int, false);
  9159. ir_emit_store(proc, count_ptr, ir_slice_len(proc, slice));
  9160. }
  9161. ir_build_range_indexed(proc, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  9162. break;
  9163. }
  9164. case Type_Basic: {
  9165. irValue *string = ir_build_expr(proc, expr);
  9166. if (is_type_pointer(ir_type(string))) {
  9167. string = ir_emit_load(proc, string);
  9168. }
  9169. if (is_type_untyped(expr_type)) {
  9170. irValue *s = ir_add_local_generated(proc, default_type(ir_type(string)), false);
  9171. ir_emit_store(proc, s, string);
  9172. string = ir_emit_load(proc, s);
  9173. }
  9174. Type *t = base_type(ir_type(string));
  9175. GB_ASSERT(!is_type_cstring(t));
  9176. ir_build_range_string(proc, string, val0_type, &val, &key, &loop, &done);
  9177. break;
  9178. }
  9179. case Type_Tuple:
  9180. ir_build_range_tuple(proc, expr, val0_type, val1_type, &val, &key, &loop, &done);
  9181. break;
  9182. default:
  9183. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  9184. break;
  9185. }
  9186. }
  9187. if (is_map) {
  9188. if (val0_type) ir_store_range_stmt_val(proc, rs->val0, key);
  9189. if (val1_type) ir_store_range_stmt_val(proc, rs->val1, val);
  9190. } else {
  9191. if (val0_type) ir_store_range_stmt_val(proc, rs->val0, val);
  9192. if (val1_type) ir_store_range_stmt_val(proc, rs->val1, key);
  9193. }
  9194. ir_push_target_list(proc, rs->label, done, loop, nullptr);
  9195. ir_build_stmt(proc, rs->body);
  9196. ir_close_scope(proc, irDeferExit_Default, nullptr);
  9197. ir_pop_target_list(proc);
  9198. ir_emit_jump(proc, loop);
  9199. ir_start_block(proc, done);
  9200. case_end;
  9201. case_ast_node(rs, InlineRangeStmt, node);
  9202. ir_emit_comment(proc, str_lit("InlineRangeStmt"));
  9203. ir_open_scope(proc); // Open scope here
  9204. irBlock *done = ir_new_block(proc, node, "inline.for.done");
  9205. Type *val0_type = nullptr;
  9206. Type *val1_type = nullptr;
  9207. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  9208. val0_type = type_of_expr(rs->val0);
  9209. }
  9210. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  9211. val1_type = type_of_expr(rs->val1);
  9212. }
  9213. if (val0_type != nullptr) {
  9214. ir_add_local_for_identifier(proc, rs->val0, true);
  9215. }
  9216. if (val1_type != nullptr) {
  9217. ir_add_local_for_identifier(proc, rs->val1, true);
  9218. }
  9219. irValue *val = nullptr;
  9220. irValue *key = nullptr;
  9221. Ast *expr = unparen_expr(rs->expr);
  9222. TypeAndValue tav = type_and_value_of_expr(expr);
  9223. if (is_ast_range(expr)) {
  9224. irAddr val0_addr = {};
  9225. irAddr val1_addr = {};
  9226. if (val0_type) val0_addr = ir_build_addr(proc, rs->val0);
  9227. if (val1_type) val1_addr = ir_build_addr(proc, rs->val1);
  9228. TokenKind op = expr->BinaryExpr.op.kind;
  9229. Ast *start_expr = expr->BinaryExpr.left;
  9230. Ast *end_expr = expr->BinaryExpr.right;
  9231. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  9232. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  9233. ExactValue start = start_expr->tav.value;
  9234. ExactValue end = end_expr->tav.value;
  9235. if (op == Token_Ellipsis) { // .. [start, end]
  9236. ExactValue index = exact_value_i64(0);
  9237. for (ExactValue val = start;
  9238. compare_exact_values(Token_LtEq, val, end);
  9239. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  9240. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  9241. ir_emit_jump(proc, body);
  9242. if (val0_type) ir_addr_store(proc, val0_addr, ir_value_constant(val0_type, val));
  9243. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, index));
  9244. ir_start_block(proc, body);
  9245. ir_build_stmt(proc, rs->body);
  9246. }
  9247. } else if (op == Token_RangeHalf) { // ..< [start, end)
  9248. ExactValue index = exact_value_i64(0);
  9249. for (ExactValue val = start;
  9250. compare_exact_values(Token_Lt, val, end);
  9251. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  9252. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  9253. ir_emit_jump(proc, body);
  9254. ir_start_block(proc, body);
  9255. if (val0_type) ir_addr_store(proc, val0_addr, ir_value_constant(val0_type, val));
  9256. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, index));
  9257. ir_build_stmt(proc, rs->body);
  9258. }
  9259. }
  9260. } else if (tav.mode == Addressing_Type) {
  9261. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  9262. Type *et = type_deref(tav.type);
  9263. Type *bet = base_type(et);
  9264. irAddr val0_addr = {};
  9265. irAddr val1_addr = {};
  9266. if (val0_type) val0_addr = ir_build_addr(proc, rs->val0);
  9267. if (val1_type) val1_addr = ir_build_addr(proc, rs->val1);
  9268. for_array(i, bet->Enum.fields) {
  9269. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  9270. ir_emit_jump(proc, body);
  9271. ir_start_block(proc, body);
  9272. Entity *field = bet->Enum.fields[i];
  9273. GB_ASSERT(field->kind == Entity_Constant);
  9274. if (val0_type) ir_addr_store(proc, val0_addr, ir_value_constant(val0_type, field->Constant.value));
  9275. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, exact_value_i64(i)));
  9276. ir_build_stmt(proc, rs->body);
  9277. }
  9278. } else {
  9279. irAddr val0_addr = {};
  9280. irAddr val1_addr = {};
  9281. if (val0_type) val0_addr = ir_build_addr(proc, rs->val0);
  9282. if (val1_type) val1_addr = ir_build_addr(proc, rs->val1);
  9283. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  9284. Type *t = base_type(expr->tav.type);
  9285. switch (t->kind) {
  9286. case Type_Basic:
  9287. GB_ASSERT(is_type_string(t));
  9288. {
  9289. ExactValue value = expr->tav.value;
  9290. GB_ASSERT(value.kind == ExactValue_String);
  9291. String str = value.value_string;
  9292. Rune codepoint = 0;
  9293. isize offset = 0;
  9294. do {
  9295. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  9296. ir_emit_jump(proc, body);
  9297. ir_start_block(proc, body);
  9298. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  9299. if (val0_type) ir_addr_store(proc, val0_addr, ir_value_constant(val0_type, exact_value_i64(codepoint)));
  9300. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, exact_value_i64(offset)));
  9301. ir_build_stmt(proc, rs->body);
  9302. offset += width;
  9303. } while (offset < str.len);
  9304. }
  9305. break;
  9306. case Type_Array:
  9307. if (t->Array.count > 0) {
  9308. irValue *val = ir_build_expr(proc, expr);
  9309. irValue *val_addr = ir_address_from_load_or_generate_local(proc, val);
  9310. for (i64 i = 0; i < t->Array.count; i++) {
  9311. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  9312. ir_emit_jump(proc, body);
  9313. ir_start_block(proc, body);
  9314. if (val0_type) {
  9315. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  9316. irValue *elem = ir_emit_array_epi(proc, val_addr, cast(i32)i);
  9317. ir_addr_store(proc, val0_addr, ir_emit_load(proc, elem));
  9318. }
  9319. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, exact_value_i64(i)));
  9320. ir_build_stmt(proc, rs->body);
  9321. }
  9322. }
  9323. break;
  9324. case Type_EnumeratedArray:
  9325. if (t->EnumeratedArray.count > 0) {
  9326. irValue *val = ir_build_expr(proc, expr);
  9327. irValue *val_addr = ir_address_from_load_or_generate_local(proc, val);
  9328. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  9329. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  9330. ir_emit_jump(proc, body);
  9331. ir_start_block(proc, body);
  9332. if (val0_type) {
  9333. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  9334. irValue *elem = ir_emit_array_epi(proc, val_addr, cast(i32)i);
  9335. ir_addr_store(proc, val0_addr, ir_emit_load(proc, elem));
  9336. }
  9337. if (val1_type) {
  9338. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  9339. ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, idx));
  9340. }
  9341. ir_build_stmt(proc, rs->body);
  9342. }
  9343. }
  9344. break;
  9345. default:
  9346. GB_PANIC("Invalid inline for type");
  9347. break;
  9348. }
  9349. }
  9350. ir_emit_jump(proc, done);
  9351. ir_start_block(proc, done);
  9352. ir_close_scope(proc, irDeferExit_Default, nullptr);
  9353. case_end;
  9354. case_ast_node(ss, SwitchStmt, node);
  9355. ir_emit_comment(proc, str_lit("SwitchStmt"));
  9356. if (ss->init != nullptr) {
  9357. ir_build_stmt(proc, ss->init);
  9358. }
  9359. irValue *tag = v_true;
  9360. if (ss->tag != nullptr) {
  9361. tag = ir_build_expr(proc, ss->tag);
  9362. }
  9363. irBlock *done = ir_new_block(proc, node, "switch.done"); // NOTE(bill): Append later
  9364. ast_node(body, BlockStmt, ss->body);
  9365. Slice<Ast *> default_stmts = {};
  9366. irBlock *default_fall = nullptr;
  9367. irBlock *default_block = nullptr;
  9368. irBlock *fall = nullptr;
  9369. bool append_fall = false;
  9370. isize case_count = body->stmts.count;
  9371. for_array(i, body->stmts) {
  9372. Ast *clause = body->stmts[i];
  9373. irBlock *body = fall;
  9374. ast_node(cc, CaseClause, clause);
  9375. if (body == nullptr) {
  9376. if (cc->list.count == 0) {
  9377. body = ir_new_block(proc, clause, "switch.dflt.body");
  9378. } else {
  9379. body = ir_new_block(proc, clause, "switch.case.body");
  9380. }
  9381. }
  9382. if (append_fall && body == fall) {
  9383. append_fall = false;
  9384. }
  9385. fall = done;
  9386. if (i+1 < case_count) {
  9387. append_fall = true;
  9388. fall = ir_new_block(proc, clause, "switch.fall.body");
  9389. }
  9390. if (cc->list.count == 0) {
  9391. // default case
  9392. default_stmts = cc->stmts;
  9393. default_fall = fall;
  9394. default_block = body;
  9395. continue;
  9396. }
  9397. irBlock *next_cond = nullptr;
  9398. for_array(j, cc->list) {
  9399. Ast *expr = unparen_expr(cc->list[j]);
  9400. next_cond = ir_new_block(proc, clause, "switch.case.next");
  9401. irValue *cond = v_false;
  9402. if (is_ast_range(expr)) {
  9403. ast_node(ie, BinaryExpr, expr);
  9404. TokenKind op = Token_Invalid;
  9405. switch (ie->op.kind) {
  9406. case Token_Ellipsis: op = Token_LtEq; break;
  9407. case Token_RangeHalf: op = Token_Lt; break;
  9408. default: GB_PANIC("Invalid interval operator"); break;
  9409. }
  9410. irValue *lhs = ir_build_expr(proc, ie->left);
  9411. irValue *rhs = ir_build_expr(proc, ie->right);
  9412. // TODO(bill): do short circuit here
  9413. irValue *cond_lhs = ir_emit_comp(proc, Token_LtEq, lhs, tag);
  9414. irValue *cond_rhs = ir_emit_comp(proc, op, tag, rhs);
  9415. cond = ir_emit_arith(proc, Token_And, cond_lhs, cond_rhs, t_bool);
  9416. } else {
  9417. if (expr->tav.mode == Addressing_Type) {
  9418. GB_ASSERT(is_type_typeid(ir_type(tag)));
  9419. irValue *e = ir_typeid(proc->module, expr->tav.type);
  9420. e = ir_emit_conv(proc, e, ir_type(tag));
  9421. cond = ir_emit_comp(proc, Token_CmpEq, tag, e);
  9422. } else {
  9423. cond = ir_emit_comp(proc, Token_CmpEq, tag, ir_build_expr(proc, expr));
  9424. }
  9425. }
  9426. ir_emit_if(proc, cond, body, next_cond);
  9427. ir_start_block(proc, next_cond);
  9428. }
  9429. ir_start_block(proc, body);
  9430. ir_push_target_list(proc, ss->label, done, nullptr, fall);
  9431. ir_open_scope(proc);
  9432. ir_build_stmt_list(proc, cc->stmts);
  9433. ir_close_scope(proc, irDeferExit_Default, body);
  9434. ir_pop_target_list(proc);
  9435. ir_emit_jump(proc, done);
  9436. proc->curr_block = next_cond;
  9437. // ir_start_block(proc, next_cond);
  9438. }
  9439. if (default_block != nullptr) {
  9440. ir_emit_jump(proc, default_block);
  9441. ir_start_block(proc, default_block);
  9442. ir_push_target_list(proc, ss->label, done, nullptr, default_fall);
  9443. ir_open_scope(proc);
  9444. ir_build_stmt_list(proc, default_stmts);
  9445. ir_close_scope(proc, irDeferExit_Default, default_block);
  9446. ir_pop_target_list(proc);
  9447. }
  9448. ir_emit_jump(proc, done);
  9449. ir_start_block(proc, done);
  9450. case_end;
  9451. case_ast_node(ss, TypeSwitchStmt, node);
  9452. ir_emit_comment(proc, str_lit("TypeSwitchStmt"));
  9453. gbAllocator allocator = ir_allocator();
  9454. ast_node(as, AssignStmt, ss->tag);
  9455. GB_ASSERT(as->lhs.count == 1);
  9456. GB_ASSERT(as->rhs.count == 1);
  9457. irValue *parent = ir_build_expr(proc, as->rhs[0]);
  9458. Type *parent_type = ir_type(parent);
  9459. bool is_parent_ptr = is_type_pointer(ir_type(parent));
  9460. TypeSwitchKind switch_kind = check_valid_type_switch_type(ir_type(parent));
  9461. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  9462. irValue *parent_value = parent;
  9463. irValue *parent_ptr = parent;
  9464. if (!is_parent_ptr) {
  9465. parent_ptr = ir_address_from_load_or_generate_local(proc, parent_ptr);
  9466. }
  9467. irValue *tag_index = nullptr;
  9468. irValue *union_data = nullptr;
  9469. if (switch_kind == TypeSwitch_Union) {
  9470. ir_emit_comment(proc, str_lit("get union's tag"));
  9471. tag_index = ir_emit_load(proc, ir_emit_union_tag_ptr(proc, parent_ptr));
  9472. union_data = ir_emit_conv(proc, parent_ptr, t_rawptr);
  9473. }
  9474. irBlock *start_block = ir_new_block(proc, node, "typeswitch.case.first");
  9475. ir_emit_jump(proc, start_block);
  9476. ir_start_block(proc, start_block);
  9477. // NOTE(bill): Append this later
  9478. irBlock *done = ir_new_block(proc, node, "typeswitch.done");
  9479. Ast *default_ = nullptr;
  9480. ast_node(body, BlockStmt, ss->body);
  9481. gb_local_persist i32 weird_count = 0;
  9482. for_array(i, body->stmts) {
  9483. Ast *clause = body->stmts[i];
  9484. ast_node(cc, CaseClause, clause);
  9485. if (cc->list.count == 0) {
  9486. default_ = clause;
  9487. continue;
  9488. }
  9489. irBlock *body = ir_new_block(proc, clause, "typeswitch.body");
  9490. irBlock *next = nullptr;
  9491. Type *case_type = nullptr;
  9492. for_array(type_index, cc->list) {
  9493. next = ir_new_block(proc, nullptr, "typeswitch.next");
  9494. case_type = type_of_expr(cc->list[type_index]);
  9495. irValue *cond = nullptr;
  9496. if (switch_kind == TypeSwitch_Union) {
  9497. Type *ut = base_type(type_deref(parent_type));
  9498. irValue *variant_tag = ir_const_union_tag(ut, case_type);
  9499. cond = ir_emit_comp(proc, Token_CmpEq, tag_index, variant_tag);
  9500. } else if (switch_kind == TypeSwitch_Any) {
  9501. irValue *any_typeid = ir_emit_load(proc, ir_emit_struct_ep(proc, parent_ptr, 1));
  9502. irValue *case_typeid = ir_typeid(proc->module, case_type);
  9503. cond = ir_emit_comp(proc, Token_CmpEq, any_typeid, case_typeid);
  9504. }
  9505. GB_ASSERT(cond != nullptr);
  9506. ir_emit_if(proc, cond, body, next);
  9507. ir_start_block(proc, next);
  9508. }
  9509. Entity *case_entity = implicit_entity_of_node(clause);
  9510. irValue *value = parent_value;
  9511. ir_start_block(proc, body);
  9512. // bool any_or_not_ptr = is_type_any(type_deref(parent_type)) || !is_parent_ptr;
  9513. if (cc->list.count == 1) {
  9514. irValue *data = nullptr;
  9515. if (switch_kind == TypeSwitch_Union) {
  9516. data = union_data;
  9517. } else if (switch_kind == TypeSwitch_Any) {
  9518. irValue *any_data = ir_emit_load(proc, ir_emit_struct_ep(proc, parent_ptr, 0));
  9519. data = any_data;
  9520. }
  9521. Type *ct = case_entity->type;
  9522. Type *ct_ptr = alloc_type_pointer(ct);
  9523. value = ir_emit_conv(proc, data, ct_ptr);
  9524. if (case_entity->flags & EntityFlag_Value) {
  9525. // by value
  9526. value = ir_emit_load(proc, value);
  9527. } else {
  9528. // by reference
  9529. }
  9530. }
  9531. ir_store_type_case_implicit(proc, clause, value);
  9532. ir_type_case_body(proc, ss->label, clause, body, done);
  9533. ir_start_block(proc, next);
  9534. }
  9535. if (default_ != nullptr) {
  9536. ir_store_type_case_implicit(proc, default_, parent_value);
  9537. ir_type_case_body(proc, ss->label, default_, proc->curr_block, done);
  9538. } else {
  9539. ir_emit_jump(proc, done);
  9540. }
  9541. ir_start_block(proc, done);
  9542. case_end;
  9543. case_ast_node(bs, BranchStmt, node);
  9544. irBlock *block = nullptr;
  9545. if (bs->label != nullptr) {
  9546. irBranchBlocks bb = ir_lookup_branch_blocks(proc, bs->label);
  9547. switch (bs->token.kind) {
  9548. case Token_break: block = bb.break_; break;
  9549. case Token_continue: block = bb.continue_; break;
  9550. case Token_fallthrough:
  9551. GB_PANIC("fallthrough cannot have a label");
  9552. break;
  9553. }
  9554. } else {
  9555. for (irTargetList *t = proc->target_list; t != nullptr && block == nullptr; t = t->prev) {
  9556. if (t->is_block) {
  9557. continue;
  9558. }
  9559. switch (bs->token.kind) {
  9560. case Token_break: block = t->break_; break;
  9561. case Token_continue: block = t->continue_; break;
  9562. case Token_fallthrough: block = t->fallthrough_; break;
  9563. }
  9564. }
  9565. }
  9566. if (block != nullptr) {
  9567. ir_emit_defer_stmts(proc, irDeferExit_Branch, block);
  9568. }
  9569. switch (bs->token.kind) {
  9570. case Token_break: ir_emit_comment(proc, str_lit("break")); break;
  9571. case Token_continue: ir_emit_comment(proc, str_lit("continue")); break;
  9572. case Token_fallthrough: ir_emit_comment(proc, str_lit("fallthrough")); break;
  9573. }
  9574. ir_emit_jump(proc, block);
  9575. ir_emit_unreachable(proc);
  9576. case_end;
  9577. }
  9578. }
  9579. ////////////////////////////////////////////////////////////////
  9580. //
  9581. // @Procedure
  9582. //
  9583. ////////////////////////////////////////////////////////////////
  9584. void ir_number_proc_registers(irProcedure *proc) {
  9585. // i32 reg_index = proc->parameter_count;
  9586. i32 reg_index = 0;
  9587. for_array(i, proc->blocks) {
  9588. irBlock *b = proc->blocks[i];
  9589. b->index = cast(i32)i;
  9590. for_array(j, b->instrs) {
  9591. irValue *value = b->instrs[j];
  9592. GB_ASSERT_MSG(value->kind == irValue_Instr, "%.*s", LIT(proc->name));
  9593. irInstr *instr = &value->Instr;
  9594. if (ir_instr_type(instr) == nullptr) { // NOTE(bill): Ignore non-returning instructions
  9595. value->index = -1;
  9596. continue;
  9597. }
  9598. value->index = reg_index;
  9599. value->index_set = true;
  9600. reg_index++;
  9601. }
  9602. }
  9603. }
  9604. void ir_begin_procedure_body(irProcedure *proc) {
  9605. gbAllocator a = ir_allocator();
  9606. array_add(&proc->module->procs, proc);
  9607. array_init(&proc->blocks, heap_allocator());
  9608. array_init(&proc->defer_stmts, heap_allocator());
  9609. array_init(&proc->children, heap_allocator());
  9610. array_init(&proc->branch_blocks, heap_allocator());
  9611. array_init(&proc->context_stack, heap_allocator());
  9612. DeclInfo *decl = decl_info_of_entity(proc->entity);
  9613. if (decl != nullptr) {
  9614. for_array(i, decl->labels) {
  9615. BlockLabel bl = decl->labels[i];
  9616. irBranchBlocks bb = {bl.label, nullptr, nullptr};
  9617. array_add(&proc->branch_blocks, bb);
  9618. }
  9619. }
  9620. // NOTE(lachsinc): This is somewhat of a fallback/catch-all; We use the procedure's identifer as a debug location..
  9621. // Additional debug locations should be pushed for the procedures statements/expressions themselves.
  9622. if (proc->module->generate_debug_info && proc->entity && proc->entity->identifier) { // TODO(lachsinc): Better way to determine if these procs are main/runtime_startup.
  9623. // TODO(lachsinc): Passing the file for the scope may not be correct for nested procedures? This should probably be
  9624. // handled all inside push_debug_location, with just the Ast * we can pull out everything we need to construct scope/file debug info etc.
  9625. ir_add_debug_info_proc(proc);
  9626. ir_push_debug_location(proc->module, proc->entity->identifier, proc->debug_scope);
  9627. GB_ASSERT_NOT_NULL(proc->debug_scope);
  9628. } else {
  9629. ir_push_debug_location(proc->module, nullptr, nullptr);
  9630. }
  9631. proc->decl_block = ir_new_block(proc, proc->type_expr, "decls");
  9632. ir_start_block(proc, proc->decl_block);
  9633. proc->entry_block = ir_new_block(proc, proc->type_expr, "entry");
  9634. ir_start_block(proc, proc->entry_block);
  9635. i32 parameter_index = 0;
  9636. if (proc->type->Proc.return_by_pointer) {
  9637. // NOTE(bill): this must be the first parameter stored
  9638. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(proc->type->Proc.results));
  9639. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  9640. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  9641. irValue *param = ir_value_param(proc, e, ptr_type, -1);
  9642. param->Param.kind = irParamPass_Pointer;
  9643. ir_module_add_value(proc->module, e, param);
  9644. proc->return_ptr = param;
  9645. }
  9646. GB_ASSERT(proc->type != nullptr);
  9647. if (proc->type->Proc.params != nullptr) {
  9648. TypeTuple *params = &proc->type->Proc.params->Tuple;
  9649. if (proc->type_expr != nullptr) {
  9650. ast_node(pt, ProcType, proc->type_expr);
  9651. isize param_index = 0;
  9652. isize q_index = 0;
  9653. for_array(i, params->variables) {
  9654. ast_node(fl, FieldList, pt->params);
  9655. GB_ASSERT(fl->list.count > 0);
  9656. GB_ASSERT(fl->list[0]->kind == Ast_Field);
  9657. if (q_index == fl->list[param_index]->Field.names.count) {
  9658. q_index = 0;
  9659. param_index++;
  9660. }
  9661. ast_node(field, Field, fl->list[param_index]);
  9662. Ast *name = field->names[q_index++];
  9663. Entity *e = params->variables[i];
  9664. if (e->kind != Entity_Variable) {
  9665. parameter_index += 1;
  9666. continue;
  9667. }
  9668. Type *abi_type = proc->type->Proc.abi_compat_params[i];
  9669. if (e->token.string != "") {
  9670. ir_add_param(proc, e, name, abi_type, parameter_index);
  9671. }
  9672. if (is_type_tuple(abi_type)) {
  9673. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  9674. } else {
  9675. parameter_index += 1;
  9676. }
  9677. }
  9678. } else {
  9679. auto abi_types = proc->type->Proc.abi_compat_params;
  9680. for_array(i, params->variables) {
  9681. Entity *e = params->variables[i];
  9682. if (e->kind != Entity_Variable) {
  9683. parameter_index += 1;
  9684. continue;
  9685. }
  9686. Type *abi_type = e->type;
  9687. if (abi_types.count > 0) {
  9688. abi_type = abi_types[i];
  9689. }
  9690. if (e->token.string != "") {
  9691. ir_add_param(proc, e, nullptr, abi_type, parameter_index);
  9692. }
  9693. if (is_type_tuple(abi_type)) {
  9694. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  9695. } else {
  9696. parameter_index += 1;
  9697. }
  9698. }
  9699. }
  9700. }
  9701. if (proc->type->Proc.has_named_results) {
  9702. GB_ASSERT(proc->type->Proc.result_count > 0);
  9703. TypeTuple *results = &proc->type->Proc.results->Tuple;
  9704. for_array(i, results->variables) {
  9705. Entity *e = results->variables[i];
  9706. GB_ASSERT(e->kind == Entity_Variable);
  9707. if (e->token.string != "") {
  9708. GB_ASSERT(!is_blank_ident(e->token));
  9709. irAddr res = {};
  9710. if (proc->type->Proc.return_by_pointer) {
  9711. irValue *ptr = proc->return_ptr;
  9712. if (results->variables.count != 1) {
  9713. ptr = ir_emit_struct_ep(proc, ptr, cast(i32)i);
  9714. }
  9715. res = ir_addr(ptr);
  9716. ir_module_add_value(proc->module, e, ptr);
  9717. } else {
  9718. res = ir_addr(ir_add_local(proc, e, e->identifier, true));
  9719. }
  9720. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  9721. irValue *c = ir_handle_param_value(proc, e->type, e->Variable.param_value, e->token.pos);
  9722. ir_addr_store(proc, res, c);
  9723. }
  9724. }
  9725. }
  9726. }
  9727. if (proc->type->Proc.calling_convention == ProcCC_Odin) {
  9728. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  9729. e->flags |= EntityFlag_NoAlias;
  9730. irValue *param = ir_value_param(proc, e, e->type, -1);
  9731. ir_module_add_value(proc->module, e, param);
  9732. irContextData ctx = {param, proc->scope_index};
  9733. array_add(&proc->context_stack, ctx);
  9734. }
  9735. proc->parameter_count = parameter_index;
  9736. }
  9737. bool ir_remove_dead_instr(irProcedure *proc) {
  9738. if (proc->ignore_dead_instr) {
  9739. return false;
  9740. }
  9741. isize elimination_count = 0;
  9742. retry:
  9743. #if 1
  9744. for_array(i, proc->blocks) {
  9745. irBlock *b = proc->blocks[i];
  9746. b->index = cast(i32)i;
  9747. for (isize j = 0; j < b->instrs.count; /**/) {
  9748. irValue *value = b->instrs[j];
  9749. GB_ASSERT_MSG(value->kind == irValue_Instr, "%.*s", LIT(proc->name));
  9750. irInstr *instr = &value->Instr;
  9751. if (value->uses == 0) {
  9752. switch (instr->kind) {
  9753. case irInstr_Load:
  9754. instr->Load.address->uses -= 1;
  9755. array_ordered_remove(&b->instrs, j);
  9756. elimination_count += 1;
  9757. continue;
  9758. case irInstr_Local:
  9759. array_ordered_remove(&b->instrs, j);
  9760. elimination_count += 1;
  9761. continue;
  9762. case irInstr_AtomicLoad:
  9763. instr->AtomicLoad.address->uses -= 1;
  9764. array_ordered_remove(&b->instrs, j);
  9765. elimination_count += 1;
  9766. continue;
  9767. case irInstr_PtrOffset:
  9768. instr->PtrOffset.address->uses -= 1;
  9769. instr->PtrOffset.offset->uses -= 1;
  9770. array_ordered_remove(&b->instrs, j);
  9771. elimination_count += 1;
  9772. continue;
  9773. case irInstr_ArrayElementPtr:
  9774. instr->ArrayElementPtr.address->uses -= 1;
  9775. instr->ArrayElementPtr.elem_index->uses -= 1;
  9776. array_ordered_remove(&b->instrs, j);
  9777. elimination_count += 1;
  9778. continue;
  9779. case irInstr_StructElementPtr:
  9780. instr->StructElementPtr.address->uses -= 1;
  9781. array_ordered_remove(&b->instrs, j);
  9782. elimination_count += 1;
  9783. continue;
  9784. case irInstr_StructExtractValue:
  9785. instr->StructExtractValue.address->uses -= 1;
  9786. array_ordered_remove(&b->instrs, j);
  9787. elimination_count += 1;
  9788. continue;
  9789. case irInstr_UnionTagPtr:
  9790. instr->UnionTagPtr.address->uses -= 1;
  9791. array_ordered_remove(&b->instrs, j);
  9792. elimination_count += 1;
  9793. continue;
  9794. case irInstr_UnionTagValue:
  9795. instr->UnionTagValue.address->uses -= 1;
  9796. array_ordered_remove(&b->instrs, j);
  9797. elimination_count += 1;
  9798. continue;
  9799. // case irInstr_Conv:
  9800. // // instr->Conv.value->uses -= 1;
  9801. // array_ordered_remove(&b->instrs, j);
  9802. // elimination_count += 1;
  9803. // continue;
  9804. // case irInstr_UnaryOp:
  9805. // // instr->UnaryOp.expr->uses -= 1;
  9806. // array_ordered_remove(&b->instrs, j);
  9807. // elimination_count += 1;
  9808. // continue;
  9809. // case irInstr_BinaryOp:
  9810. // // instr->BinaryOp.left->uses -= 1;
  9811. // // instr->BinaryOp.right->uses -= 1;
  9812. // array_ordered_remove(&b->instrs, j);
  9813. // elimination_count += 1;
  9814. // continue;
  9815. }
  9816. }
  9817. j += 1;
  9818. }
  9819. }
  9820. #endif
  9821. if (elimination_count > 0) {
  9822. // gb_printf_err("Retry ir_remove_dead_instr, count: %td; %.*s\n", elimination_count, LIT(proc->name));
  9823. elimination_count = 0;
  9824. goto retry;
  9825. }
  9826. return elimination_count > 0;
  9827. }
  9828. void ir_end_procedure_body(irProcedure *proc) {
  9829. if (proc->type->Proc.result_count == 0) {
  9830. ir_emit_return(proc, nullptr);
  9831. }
  9832. if (proc->curr_block->instrs.count == 0) {
  9833. ir_emit_unreachable(proc);
  9834. }
  9835. GB_ASSERT(proc->scope_index == 0);
  9836. proc->curr_block = proc->decl_block;
  9837. ir_emit_jump(proc, proc->entry_block);
  9838. proc->curr_block = nullptr;
  9839. ir_remove_dead_instr(proc);
  9840. ir_number_proc_registers(proc);
  9841. ir_pop_debug_location(proc->module);
  9842. }
  9843. void ir_insert_code_before_proc(irProcedure* proc, irProcedure *parent) {
  9844. // if (parent == nullptr) {
  9845. // if (proc->name == "main") {
  9846. // ir_emit_startup_runtime(proc);
  9847. // }
  9848. // }
  9849. }
  9850. void ir_build_proc(irValue *value, irProcedure *parent) {
  9851. irProcedure *proc = &value->Proc;
  9852. set_procedure_abi_types(proc->type);
  9853. proc->parent = parent;
  9854. if (proc->body != nullptr && proc->body->kind != Ast_Invalid) {
  9855. u64 prev_state_flags = proc->module->state_flags;
  9856. if (proc->tags != 0) {
  9857. u64 in = proc->tags;
  9858. u64 out = proc->module->state_flags;
  9859. if (in & ProcTag_bounds_check) {
  9860. out |= StateFlag_bounds_check;
  9861. out &= ~StateFlag_no_bounds_check;
  9862. } else if (in & ProcTag_no_bounds_check) {
  9863. out |= StateFlag_no_bounds_check;
  9864. out &= ~StateFlag_bounds_check;
  9865. }
  9866. proc->module->state_flags = out;
  9867. }
  9868. ir_begin_procedure_body(proc);
  9869. ir_insert_code_before_proc(proc, parent);
  9870. ir_build_stmt(proc, proc->body);
  9871. ir_end_procedure_body(proc);
  9872. proc->module->state_flags = prev_state_flags;
  9873. }
  9874. // NOTE(lachsinc): For now we pop the debug location inside ir_end_procedure_body().
  9875. // This may result in debug info being missing for below.
  9876. if (proc->type->Proc.has_proc_default_values) {
  9877. auto *p = &proc->type->Proc;
  9878. if (p->params != nullptr) for_array(i, p->params->Tuple.variables) {
  9879. Entity *f = p->params->Tuple.variables[i];
  9880. if (f->kind == Entity_Variable) {
  9881. ParameterValue pv = f->Variable.param_value;
  9882. if (pv.kind == ParameterValue_Constant && pv.value.kind == ExactValue_Procedure) {
  9883. Ast *expr = f->Variable.param_value.value.value_procedure;
  9884. GB_ASSERT(expr != nullptr);
  9885. if (expr->kind == Ast_ProcLit) {
  9886. ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
  9887. }
  9888. }
  9889. }
  9890. }
  9891. if (p->results != nullptr) for_array(i, p->results->Tuple.variables) {
  9892. Entity *f = p->results->Tuple.variables[i];
  9893. if (f->kind == Entity_Variable) {
  9894. ParameterValue pv = f->Variable.param_value;
  9895. if (pv.kind == ParameterValue_Constant && pv.value.kind == ExactValue_Procedure) {
  9896. Ast *expr = f->Variable.param_value.value.value_procedure;
  9897. GB_ASSERT(expr != nullptr);
  9898. if (expr->kind == Ast_ProcLit) {
  9899. ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
  9900. }
  9901. }
  9902. }
  9903. }
  9904. }
  9905. }
  9906. ////////////////////////////////////////////////////////////////
  9907. //
  9908. // @Module
  9909. //
  9910. ////////////////////////////////////////////////////////////////
  9911. void ir_module_add_value(irModule *m, Entity *e, irValue *v) {
  9912. map_set(&m->values, hash_entity(e), v);
  9913. // TODO(lachsinc): This may not be the most sensible place to do this!
  9914. // it may be more sensible to look for more specific locations that call ir_value_global and assign it a value? maybe?
  9915. // ir_value_global itself doesn't have access to module though.
  9916. if (v->kind == irValue_Global && v->Global.value != nullptr && e->state == EntityState_Resolved) {
  9917. ir_add_debug_info_global(m, v);
  9918. }
  9919. }
  9920. void ir_init_module(irModule *m, Checker *c) {
  9921. // TODO(bill): Determine a decent size for the arena
  9922. isize token_count = c->parser->total_token_count;
  9923. isize arena_size = 4 * token_count * gb_size_of(irValue);
  9924. gb_arena_init_from_allocator(&m->tmp_arena, heap_allocator(), arena_size);
  9925. ir_allocator() = ir_allocator();
  9926. m->tmp_allocator = gb_arena_allocator(&m->tmp_arena);
  9927. m->info = &c->info;
  9928. m->generate_debug_info = false;
  9929. if (build_context.ODIN_DEBUG) {
  9930. m->generate_debug_info = build_context.ODIN_OS == "windows" && build_context.word_size == 8;
  9931. }
  9932. map_init(&m->values, heap_allocator());
  9933. string_map_init(&m->members, heap_allocator());
  9934. map_init(&m->debug_info, heap_allocator());
  9935. map_init(&m->entity_names, heap_allocator());
  9936. map_init(&m->anonymous_proc_lits, heap_allocator());
  9937. map_init(&m->equal_procs, heap_allocator());
  9938. map_init(&m->hasher_procs, heap_allocator());
  9939. array_init(&m->procs, heap_allocator());
  9940. array_init(&m->procs_to_generate, heap_allocator());
  9941. array_init(&m->foreign_library_paths, heap_allocator());
  9942. string_map_init(&m->const_strings, heap_allocator());
  9943. string_map_init(&m->const_string_byte_slices, heap_allocator());
  9944. map_init(&m->constant_value_to_global, heap_allocator());
  9945. // Default states
  9946. m->state_flags = 0;
  9947. m->state_flags |= StateFlag_bounds_check;
  9948. {
  9949. // Add type info data
  9950. {
  9951. isize max_type_info_count = ir_type_info_count(m->info);
  9952. String name = str_lit(IR_TYPE_INFO_DATA_NAME);
  9953. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name), alloc_type_array(t_type_info, max_type_info_count));
  9954. irValue *g = ir_value_global(e, nullptr);
  9955. g->Global.is_private = true;
  9956. ir_module_add_value(m, e, g);
  9957. string_map_set(&m->members, name, g);
  9958. ir_global_type_info_data = g;
  9959. }
  9960. // Type info member buffer
  9961. {
  9962. // NOTE(bill): Removes need for heap allocation by making it global memory
  9963. isize count = 0;
  9964. for_array(entry_index, m->info->type_info_types) {
  9965. Type *t = m->info->type_info_types[entry_index];
  9966. isize index = ir_type_info_index(m->info, t, false);
  9967. if (index < 0) {
  9968. continue;
  9969. }
  9970. switch (t->kind) {
  9971. case Type_Union:
  9972. count += t->Union.variants.count;
  9973. break;
  9974. case Type_Struct:
  9975. count += t->Struct.fields.count;
  9976. break;
  9977. case Type_Tuple:
  9978. count += t->Tuple.variables.count;
  9979. break;
  9980. }
  9981. }
  9982. if (count > 0) {
  9983. {
  9984. String name = str_lit(IR_TYPE_INFO_TYPES_NAME);
  9985. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  9986. alloc_type_array(t_type_info_ptr, count));
  9987. irValue *g = ir_value_global(e, nullptr);
  9988. ir_module_add_value(m, e, g);
  9989. string_map_set(&m->members, name, g);
  9990. ir_global_type_info_member_types = g;
  9991. }
  9992. {
  9993. String name = str_lit(IR_TYPE_INFO_NAMES_NAME);
  9994. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  9995. alloc_type_array(t_string, count));
  9996. irValue *g = ir_value_global(e, nullptr);
  9997. ir_module_add_value(m, e, g);
  9998. string_map_set(&m->members, name, g);
  9999. ir_global_type_info_member_names = g;
  10000. }
  10001. {
  10002. String name = str_lit(IR_TYPE_INFO_OFFSETS_NAME);
  10003. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  10004. alloc_type_array(t_uintptr, count));
  10005. irValue *g = ir_value_global(e, nullptr);
  10006. ir_module_add_value(m, e, g);
  10007. string_map_set(&m->members, name, g);
  10008. ir_global_type_info_member_offsets = g;
  10009. }
  10010. {
  10011. String name = str_lit(IR_TYPE_INFO_USINGS_NAME);
  10012. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  10013. alloc_type_array(t_bool, count));
  10014. irValue *g = ir_value_global(e, nullptr);
  10015. ir_module_add_value(m, e, g);
  10016. string_map_set(&m->members, name, g);
  10017. ir_global_type_info_member_usings = g;
  10018. }
  10019. {
  10020. String name = str_lit(IR_TYPE_INFO_TAGS_NAME);
  10021. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  10022. alloc_type_array(t_string, count));
  10023. irValue *g = ir_value_global(e, nullptr);
  10024. ir_module_add_value(m, e, g);
  10025. string_map_set(&m->members, name, g);
  10026. ir_global_type_info_member_tags = g;
  10027. }
  10028. }
  10029. }
  10030. }
  10031. {
  10032. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompileUnit);
  10033. GB_ASSERT(m->info->files.entries.count > 0);
  10034. AstFile *file = m->info->files.entries[0].value;
  10035. di->CompileUnit.file = file; // Zeroth is the init file
  10036. di->CompileUnit.producer = str_lit("odin");
  10037. map_set(&m->debug_info, hash_pointer(m), di);
  10038. m->debug_compile_unit = di;
  10039. irDebugInfo *enums_di = ir_alloc_debug_info(irDebugInfo_DebugInfoArray);
  10040. array_init(&enums_di->DebugInfoArray.elements, heap_allocator()); // TODO(lachsinc): ir_allocator() ??
  10041. map_set(&m->debug_info, hash_pointer(enums_di), enums_di);
  10042. m->debug_compile_unit->CompileUnit.enums = enums_di;
  10043. irDebugInfo *globals_di = ir_alloc_debug_info(irDebugInfo_DebugInfoArray);
  10044. array_init(&globals_di->DebugInfoArray.elements, heap_allocator()); // TODO(lachsinc): ir_allocator() ??
  10045. map_set(&m->debug_info, hash_pointer(globals_di), globals_di);
  10046. m->debug_compile_unit->CompileUnit.globals = globals_di;
  10047. array_init(&m->debug_location_stack, heap_allocator()); // TODO(lachsinc): ir_allocator() ??
  10048. }
  10049. {
  10050. for_array(i, m->info->files.entries) {
  10051. AstFile *file = m->info->files.entries[i].value;
  10052. ir_add_debug_info_file(m, file);
  10053. }
  10054. }
  10055. }
  10056. void ir_destroy_module(irModule *m) {
  10057. map_destroy(&m->values);
  10058. string_map_destroy(&m->members);
  10059. map_destroy(&m->entity_names);
  10060. map_destroy(&m->anonymous_proc_lits);
  10061. map_destroy(&m->debug_info);
  10062. string_map_destroy(&m->const_strings);
  10063. string_map_destroy(&m->const_string_byte_slices);
  10064. map_destroy(&m->constant_value_to_global);
  10065. array_free(&m->procs);
  10066. array_free(&m->procs_to_generate);
  10067. array_free(&m->foreign_library_paths);
  10068. array_free(&m->debug_location_stack);
  10069. gb_arena_free(&m->tmp_arena);
  10070. }
  10071. ////////////////////////////////////////////////////////////////
  10072. //
  10073. // @Code Generation
  10074. //
  10075. ////////////////////////////////////////////////////////////////
  10076. bool ir_gen_init(irGen *s, Checker *c) {
  10077. if (global_error_collector.count != 0) {
  10078. return false;
  10079. }
  10080. isize tc = c->parser->total_token_count;
  10081. if (tc < 2) {
  10082. return false;
  10083. }
  10084. arena_init(&global_ir_arena, heap_allocator());
  10085. ir_init_module(&s->module, c);
  10086. // s->module.generate_debug_info = false;
  10087. String init_fullpath = c->parser->init_fullpath;
  10088. if (build_context.out_filepath.len == 0) {
  10089. s->output_name = remove_directory_from_path(init_fullpath);
  10090. s->output_name = remove_extension_from_path(s->output_name);
  10091. s->output_name = string_trim_whitespace(s->output_name);
  10092. if (s->output_name.len == 0) {
  10093. s->output_name = c->info.init_scope->pkg->name;
  10094. }
  10095. s->output_base = s->output_name;
  10096. } else {
  10097. s->output_name = build_context.out_filepath;
  10098. s->output_name = string_trim_whitespace(s->output_name);
  10099. if (s->output_name.len == 0) {
  10100. s->output_name = c->info.init_scope->pkg->name;
  10101. }
  10102. isize pos = string_extension_position(s->output_name);
  10103. if (pos < 0) {
  10104. s->output_base = s->output_name;
  10105. } else {
  10106. s->output_base = substring(s->output_name, 0, pos);
  10107. }
  10108. }
  10109. gbAllocator ha = heap_allocator();
  10110. s->output_base = path_to_full_path(ha, s->output_base);
  10111. gbString output_file_path = gb_string_make_length(ha, s->output_base.text, s->output_base.len);
  10112. output_file_path = gb_string_appendc(output_file_path, ".ll");
  10113. defer (gb_string_free(output_file_path));
  10114. gbFileError err = gb_file_create(&s->output_file, output_file_path);
  10115. if (err != gbFileError_None) {
  10116. gb_printf_err("Failed to create file %s\n", output_file_path);
  10117. return false;
  10118. }
  10119. return true;
  10120. }
  10121. void ir_gen_destroy(irGen *s) {
  10122. ir_destroy_module(&s->module);
  10123. gb_file_close(&s->output_file);
  10124. }
  10125. //
  10126. // Type Info stuff
  10127. //
  10128. irValue *ir_get_type_info_ptr(irProcedure *proc, Type *type) {
  10129. i32 index = cast(i32)ir_type_info_index(proc->module->info, type);
  10130. // gb_printf_err("%d %s\n", index, type_to_string(type));
  10131. irValue *ptr = ir_emit_array_epi(proc, ir_global_type_info_data, index);
  10132. return ir_emit_bitcast(proc, ptr, t_type_info_ptr);
  10133. }
  10134. irValue *ir_type_info_member_types_offset(irProcedure *proc, isize count) {
  10135. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_types, ir_global_type_info_member_types_index);
  10136. ir_global_type_info_member_types_index += cast(i32)count;
  10137. return offset;
  10138. }
  10139. irValue *ir_type_info_member_names_offset(irProcedure *proc, isize count) {
  10140. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_names, ir_global_type_info_member_names_index);
  10141. ir_global_type_info_member_names_index += cast(i32)count;
  10142. return offset;
  10143. }
  10144. irValue *ir_type_info_member_offsets_offset(irProcedure *proc, isize count) {
  10145. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_offsets, ir_global_type_info_member_offsets_index);
  10146. ir_global_type_info_member_offsets_index += cast(i32)count;
  10147. return offset;
  10148. }
  10149. irValue *ir_type_info_member_usings_offset(irProcedure *proc, isize count) {
  10150. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_usings, ir_global_type_info_member_usings_index);
  10151. ir_global_type_info_member_usings_index += cast(i32)count;
  10152. return offset;
  10153. }
  10154. irValue *ir_type_info_member_tags_offset(irProcedure *proc, isize count) {
  10155. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_tags, ir_global_type_info_member_tags_index);
  10156. ir_global_type_info_member_tags_index += cast(i32)count;
  10157. return offset;
  10158. }
  10159. void ir_setup_type_info_data(irProcedure *proc) { // NOTE(bill): Setup type_info data
  10160. irModule *m = proc->module;
  10161. gbAllocator a = ir_allocator();
  10162. CheckerInfo *info = m->info;
  10163. if (true) {
  10164. irValue *global_type_table = ir_find_global_variable(proc, str_lit("type_table"));
  10165. Type *type = base_type(type_deref(ir_type(ir_global_type_info_data)));
  10166. GB_ASSERT(is_type_array(type));
  10167. irValue *len = ir_const_int(type->Array.count);
  10168. ir_fill_slice(proc, global_type_table,
  10169. ir_emit_array_epi(proc, ir_global_type_info_data, 0),
  10170. len);
  10171. }
  10172. // Useful types
  10173. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  10174. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  10175. Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags"));
  10176. Type *t_type_info_flags = type_info_flags_entity->type;
  10177. i32 type_info_member_types_index = 0;
  10178. i32 type_info_member_names_index = 0;
  10179. i32 type_info_member_offsets_index = 0;
  10180. for_array(type_info_type_index, info->type_info_types) {
  10181. Type *t = info->type_info_types[type_info_type_index];
  10182. t = default_type(t);
  10183. if (t == t_invalid) {
  10184. continue;
  10185. }
  10186. isize entry_index = ir_type_info_index(info, t, false);
  10187. if (entry_index <= 0) {
  10188. continue;
  10189. }
  10190. irValue *tag = nullptr;
  10191. irValue *ti_ptr = ir_emit_array_epi(proc, ir_global_type_info_data, cast(i32)entry_index);
  10192. irValue *variant_ptr = ir_emit_struct_ep(proc, ti_ptr, 4);
  10193. irValue *type_info_flags = ir_value_constant(t_type_info_flags, exact_value_i64(type_info_flags_of_type(t)));
  10194. ir_emit_store(proc, ir_emit_struct_ep(proc, ti_ptr, 0), ir_const_int(type_size_of(t)));
  10195. ir_emit_store(proc, ir_emit_struct_ep(proc, ti_ptr, 1), ir_const_int(type_align_of(t)));
  10196. ir_emit_store(proc, ir_emit_struct_ep(proc, ti_ptr, 2), type_info_flags);
  10197. ir_emit_store(proc, ir_emit_struct_ep(proc, ti_ptr, 3), ir_typeid(proc->module, t));
  10198. switch (t->kind) {
  10199. case Type_Named: {
  10200. ir_emit_comment(proc, str_lit("Type_Info_Named"));
  10201. tag = ir_emit_conv(proc, variant_ptr, t_type_info_named_ptr);
  10202. // TODO(bill): Which is better? The mangled name or actual name?
  10203. irValue *name = ir_const_string(proc->module, t->Named.type_name->token.string);
  10204. irValue *gtip = ir_get_type_info_ptr(proc, t->Named.base);
  10205. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), name);
  10206. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), gtip);
  10207. if (t->Named.type_name->pkg) {
  10208. irValue *name = ir_const_string(proc->module, t->Named.type_name->pkg->name);
  10209. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 2), name);
  10210. }
  10211. String proc_name = {};
  10212. if (t->Named.type_name->parent_proc_decl) {
  10213. DeclInfo *decl = t->Named.type_name->parent_proc_decl;
  10214. if (decl->entity && decl->entity->kind == Entity_Procedure) {
  10215. proc_name = decl->entity->token.string;
  10216. }
  10217. }
  10218. irValue *loc = ir_emit_source_code_location(proc, proc_name, t->Named.type_name->token.pos);
  10219. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 3), loc);
  10220. break;
  10221. }
  10222. case Type_Basic:
  10223. ir_emit_comment(proc, str_lit("Type_Info_Basic"));
  10224. switch (t->Basic.kind) {
  10225. case Basic_bool:
  10226. case Basic_b8:
  10227. case Basic_b16:
  10228. case Basic_b32:
  10229. case Basic_b64:
  10230. tag = ir_emit_conv(proc, variant_ptr, t_type_info_boolean_ptr);
  10231. break;
  10232. case Basic_i8:
  10233. case Basic_u8:
  10234. case Basic_i16:
  10235. case Basic_u16:
  10236. case Basic_i32:
  10237. case Basic_u32:
  10238. case Basic_i64:
  10239. case Basic_u64:
  10240. case Basic_i128:
  10241. case Basic_u128:
  10242. case Basic_i16le:
  10243. case Basic_u16le:
  10244. case Basic_i32le:
  10245. case Basic_u32le:
  10246. case Basic_i64le:
  10247. case Basic_u64le:
  10248. case Basic_i128le:
  10249. case Basic_u128le:
  10250. case Basic_i16be:
  10251. case Basic_u16be:
  10252. case Basic_i32be:
  10253. case Basic_u32be:
  10254. case Basic_i64be:
  10255. case Basic_u64be:
  10256. case Basic_i128be:
  10257. case Basic_u128be:
  10258. case Basic_int:
  10259. case Basic_uint:
  10260. case Basic_uintptr: {
  10261. tag = ir_emit_conv(proc, variant_ptr, t_type_info_integer_ptr);
  10262. irValue *is_signed = ir_const_bool((t->Basic.flags & BasicFlag_Unsigned) == 0);
  10263. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), is_signed);
  10264. // NOTE(bill): This is matches the runtime layout
  10265. u8 endianness_value = 0;
  10266. if (t->Basic.flags & BasicFlag_EndianLittle) {
  10267. endianness_value = 1;
  10268. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  10269. endianness_value = 2;
  10270. }
  10271. irValue *endianness = ir_const_u8(endianness_value);
  10272. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), endianness);
  10273. break;
  10274. }
  10275. case Basic_rune:
  10276. tag = ir_emit_conv(proc, variant_ptr, t_type_info_rune_ptr);
  10277. break;
  10278. // case Basic_f16:
  10279. case Basic_f32:
  10280. case Basic_f64:
  10281. case Basic_f32le:
  10282. case Basic_f64le:
  10283. case Basic_f32be:
  10284. case Basic_f64be:
  10285. {
  10286. tag = ir_emit_conv(proc, variant_ptr, t_type_info_float_ptr);
  10287. // NOTE(bill): This is matches the runtime layout
  10288. u8 endianness_value = 0;
  10289. if (t->Basic.flags & BasicFlag_EndianLittle) {
  10290. endianness_value = 1;
  10291. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  10292. endianness_value = 2;
  10293. }
  10294. irValue *endianness = ir_const_u8(endianness_value);
  10295. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), endianness);
  10296. }
  10297. break;
  10298. // case Basic_complex32:
  10299. case Basic_complex64:
  10300. case Basic_complex128:
  10301. tag = ir_emit_conv(proc, variant_ptr, t_type_info_complex_ptr);
  10302. break;
  10303. case Basic_quaternion128:
  10304. case Basic_quaternion256:
  10305. tag = ir_emit_conv(proc, variant_ptr, t_type_info_quaternion_ptr);
  10306. break;
  10307. case Basic_rawptr:
  10308. tag = ir_emit_conv(proc, variant_ptr, t_type_info_pointer_ptr);
  10309. break;
  10310. case Basic_string:
  10311. tag = ir_emit_conv(proc, variant_ptr, t_type_info_string_ptr);
  10312. break;
  10313. case Basic_cstring:
  10314. tag = ir_emit_conv(proc, variant_ptr, t_type_info_string_ptr);
  10315. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), v_true); // is_cstring
  10316. break;
  10317. case Basic_any:
  10318. tag = ir_emit_conv(proc, variant_ptr, t_type_info_any_ptr);
  10319. break;
  10320. case Basic_typeid:
  10321. tag = ir_emit_conv(proc, variant_ptr, t_type_info_typeid_ptr);
  10322. break;
  10323. }
  10324. break;
  10325. case Type_Pointer: {
  10326. ir_emit_comment(proc, str_lit("Type_Info_Pointer"));
  10327. tag = ir_emit_conv(proc, variant_ptr, t_type_info_pointer_ptr);
  10328. irValue *gep = ir_get_type_info_ptr(proc, t->Pointer.elem);
  10329. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  10330. break;
  10331. }
  10332. case Type_Array: {
  10333. ir_emit_comment(proc, str_lit("Type_Info_Array"));
  10334. tag = ir_emit_conv(proc, variant_ptr, t_type_info_array_ptr);
  10335. irValue *gep = ir_get_type_info_ptr(proc, t->Array.elem);
  10336. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  10337. i64 ez = type_size_of(t->Array.elem);
  10338. irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
  10339. ir_emit_store(proc, elem_size, ir_const_int(ez));
  10340. irValue *count = ir_emit_struct_ep(proc, tag, 2);
  10341. ir_emit_store(proc, count, ir_const_int(t->Array.count));
  10342. break;
  10343. }
  10344. case Type_EnumeratedArray: {
  10345. ir_emit_comment(proc, str_lit("Type_Info_Enumerated_Array"));
  10346. tag = ir_emit_conv(proc, variant_ptr, t_type_info_enumerated_array_ptr);
  10347. irValue *elem = ir_get_type_info_ptr(proc, t->EnumeratedArray.elem);
  10348. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), elem);
  10349. irValue *index = ir_get_type_info_ptr(proc, t->EnumeratedArray.index);
  10350. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), index);
  10351. i64 ez = type_size_of(t->EnumeratedArray.elem);
  10352. irValue *elem_size = ir_emit_struct_ep(proc, tag, 2);
  10353. ir_emit_store(proc, elem_size, ir_const_int(ez));
  10354. irValue *count = ir_emit_struct_ep(proc, tag, 3);
  10355. ir_emit_store(proc, count, ir_const_int(t->EnumeratedArray.count));
  10356. irValue *min_value = ir_emit_struct_ep(proc, tag, 4);
  10357. irValue *max_value = ir_emit_struct_ep(proc, tag, 5);
  10358. irValue *min_v = ir_value_constant(t_i64, t->EnumeratedArray.min_value);
  10359. irValue *max_v = ir_value_constant(t_i64, t->EnumeratedArray.max_value);
  10360. ir_emit_store(proc, min_value, min_v);
  10361. ir_emit_store(proc, max_value, max_v);
  10362. break;
  10363. }
  10364. case Type_DynamicArray: {
  10365. ir_emit_comment(proc, str_lit("Type_Info_Dynamic_Array"));
  10366. tag = ir_emit_conv(proc, variant_ptr, t_type_info_dynamic_array_ptr);
  10367. irValue *gep = ir_get_type_info_ptr(proc, t->DynamicArray.elem);
  10368. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  10369. i64 ez = type_size_of(t->DynamicArray.elem);
  10370. irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
  10371. ir_emit_store(proc, elem_size, ir_const_int(ez));
  10372. break;
  10373. }
  10374. case Type_Slice: {
  10375. ir_emit_comment(proc, str_lit("Type_Info_Slice"));
  10376. tag = ir_emit_conv(proc, variant_ptr, t_type_info_slice_ptr);
  10377. irValue *gep = ir_get_type_info_ptr(proc, t->Slice.elem);
  10378. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  10379. i64 ez = type_size_of(t->Slice.elem);
  10380. irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
  10381. ir_emit_store(proc, elem_size, ir_const_int(ez));
  10382. break;
  10383. }
  10384. case Type_Proc: {
  10385. ir_emit_comment(proc, str_lit("Type_Info_Proc"));
  10386. tag = ir_emit_conv(proc, variant_ptr, t_type_info_procedure_ptr);
  10387. irValue *params = ir_emit_struct_ep(proc, tag, 0);
  10388. irValue *results = ir_emit_struct_ep(proc, tag, 1);
  10389. irValue *variadic = ir_emit_struct_ep(proc, tag, 2);
  10390. irValue *convention = ir_emit_struct_ep(proc, tag, 3);
  10391. if (t->Proc.params != nullptr) {
  10392. ir_emit_store(proc, params, ir_get_type_info_ptr(proc, t->Proc.params));
  10393. }
  10394. if (t->Proc.results != nullptr) {
  10395. ir_emit_store(proc, results, ir_get_type_info_ptr(proc, t->Proc.results));
  10396. }
  10397. ir_emit_store(proc, variadic, ir_const_bool(t->Proc.variadic));
  10398. ir_emit_store(proc, convention, ir_const_u8(t->Proc.calling_convention));
  10399. // TODO(bill): TypeInfo for procedures
  10400. break;
  10401. }
  10402. case Type_Tuple: {
  10403. ir_emit_comment(proc, str_lit("Type_Info_Tuple"));
  10404. tag = ir_emit_conv(proc, variant_ptr, t_type_info_tuple_ptr);
  10405. irValue *memory_types = ir_type_info_member_types_offset(proc, t->Tuple.variables.count);
  10406. irValue *memory_names = ir_type_info_member_names_offset(proc, t->Tuple.variables.count);
  10407. for_array(i, t->Tuple.variables) {
  10408. // NOTE(bill): offset is not used for tuples
  10409. Entity *f = t->Tuple.variables[i];
  10410. irValue *index = ir_const_int(i);
  10411. irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
  10412. ir_emit_store(proc, type_info, ir_type_info(proc, f->type));
  10413. if (f->token.string.len > 0) {
  10414. irValue *name = ir_emit_ptr_offset(proc, memory_names, index);
  10415. ir_emit_store(proc, name, ir_const_string(proc->module, f->token.string));
  10416. }
  10417. }
  10418. irValue *count = ir_const_int(t->Tuple.variables.count);
  10419. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 0), memory_types, count);
  10420. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 1), memory_names, count);
  10421. break;
  10422. }
  10423. case Type_Enum:
  10424. ir_emit_comment(proc, str_lit("Type_Info_Enum"));
  10425. tag = ir_emit_conv(proc, variant_ptr, t_type_info_enum_ptr);
  10426. {
  10427. GB_ASSERT(t->Enum.base_type != nullptr);
  10428. irValue *base = ir_type_info(proc, t->Enum.base_type);
  10429. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), base);
  10430. if (t->Enum.fields.count > 0) {
  10431. auto fields = t->Enum.fields;
  10432. irValue *name_array = ir_generate_array(m, t_string, fields.count,
  10433. str_lit("$enum_names"), cast(i64)entry_index);
  10434. irValue *value_array = ir_generate_array(m, t_type_info_enum_value, fields.count,
  10435. str_lit("$enum_values"), cast(i64)entry_index);
  10436. GB_ASSERT(is_type_integer(t->Enum.base_type));
  10437. for_array(i, fields) {
  10438. irValue *name_ep = ir_emit_array_epi(proc, name_array, cast(i32)i);
  10439. irValue *value_ep = ir_emit_array_epi(proc, value_array, cast(i32)i);
  10440. ExactValue value = fields[i]->Constant.value;
  10441. irValue *v = ir_value_constant(t_i64, value);
  10442. ir_emit_store(proc, value_ep, v);
  10443. ir_emit_store(proc, name_ep, ir_const_string(proc->module, fields[i]->token.string));
  10444. }
  10445. irValue *v_count = ir_const_int(fields.count);
  10446. irValue *names = ir_emit_struct_ep(proc, tag, 1);
  10447. irValue *name_array_elem = ir_array_elem(proc, name_array);
  10448. ir_fill_slice(proc, names, name_array_elem, v_count);
  10449. irValue *values = ir_emit_struct_ep(proc, tag, 2);
  10450. irValue *value_array_elem = ir_array_elem(proc, value_array);
  10451. ir_fill_slice(proc, values, value_array_elem, v_count);
  10452. }
  10453. }
  10454. break;
  10455. case Type_Union: {
  10456. ir_emit_comment(proc, str_lit("Type_Info_Union"));
  10457. tag = ir_emit_conv(proc, variant_ptr, t_type_info_union_ptr);
  10458. {
  10459. irValue *variant_types = ir_emit_struct_ep(proc, tag, 0);
  10460. irValue *tag_offset_ptr = ir_emit_struct_ep(proc, tag, 1);
  10461. irValue *tag_type_ptr = ir_emit_struct_ep(proc, tag, 2);
  10462. irValue *custom_align_ptr = ir_emit_struct_ep(proc, tag, 3);
  10463. irValue *no_nil_ptr = ir_emit_struct_ep(proc, tag, 4);
  10464. irValue *maybe_ptr = ir_emit_struct_ep(proc, tag, 5);
  10465. isize variant_count = gb_max(0, t->Union.variants.count);
  10466. irValue *memory_types = ir_type_info_member_types_offset(proc, variant_count);
  10467. // NOTE(bill): Zeroth is nil so ignore it
  10468. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  10469. Type *vt = t->Union.variants[variant_index];
  10470. irValue *tip = ir_get_type_info_ptr(proc, vt);
  10471. irValue *index = ir_const_int(variant_index);
  10472. irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
  10473. ir_emit_store(proc, type_info, ir_type_info(proc, vt));
  10474. }
  10475. irValue *count = ir_const_int(variant_count);
  10476. ir_fill_slice(proc, variant_types, memory_types, count);
  10477. i64 tag_size = union_tag_size(t);
  10478. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  10479. if (tag_size > 0) {
  10480. ir_emit_store(proc, tag_offset_ptr, ir_const_uintptr(tag_offset));
  10481. ir_emit_store(proc, tag_type_ptr, ir_type_info(proc, union_tag_type(t)));
  10482. }
  10483. irValue *is_custom_align = ir_const_bool(t->Union.custom_align != 0);
  10484. ir_emit_store(proc, custom_align_ptr, is_custom_align);
  10485. ir_emit_store(proc, no_nil_ptr, ir_const_bool(t->Union.no_nil));
  10486. ir_emit_store(proc, maybe_ptr, ir_const_bool(t->Union.maybe));
  10487. }
  10488. break;
  10489. }
  10490. case Type_Struct: {
  10491. ir_emit_comment(proc, str_lit("Type_Info_Struct"));
  10492. tag = ir_emit_conv(proc, variant_ptr, t_type_info_struct_ptr);
  10493. {
  10494. irValue *is_packed = ir_const_bool(t->Struct.is_packed);
  10495. irValue *is_raw_union = ir_const_bool(t->Struct.is_raw_union);
  10496. irValue *is_custom_align = ir_const_bool(t->Struct.custom_align != 0);
  10497. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 5), is_packed);
  10498. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 6), is_raw_union);
  10499. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 7), is_custom_align);
  10500. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  10501. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 8), ir_get_equal_proc_for_type(proc->module, t));
  10502. }
  10503. if (t->Struct.soa_kind != StructSoa_None) {
  10504. irValue *kind = ir_emit_struct_ep(proc, tag, 9);
  10505. Type *kind_type = type_deref(ir_type(kind));
  10506. irValue *soa_kind = ir_value_constant(kind_type, exact_value_i64(t->Struct.soa_kind));
  10507. irValue *soa_type = ir_type_info(proc, t->Struct.soa_elem);
  10508. irValue *soa_len = ir_const_int(t->Struct.soa_count);
  10509. ir_emit_store(proc, kind, soa_kind);
  10510. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 10), soa_type);
  10511. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 11), soa_len);
  10512. }
  10513. }
  10514. isize count = t->Struct.fields.count;
  10515. if (count > 0) {
  10516. irValue *memory_types = ir_type_info_member_types_offset (proc, count);
  10517. irValue *memory_names = ir_type_info_member_names_offset (proc, count);
  10518. irValue *memory_offsets = ir_type_info_member_offsets_offset(proc, count);
  10519. irValue *memory_usings = ir_type_info_member_usings_offset (proc, count);
  10520. irValue *memory_tags = ir_type_info_member_tags_offset (proc, count);
  10521. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  10522. for (isize source_index = 0; source_index < count; source_index++) {
  10523. // TODO(bill): Order fields in source order not layout order
  10524. Entity *f = t->Struct.fields[source_index];
  10525. irValue *tip = ir_get_type_info_ptr(proc, f->type);
  10526. i64 foffset = 0;
  10527. if (!t->Struct.is_raw_union) {
  10528. foffset = t->Struct.offsets[f->Variable.field_index];
  10529. }
  10530. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  10531. irValue *index = ir_const_int(source_index);
  10532. irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
  10533. irValue *offset = ir_emit_ptr_offset(proc, memory_offsets, index);
  10534. irValue *is_using = ir_emit_ptr_offset(proc, memory_usings, index);
  10535. ir_emit_store(proc, type_info, ir_type_info(proc, f->type));
  10536. if (f->token.string.len > 0) {
  10537. irValue *name = ir_emit_ptr_offset(proc, memory_names, index);
  10538. ir_emit_store(proc, name, ir_const_string(proc->module, f->token.string));
  10539. }
  10540. ir_emit_store(proc, offset, ir_const_uintptr(foffset));
  10541. ir_emit_store(proc, is_using, ir_const_bool((f->flags&EntityFlag_Using) != 0));
  10542. if (t->Struct.tags.count > 0) {
  10543. String tag_string = t->Struct.tags[source_index];
  10544. if (tag_string.len > 0) {
  10545. irValue *tag_ptr = ir_emit_ptr_offset(proc, memory_tags, index);
  10546. ir_emit_store(proc, tag_ptr, ir_const_string(proc->module, tag_string));
  10547. }
  10548. }
  10549. }
  10550. irValue *cv = ir_const_int(count);
  10551. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 0), memory_types, cv);
  10552. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 1), memory_names, cv);
  10553. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 2), memory_offsets, cv);
  10554. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 3), memory_usings, cv);
  10555. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 4), memory_tags, cv);
  10556. }
  10557. break;
  10558. }
  10559. case Type_Map: {
  10560. ir_emit_comment(proc, str_lit("Type_Info_Map"));
  10561. tag = ir_emit_conv(proc, variant_ptr, t_type_info_map_ptr);
  10562. init_map_internal_types(t);
  10563. irValue *key = ir_emit_struct_ep(proc, tag, 0);
  10564. irValue *value = ir_emit_struct_ep(proc, tag, 1);
  10565. irValue *generated_struct = ir_emit_struct_ep(proc, tag, 2);
  10566. irValue *key_equal = ir_emit_struct_ep(proc, tag, 3);
  10567. irValue *key_hasher = ir_emit_struct_ep(proc, tag, 4);
  10568. ir_emit_store(proc, key, ir_get_type_info_ptr(proc, t->Map.key));
  10569. ir_emit_store(proc, value, ir_get_type_info_ptr(proc, t->Map.value));
  10570. ir_emit_store(proc, generated_struct, ir_get_type_info_ptr(proc, t->Map.generated_struct_type));
  10571. ir_emit_store(proc, key_equal, ir_get_equal_proc_for_type(proc->module, t->Map.key));
  10572. ir_emit_store(proc, key_hasher, ir_get_hasher_proc_for_type(proc->module, t->Map.key));
  10573. break;
  10574. }
  10575. case Type_BitField: {
  10576. ir_emit_comment(proc, str_lit("Type_Info_Bit_Field"));
  10577. tag = ir_emit_conv(proc, variant_ptr, t_type_info_bit_field_ptr);
  10578. // names: []string;
  10579. // bits: []u32;
  10580. // offsets: []u32;
  10581. isize count = t->BitField.fields.count;
  10582. if (count > 0) {
  10583. auto fields = t->BitField.fields;
  10584. irValue *name_array = ir_generate_array(m, t_string, count, str_lit("$bit_field_names"), cast(i64)entry_index);
  10585. irValue *bit_array = ir_generate_array(m, t_i32, count, str_lit("$bit_field_bits"), cast(i64)entry_index);
  10586. irValue *offset_array = ir_generate_array(m, t_i32, count, str_lit("$bit_field_offsets"), cast(i64)entry_index);
  10587. for (isize i = 0; i < count; i++) {
  10588. Entity *f = fields[i];
  10589. GB_ASSERT(f->type != nullptr);
  10590. GB_ASSERT(f->type->kind == Type_BitFieldValue);
  10591. irValue *name_ep = ir_emit_array_epi(proc, name_array, cast(i32)i);
  10592. irValue *bit_ep = ir_emit_array_epi(proc, bit_array, cast(i32)i);
  10593. irValue *offset_ep = ir_emit_array_epi(proc, offset_array, cast(i32)i);
  10594. ir_emit_store(proc, name_ep, ir_const_string(proc->module, f->token.string));
  10595. ir_emit_store(proc, bit_ep, ir_const_i32(f->type->BitFieldValue.bits));
  10596. ir_emit_store(proc, offset_ep, ir_const_i32(t->BitField.offsets[i]));
  10597. }
  10598. irValue *v_count = ir_const_int(count);
  10599. irValue *names = ir_emit_struct_ep(proc, tag, 0);
  10600. irValue *name_array_elem = ir_array_elem(proc, name_array);
  10601. ir_fill_slice(proc, names, name_array_elem, v_count);
  10602. irValue *bits = ir_emit_struct_ep(proc, tag, 1);
  10603. irValue *bit_array_elem = ir_array_elem(proc, bit_array);
  10604. ir_fill_slice(proc, bits, bit_array_elem, v_count);
  10605. irValue *offsets = ir_emit_struct_ep(proc, tag, 2);
  10606. irValue *offset_array_elem = ir_array_elem(proc, offset_array);
  10607. ir_fill_slice(proc, offsets, offset_array_elem, v_count);
  10608. }
  10609. break;
  10610. }
  10611. case Type_BitSet:
  10612. ir_emit_comment(proc, str_lit("Type_Info_Bit_Set"));
  10613. tag = ir_emit_conv(proc, variant_ptr, t_type_info_bit_set_ptr);
  10614. GB_ASSERT(is_type_typed(t->BitSet.elem));
  10615. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->BitSet.elem));
  10616. if (t->BitSet.underlying != nullptr) {
  10617. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), ir_get_type_info_ptr(proc, t->BitSet.underlying));
  10618. }
  10619. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 2), ir_const_i64(t->BitSet.lower));
  10620. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 3), ir_const_i64(t->BitSet.upper));
  10621. break;
  10622. case Type_Opaque:
  10623. ir_emit_comment(proc, str_lit("Type_Opaque"));
  10624. tag = ir_emit_conv(proc, variant_ptr, t_type_info_opaque_ptr);
  10625. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->Opaque.elem));
  10626. break;
  10627. case Type_SimdVector:
  10628. ir_emit_comment(proc, str_lit("Type_SimdVector"));
  10629. tag = ir_emit_conv(proc, variant_ptr, t_type_info_simd_vector_ptr);
  10630. if (t->SimdVector.is_x86_mmx) {
  10631. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 3), v_true);
  10632. } else {
  10633. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->SimdVector.elem));
  10634. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), ir_const_int(type_size_of(t->SimdVector.elem)));
  10635. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 2), ir_const_int(t->SimdVector.count));
  10636. }
  10637. break;
  10638. case Type_RelativePointer:
  10639. ir_emit_comment(proc, str_lit("Type_RelativePointer"));
  10640. tag = ir_emit_conv(proc, variant_ptr, t_type_info_relative_pointer_ptr);
  10641. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->RelativePointer.pointer_type));
  10642. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->RelativePointer.base_integer));
  10643. break;
  10644. case Type_RelativeSlice:
  10645. ir_emit_comment(proc, str_lit("Type_RelativeSlice"));
  10646. tag = ir_emit_conv(proc, variant_ptr, t_type_info_relative_slice_ptr);
  10647. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->RelativePointer.pointer_type));
  10648. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->RelativePointer.base_integer));
  10649. break;
  10650. }
  10651. if (tag != nullptr) {
  10652. Type *tag_type = type_deref(ir_type(tag));
  10653. GB_ASSERT(is_type_named(tag_type));
  10654. ir_emit_store_union_variant(proc, variant_ptr, ir_emit_load(proc, tag), tag_type);
  10655. } else {
  10656. if (t != t_llvm_bool) {
  10657. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  10658. }
  10659. }
  10660. }
  10661. }
  10662. void ir_gen_tree(irGen *s) {
  10663. irModule *m = &s->module;
  10664. CheckerInfo *info = m->info;
  10665. gbAllocator a = ir_allocator();
  10666. if (v_zero == nullptr) {
  10667. v_zero = ir_const_int (0);
  10668. v_one = ir_const_int (1);
  10669. v_zero32 = ir_const_i32 (0);
  10670. v_one32 = ir_const_i32 (1);
  10671. v_two32 = ir_const_i32 (2);
  10672. v_false = ir_const_bool(false);
  10673. v_true = ir_const_bool(true);
  10674. v_raw_nil = ir_value_constant(t_rawptr, exact_value_pointer(0));
  10675. }
  10676. isize global_variable_max_count = 0;
  10677. Entity *entry_point = info->entry_point;
  10678. bool has_dll_main = false;
  10679. bool has_win_main = false;
  10680. for_array(i, info->entities) {
  10681. Entity *e = info->entities[i];
  10682. String name = e->token.string;
  10683. bool is_global = e->pkg != nullptr;
  10684. if (e->kind == Entity_Variable) {
  10685. global_variable_max_count++;
  10686. } else if (e->kind == Entity_Procedure && !is_global) {
  10687. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  10688. GB_ASSERT(e == entry_point);
  10689. // entry_point = e;
  10690. }
  10691. if (e->Procedure.is_export ||
  10692. (e->Procedure.link_name.len > 0) ||
  10693. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  10694. if (!has_dll_main && name == "DllMain") {
  10695. has_dll_main = true;
  10696. } else if (!has_win_main && name == "WinMain") {
  10697. has_win_main = true;
  10698. }
  10699. }
  10700. }
  10701. }
  10702. struct irGlobalVariable {
  10703. irValue *var, *init;
  10704. DeclInfo *decl;
  10705. };
  10706. auto global_variables = array_make<irGlobalVariable>(m->tmp_allocator, 0, global_variable_max_count);
  10707. m->entry_point_entity = entry_point;
  10708. m->min_dep_set = info->minimum_dependency_set;
  10709. for_array(i, info->variable_init_order) {
  10710. DeclInfo *d = info->variable_init_order[i];
  10711. Entity *e = d->entity;
  10712. if ((e->scope->flags & ScopeFlag_File) == 0) {
  10713. continue;
  10714. }
  10715. if (!ir_min_dep_entity(m, e)) {
  10716. continue;
  10717. }
  10718. DeclInfo *decl = decl_info_of_entity(e);
  10719. if (decl == nullptr) {
  10720. continue;
  10721. }
  10722. GB_ASSERT(e->kind == Entity_Variable);
  10723. bool is_foreign = e->Variable.is_foreign;
  10724. bool is_export = e->Variable.is_export;
  10725. bool no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  10726. String name = e->token.string;
  10727. if (e->Variable.link_name.len > 0) {
  10728. name = e->Variable.link_name;
  10729. }
  10730. if (!no_name_mangle) {
  10731. name = ir_mangle_name(s, e);
  10732. }
  10733. ir_add_entity_name(m, e, name);
  10734. irValue *g = ir_value_global(e, nullptr);
  10735. g->Global.name = name;
  10736. g->Global.thread_local_model = e->Variable.thread_local_model;
  10737. g->Global.is_foreign = is_foreign;
  10738. g->Global.is_export = is_export;
  10739. irGlobalVariable var = {};
  10740. var.var = g;
  10741. var.decl = decl;
  10742. if (decl->init_expr != nullptr && !is_type_any(e->type)) {
  10743. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  10744. if (tav.mode != Addressing_Invalid) {
  10745. if (tav.value.kind != ExactValue_Invalid) {
  10746. ExactValue v = tav.value;
  10747. g->Global.value = ir_add_module_constant(m, tav.type, v);
  10748. }
  10749. }
  10750. }
  10751. array_add(&global_variables, var);
  10752. ir_module_add_value(m, e, g);
  10753. string_map_set(&m->members, name, g);
  10754. }
  10755. for_array(i, info->entities) {
  10756. Entity * e = info->entities[i];
  10757. String name = e->token.string;
  10758. DeclInfo *decl = e->decl_info;
  10759. Scope * scope = e->scope;
  10760. if ((scope->flags & ScopeFlag_File) == 0) {
  10761. continue;
  10762. }
  10763. Scope *package_scope = scope->parent;
  10764. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  10765. switch (e->kind) {
  10766. case Entity_Variable:
  10767. // NOTE(bill): Handled above as it requires a specific load order
  10768. continue;
  10769. case Entity_ProcGroup:
  10770. continue;
  10771. case Entity_Procedure:
  10772. break;
  10773. }
  10774. bool polymorphic_struct = false;
  10775. if (e->type != nullptr && e->kind == Entity_TypeName) {
  10776. Type *bt = base_type(e->type);
  10777. if (bt->kind == Type_Struct) {
  10778. polymorphic_struct = is_type_polymorphic(bt);
  10779. }
  10780. }
  10781. if (!polymorphic_struct && !ir_min_dep_entity(m, e)) {
  10782. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  10783. continue;
  10784. }
  10785. String original_name = name;
  10786. #if 0
  10787. if (!package_scope->is_global || polymorphic_struct || is_type_polymorphic(e->type)) {
  10788. if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  10789. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  10790. // Handle later
  10791. } else {
  10792. name = ir_mangle_name(s, e);
  10793. }
  10794. }
  10795. #else
  10796. if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  10797. // Okay
  10798. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  10799. // Handle later
  10800. } else {
  10801. name = ir_mangle_name(s, e);
  10802. }
  10803. #endif
  10804. ir_add_entity_name(m, e, name);
  10805. switch (e->kind) {
  10806. case Entity_TypeName:
  10807. ir_gen_global_type_name(m, e, name);
  10808. break;
  10809. case Entity_Procedure: {
  10810. ast_node(pl, ProcLit, decl->proc_lit);
  10811. String original_name = name;
  10812. Ast *body = pl->body;
  10813. if (e->Procedure.is_foreign) {
  10814. name = e->token.string; // NOTE(bill): Don't use the mangled name
  10815. ir_add_foreign_library_path(m, e->Procedure.foreign_library);
  10816. }
  10817. if (e->Procedure.link_name.len > 0) {
  10818. name = e->Procedure.link_name;
  10819. }
  10820. Ast *type_expr = pl->type;
  10821. set_procedure_abi_types(e->type);
  10822. irValue *p = ir_value_procedure(m, e, e->type, type_expr, body, name);
  10823. p->Proc.tags = pl->tags;
  10824. p->Proc.inlining = pl->inlining;
  10825. p->Proc.is_export = e->Procedure.is_export;
  10826. ir_module_add_value(m, e, p);
  10827. StringHashKey hash_name = string_hash_string(name);
  10828. if (string_map_get(&m->members, hash_name) == nullptr) {
  10829. string_map_set(&m->members, hash_name, p);
  10830. }
  10831. break;
  10832. }
  10833. }
  10834. }
  10835. for_array(i, m->members.entries) {
  10836. auto *entry = &m->members.entries[i];
  10837. irValue *v = entry->value;
  10838. if (v->kind == irValue_Proc) {
  10839. ir_build_proc(v, nullptr);
  10840. }
  10841. }
  10842. irDebugInfo *compile_unit = m->debug_info.entries[0].value;
  10843. GB_ASSERT(compile_unit->kind == irDebugInfo_CompileUnit);
  10844. for_array(i, m->info->required_foreign_imports_through_force) {
  10845. Entity *e = m->info->required_foreign_imports_through_force[i];
  10846. ir_add_foreign_library_path(m, e);
  10847. }
  10848. #if defined(GB_SYSTEM_WINDOWS)
  10849. if (build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main && !build_context.no_entry_point) {
  10850. // DllMain :: proc(inst: rawptr, reason: u32, reserved: rawptr) -> i32
  10851. String name = str_lit("DllMain");
  10852. Type *proc_params = alloc_type_tuple();
  10853. Type *proc_results = alloc_type_tuple();
  10854. Scope *proc_scope = gb_alloc_item(a, Scope);
  10855. array_init(&proc_params->Tuple.variables, a, 3);
  10856. array_init(&proc_results->Tuple.variables, a, 1);
  10857. proc_params->Tuple.variables[0] = alloc_entity_param(proc_scope, blank_token, t_rawptr, false, false);
  10858. proc_params->Tuple.variables[1] = alloc_entity_param(proc_scope, make_token_ident(str_lit("reason")), t_i32, false, false);
  10859. proc_params->Tuple.variables[2] = alloc_entity_param(proc_scope, blank_token, t_rawptr, false, false);
  10860. proc_results->Tuple.variables[0] = alloc_entity_param(proc_scope, empty_token, t_i32, false, false);
  10861. Type *proc_type = alloc_type_proc(proc_scope,
  10862. proc_params, 3,
  10863. proc_results, 1, false, ProcCC_StdCall);
  10864. // TODO(bill): make this more robust
  10865. proc_type->Proc.abi_compat_params = array_make<Type *>(a, proc_params->Tuple.variables.count);
  10866. for_array(i, proc_params->Tuple.variables) {
  10867. proc_type->Proc.abi_compat_params[i] = proc_params->Tuple.variables[i]->type;
  10868. }
  10869. proc_type->Proc.abi_compat_result_type = proc_results->Tuple.variables[0]->type;
  10870. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  10871. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(name), proc_type, 0);
  10872. irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  10873. p->Proc.is_startup = true;
  10874. map_set(&m->values, hash_entity(e), p);
  10875. string_map_set(&m->members, name, p);
  10876. irProcedure *proc = &p->Proc;
  10877. proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
  10878. proc->is_entry_point = true;
  10879. e->Procedure.link_name = name;
  10880. ir_begin_procedure_body(proc);
  10881. defer (ir_end_procedure_body(proc));
  10882. // NOTE(bill): https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
  10883. // DLL_PROCESS_ATTACH == 1
  10884. irAddr reason_addr = ir_build_addr_from_entity(proc, proc_params->Tuple.variables[1], nullptr);
  10885. irValue *cond = ir_emit_comp(proc, Token_CmpEq, ir_addr_load(proc, reason_addr), v_one32);
  10886. irBlock *then = ir_new_block(proc, nullptr, "if.then");
  10887. irBlock *done = ir_new_block(proc, nullptr, "if.done"); // NOTE(bill): Append later
  10888. ir_emit_if(proc, cond, then, done);
  10889. ir_start_block(proc, then);
  10890. {
  10891. irValue **found = map_get(&m->values, hash_entity(entry_point));
  10892. ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
  10893. if (found != nullptr) {
  10894. Array<irValue *> args = {};
  10895. ir_emit_call(proc, *found, args);
  10896. }
  10897. }
  10898. ir_emit_jump(proc, done);
  10899. ir_start_block(proc, done);
  10900. ir_emit_return(proc, v_one32);
  10901. }
  10902. #endif
  10903. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main) && !build_context.no_entry_point) {
  10904. // main :: proc(argc: i32, argv: ^^u8) -> i32
  10905. String name = str_lit("main");
  10906. #if 0
  10907. if (str_eq_ignore_case(cross_compile_target, str_lit("Essence"))) {
  10908. // This is a bit hacky,
  10909. // because this makes this function the first function run in the executable
  10910. // so it won't actually have the argc/argv arguments.
  10911. name = str_lit("ProgramEntry");
  10912. }
  10913. #endif
  10914. Type *proc_params = alloc_type_tuple();
  10915. Type *proc_results = alloc_type_tuple();
  10916. Scope *proc_scope = gb_alloc_item(a, Scope);
  10917. array_init(&proc_params->Tuple.variables, a, 2);
  10918. array_init(&proc_results->Tuple.variables, a, 1);
  10919. Type *cstring_ptr = alloc_type_pointer(t_cstring);
  10920. proc_params->Tuple.variables[0] = alloc_entity_param(proc_scope, make_token_ident(str_lit("argc")), t_i32, false, false);
  10921. proc_params->Tuple.variables[1] = alloc_entity_param(proc_scope, make_token_ident(str_lit("argv")), cstring_ptr, false, false);
  10922. proc_results->Tuple.variables[0] = alloc_entity_param(proc_scope, empty_token, t_i32, false, false);
  10923. Type *proc_type = alloc_type_proc(proc_scope,
  10924. proc_params, 2,
  10925. proc_results, 1, false, ProcCC_CDecl);
  10926. // TODO(bill): make this more robust
  10927. proc_type->Proc.abi_compat_params = array_make<Type *>(a, proc_params->Tuple.variables.count);
  10928. for_array(i, proc_params->Tuple.variables) {
  10929. proc_type->Proc.abi_compat_params[i] = proc_params->Tuple.variables[i]->type;
  10930. }
  10931. proc_type->Proc.abi_compat_result_type = proc_results->Tuple.variables[0]->type;
  10932. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  10933. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(name), proc_type, 0);
  10934. irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  10935. p->Proc.is_startup = true;
  10936. map_set(&m->values, hash_entity(e), p);
  10937. string_map_set(&m->members, name, p);
  10938. irProcedure *proc = &p->Proc;
  10939. proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
  10940. proc->is_entry_point = true;
  10941. e->Procedure.link_name = name;
  10942. ir_begin_procedure_body(proc);
  10943. defer (ir_end_procedure_body(proc));
  10944. // NOTE(bill): https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
  10945. // DLL_PROCESS_ATTACH == 1
  10946. irValue *argc = ir_emit_load(proc, *map_get(&proc->module->values, hash_entity(proc_params->Tuple.variables[0])));
  10947. irValue *argv = ir_emit_load(proc, *map_get(&proc->module->values, hash_entity(proc_params->Tuple.variables[1])));
  10948. irValue *global_args = ir_find_global_variable(proc, str_lit("args__"));
  10949. ir_fill_slice(proc, global_args, argv, ir_emit_conv(proc, argc, t_int));
  10950. ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
  10951. Array<irValue *> empty_args = {};
  10952. if (build_context.command_kind == Command_test) {
  10953. for_array(i, m->info->testing_procedures) {
  10954. Entity *e = m->info->testing_procedures[i];
  10955. irValue **found = map_get(&proc->module->values, hash_entity(e));
  10956. GB_ASSERT(found != nullptr);
  10957. ir_emit_call(proc, *found, empty_args);
  10958. }
  10959. } else {
  10960. irValue **found = map_get(&proc->module->values, hash_entity(entry_point));
  10961. if (found != nullptr) {
  10962. ir_emit_call(proc, *found, empty_args);
  10963. }
  10964. }
  10965. ir_emit_return(proc, v_zero32);
  10966. }
  10967. #if defined(GB_SYSTEM_WINDOWS)
  10968. if (build_context.build_mode != BuildMode_DynamicLibrary && build_context.no_crt && !build_context.no_entry_point) {
  10969. s->print_chkstk = true;
  10970. {
  10971. // void mainCRTStartup(void)
  10972. String name = str_lit("mainCRTStartup");
  10973. Type *proc_params = alloc_type_tuple();
  10974. Type *proc_results = alloc_type_tuple();
  10975. Type *proc_type = alloc_type_proc(nullptr,
  10976. nullptr, 0,
  10977. nullptr, 0,
  10978. false,
  10979. ProcCC_StdCall);
  10980. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  10981. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(name), proc_type, 0);
  10982. irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  10983. p->Proc.is_startup = true;
  10984. m->entry_point_entity = e;
  10985. map_set(&m->values, hash_entity(e), p);
  10986. string_map_set(&m->members, name, p);
  10987. irProcedure *proc = &p->Proc;
  10988. // proc->tags = ProcTag_no_inline; // TODO(bill): is no_inline a good idea?
  10989. e->Procedure.link_name = name;
  10990. ir_begin_procedure_body(proc);
  10991. ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
  10992. irValue **found = map_get(&proc->module->values, hash_entity(entry_point));
  10993. if (found != nullptr) {
  10994. Array<irValue *> args = {};
  10995. ir_emit_call(proc, *found, args);
  10996. }
  10997. ir_end_procedure_body(proc);
  10998. }
  10999. }
  11000. #endif
  11001. irValue *startup_type_info = nullptr;
  11002. { // Startup Type Info
  11003. // Cleanup(bill): probably better way of doing code insertion
  11004. String name = str_lit(IR_STARTUP_TYPE_INFO_PROC_NAME);
  11005. Type *proc_type = alloc_type_proc(gb_alloc_item(a, Scope),
  11006. nullptr, 0,
  11007. nullptr, 0, false,
  11008. ProcCC_Contextless);
  11009. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  11010. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(name), proc_type, 0);
  11011. irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  11012. p->Proc.is_startup = true;
  11013. startup_type_info = p;
  11014. map_set(&m->values, hash_entity(e), p);
  11015. string_map_set(&m->members, name, p);
  11016. irProcedure *proc = &p->Proc;
  11017. proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
  11018. ir_begin_procedure_body(proc);
  11019. ir_setup_type_info_data(proc);
  11020. ir_end_procedure_body(proc);
  11021. }
  11022. { // Startup Runtime
  11023. // Cleanup(bill): probably better way of doing code insertion
  11024. String name = str_lit(IR_STARTUP_RUNTIME_PROC_NAME);
  11025. Type *proc_type = alloc_type_proc(gb_alloc_item(a, Scope),
  11026. nullptr, 0,
  11027. nullptr, 0, false,
  11028. ProcCC_Contextless);
  11029. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  11030. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(name), proc_type, 0);
  11031. irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  11032. p->Proc.is_startup = true;
  11033. map_set(&m->values, hash_entity(e), p);
  11034. string_map_set(&m->members, name, p);
  11035. irProcedure *proc = &p->Proc;
  11036. proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
  11037. ir_begin_procedure_body(proc);
  11038. defer (ir_end_procedure_body(proc));
  11039. ir_emit(proc, ir_instr_call(proc, startup_type_info, nullptr, {}, nullptr, nullptr, ProcInlining_none));
  11040. for_array(i, global_variables) {
  11041. irGlobalVariable *var = &global_variables[i];
  11042. if (var->decl->init_expr != nullptr) {
  11043. var->init = ir_build_expr(proc, var->decl->init_expr);
  11044. }
  11045. Entity *e = var->var->Global.entity;
  11046. GB_ASSERT(e->kind == Entity_Variable);
  11047. if (e->Variable.is_foreign) {
  11048. Entity *fl = e->Procedure.foreign_library;
  11049. ir_add_foreign_library_path(m, fl);
  11050. }
  11051. if (e->flags & EntityFlag_Static) {
  11052. var->var->Global.is_internal = true;
  11053. }
  11054. if (var->init != nullptr) {
  11055. Type *t = type_deref(ir_type(var->var));
  11056. if (is_type_any(t)) {
  11057. // NOTE(bill): Edge case for 'any' type
  11058. Type *var_type = default_type(ir_type(var->init));
  11059. irValue *g = ir_add_global_generated(proc->module, var_type, var->init);
  11060. ir_emit_store(proc, g, var->init);
  11061. irValue *data = ir_emit_struct_ep(proc, var->var, 0);
  11062. irValue *ti = ir_emit_struct_ep(proc, var->var, 1);
  11063. ir_emit_store(proc, data, ir_emit_conv(proc, g, t_rawptr));
  11064. ir_emit_store(proc, ti, ir_type_info(proc, var_type));
  11065. } else {
  11066. ir_emit_store(proc, var->var, ir_emit_conv(proc, var->init, t));
  11067. }
  11068. }
  11069. }
  11070. }
  11071. for_array(i, m->procs_to_generate) {
  11072. irValue *p = m->procs_to_generate[i];
  11073. ir_build_proc(p, p->Proc.parent);
  11074. }
  11075. GB_ASSERT_MSG(m->debug_location_stack.count == 0, "Debug location stack contains unpopped entries.");
  11076. // Number debug info
  11077. for_array(i, m->debug_info.entries) {
  11078. auto *entry = &m->debug_info.entries[i];
  11079. irDebugInfo *di = entry->value;
  11080. di->id = cast(i32)(i+1);
  11081. }
  11082. // m->layout = str_lit("e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64");
  11083. }