llvm_backend.cpp 479 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324
  1. #define MULTITHREAD_OBJECT_GENERATION 1
  2. #ifndef USE_SEPARTE_MODULES
  3. #define USE_SEPARTE_MODULES build_context.use_separate_modules
  4. #endif
  5. #ifndef MULTITHREAD_OBJECT_GENERATION
  6. #define MULTITHREAD_OBJECT_GENERATION 0
  7. #endif
  8. #include "llvm_backend.hpp"
  9. #include "llvm_abi.cpp"
  10. #include "llvm_backend_opt.cpp"
  11. gb_global ThreadPool lb_thread_pool = {};
  12. gb_global Entity *lb_global_type_info_data_entity = {};
  13. gb_global lbAddr lb_global_type_info_member_types = {};
  14. gb_global lbAddr lb_global_type_info_member_names = {};
  15. gb_global lbAddr lb_global_type_info_member_offsets = {};
  16. gb_global lbAddr lb_global_type_info_member_usings = {};
  17. gb_global lbAddr lb_global_type_info_member_tags = {};
  18. gb_global isize lb_global_type_info_data_index = 0;
  19. gb_global isize lb_global_type_info_member_types_index = 0;
  20. gb_global isize lb_global_type_info_member_names_index = 0;
  21. gb_global isize lb_global_type_info_member_offsets_index = 0;
  22. gb_global isize lb_global_type_info_member_usings_index = 0;
  23. gb_global isize lb_global_type_info_member_tags_index = 0;
  24. lbValue lb_global_type_info_data_ptr(lbModule *m) {
  25. lbValue v = lb_find_value_from_entity(m, lb_global_type_info_data_entity);
  26. return v;
  27. }
  28. struct lbLoopData {
  29. lbAddr idx_addr;
  30. lbValue idx;
  31. lbBlock *body;
  32. lbBlock *done;
  33. lbBlock *loop;
  34. };
  35. struct lbCompoundLitElemTempData {
  36. Ast * expr;
  37. lbValue value;
  38. i32 elem_index;
  39. lbValue gep;
  40. };
  41. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32);
  42. void lb_loop_end(lbProcedure *p, lbLoopData const &data);
  43. LLVMValueRef llvm_zero(lbModule *m) {
  44. return LLVMConstInt(lb_type(m, t_int), 0, false);
  45. }
  46. LLVMValueRef llvm_zero32(lbModule *m) {
  47. return LLVMConstInt(lb_type(m, t_i32), 0, false);
  48. }
  49. LLVMValueRef llvm_one(lbModule *m) {
  50. return LLVMConstInt(lb_type(m, t_i32), 1, false);
  51. }
  52. lbValue lb_zero(lbModule *m, Type *t) {
  53. lbValue v = {};
  54. v.value = LLVMConstInt(lb_type(m, t), 0, false);
  55. v.type = t;
  56. return v;
  57. }
  58. LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  59. lbValue v = lb_find_or_add_entity_string(m, str);
  60. unsigned indices[1] = {0};
  61. return LLVMConstExtractValue(v.value, indices, gb_count_of(indices));
  62. }
  63. bool lb_is_instr_terminating(LLVMValueRef instr) {
  64. if (instr != nullptr) {
  65. LLVMOpcode op = LLVMGetInstructionOpcode(instr);
  66. switch (op) {
  67. case LLVMRet:
  68. case LLVMBr:
  69. case LLVMSwitch:
  70. case LLVMIndirectBr:
  71. case LLVMInvoke:
  72. case LLVMUnreachable:
  73. case LLVMCallBr:
  74. return true;
  75. }
  76. }
  77. return false;
  78. }
  79. lbModule *lb_pkg_module(lbGenerator *gen, AstPackage *pkg) {
  80. auto *found = map_get(&gen->modules, hash_pointer(pkg));
  81. if (found) {
  82. return *found;
  83. }
  84. return &gen->default_module;
  85. }
  86. lbAddr lb_addr(lbValue addr) {
  87. lbAddr v = {lbAddr_Default, addr};
  88. if (addr.type != nullptr && is_type_relative_pointer(type_deref(addr.type))) {
  89. GB_ASSERT(is_type_pointer(addr.type));
  90. v.kind = lbAddr_RelativePointer;
  91. } else if (addr.type != nullptr && is_type_relative_slice(type_deref(addr.type))) {
  92. GB_ASSERT(is_type_pointer(addr.type));
  93. v.kind = lbAddr_RelativeSlice;
  94. }
  95. return v;
  96. }
  97. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  98. lbAddr v = {lbAddr_Map, addr};
  99. v.map.key = map_key;
  100. v.map.type = map_type;
  101. v.map.result = map_result;
  102. return v;
  103. }
  104. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  105. lbAddr v = {lbAddr_SoaVariable, addr};
  106. v.soa.index = index;
  107. v.soa.index_expr = index_expr;
  108. return v;
  109. }
  110. Type *lb_addr_type(lbAddr const &addr) {
  111. if (addr.addr.value == nullptr) {
  112. return nullptr;
  113. }
  114. if (addr.kind == lbAddr_Map) {
  115. Type *t = base_type(addr.map.type);
  116. GB_ASSERT(is_type_map(t));
  117. return t->Map.value;
  118. }
  119. return type_deref(addr.addr.type);
  120. }
  121. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  122. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  123. }
  124. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  125. if (addr.addr.value == nullptr) {
  126. GB_PANIC("Illegal addr -> nullptr");
  127. return {};
  128. }
  129. switch (addr.kind) {
  130. case lbAddr_Map: {
  131. Type *map_type = base_type(addr.map.type);
  132. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  133. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  134. auto args = array_make<lbValue>(permanent_allocator(), 2);
  135. args[0] = h;
  136. args[1] = key;
  137. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  138. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  139. }
  140. case lbAddr_RelativePointer: {
  141. Type *rel_ptr = base_type(lb_addr_type(addr));
  142. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  143. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  144. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  145. offset = lb_emit_load(p, offset);
  146. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  147. offset = lb_emit_conv(p, offset, t_i64);
  148. }
  149. offset = lb_emit_conv(p, offset, t_uintptr);
  150. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  151. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  152. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  153. // NOTE(bill): nil check
  154. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  155. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  156. return final_ptr;
  157. }
  158. case lbAddr_SoaVariable: {
  159. // TODO(bill): FIX THIS HACK
  160. return lb_address_from_load(p, lb_addr_load(p, addr));
  161. }
  162. case lbAddr_Context:
  163. GB_PANIC("lbAddr_Context should be handled elsewhere");
  164. }
  165. return addr.addr;
  166. }
  167. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  168. lbAddr addr = lb_build_addr(p, expr);
  169. return lb_addr_get_ptr(p, addr);
  170. }
  171. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  172. if (build_context.no_bounds_check) {
  173. return;
  174. }
  175. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  176. return;
  177. }
  178. index = lb_emit_conv(p, index, t_int);
  179. len = lb_emit_conv(p, len, t_int);
  180. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  181. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  182. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  183. auto args = array_make<lbValue>(permanent_allocator(), 5);
  184. args[0] = file;
  185. args[1] = line;
  186. args[2] = column;
  187. args[3] = index;
  188. args[4] = len;
  189. lb_emit_runtime_call(p, "bounds_check_error", args);
  190. }
  191. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  192. if (build_context.no_bounds_check) {
  193. return;
  194. }
  195. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  196. return;
  197. }
  198. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  199. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  200. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  201. high = lb_emit_conv(p, high, t_int);
  202. if (!lower_value_used) {
  203. auto args = array_make<lbValue>(permanent_allocator(), 5);
  204. args[0] = file;
  205. args[1] = line;
  206. args[2] = column;
  207. args[3] = high;
  208. args[4] = len;
  209. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  210. } else {
  211. // No need to convert unless used
  212. low = lb_emit_conv(p, low, t_int);
  213. auto args = array_make<lbValue>(permanent_allocator(), 6);
  214. args[0] = file;
  215. args[1] = line;
  216. args[2] = column;
  217. args[3] = low;
  218. args[4] = high;
  219. args[5] = len;
  220. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  221. }
  222. }
  223. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  224. if (addr.addr.value == nullptr) {
  225. return;
  226. }
  227. GB_ASSERT(value.type != nullptr);
  228. if (is_type_untyped_undef(value.type)) {
  229. Type *t = lb_addr_type(addr);
  230. value.type = t;
  231. value.value = LLVMGetUndef(lb_type(p->module, t));
  232. } else if (is_type_untyped_nil(value.type)) {
  233. Type *t = lb_addr_type(addr);
  234. value.type = t;
  235. value.value = LLVMConstNull(lb_type(p->module, t));
  236. }
  237. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  238. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  239. }
  240. if (addr.kind == lbAddr_RelativePointer) {
  241. Type *rel_ptr = base_type(lb_addr_type(addr));
  242. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  243. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  244. GB_ASSERT(is_type_pointer(addr.addr.type));
  245. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  246. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  247. lbValue offset = {};
  248. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  249. offset.type = t_uintptr;
  250. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  251. offset = lb_emit_conv(p, offset, t_i64);
  252. }
  253. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  254. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  255. offset = lb_emit_select(p,
  256. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  257. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  258. offset
  259. );
  260. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  261. return;
  262. } else if (addr.kind == lbAddr_RelativeSlice) {
  263. Type *rel_ptr = base_type(lb_addr_type(addr));
  264. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  265. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  266. GB_ASSERT(is_type_pointer(addr.addr.type));
  267. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  268. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  269. lbValue offset = {};
  270. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  271. offset.type = t_uintptr;
  272. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  273. offset = lb_emit_conv(p, offset, t_i64);
  274. }
  275. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  276. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  277. offset = lb_emit_select(p,
  278. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  279. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  280. offset
  281. );
  282. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  283. lbValue len = lb_slice_len(p, value);
  284. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  285. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  286. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  287. return;
  288. } else if (addr.kind == lbAddr_AtomOp_index_set) {
  289. lbValue ptr = addr.addr;
  290. lbValue index = addr.index_set.index;
  291. Ast *node = addr.index_set.node;
  292. ast_node(ce, CallExpr, node);
  293. Type *proc_type = type_and_value_of_expr(ce->proc).type;
  294. proc_type = base_type(proc_type);
  295. GB_ASSERT(is_type_proc(proc_type));
  296. TypeProc *pt = &proc_type->Proc;
  297. isize arg_count = 3;
  298. isize param_count = 0;
  299. if (pt->params) {
  300. GB_ASSERT(pt->params->kind == Type_Tuple);
  301. param_count = pt->params->Tuple.variables.count;
  302. }
  303. auto args = array_make<lbValue>(permanent_allocator(), gb_max(arg_count, param_count));
  304. args[0] = ptr;
  305. args[1] = index;
  306. args[2] = value;
  307. isize arg_index = arg_count;
  308. if (arg_count < param_count) {
  309. lbModule *m = p->module;
  310. String proc_name = {};
  311. if (p->entity != nullptr) {
  312. proc_name = p->entity->token.string;
  313. }
  314. TokenPos pos = ast_token(ce->proc).pos;
  315. TypeTuple *param_tuple = &pt->params->Tuple;
  316. isize end = cast(isize)param_count;
  317. while (arg_index < end) {
  318. Entity *e = param_tuple->variables[arg_index];
  319. GB_ASSERT(e->kind == Entity_Variable);
  320. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, pos);
  321. }
  322. }
  323. Entity *e = entity_from_expr(ce->proc);
  324. GB_ASSERT(e != nullptr);
  325. GB_ASSERT(is_type_polymorphic(e->type));
  326. {
  327. lb_emit_call(p, lb_find_procedure_value_from_entity(p->module, e), args);
  328. }
  329. return;
  330. } else if (addr.kind == lbAddr_Map) {
  331. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  332. return;
  333. } else if (addr.kind == lbAddr_Context) {
  334. lbAddr old_addr = lb_find_or_generate_context_ptr(p);
  335. // IMPORTANT NOTE(bill, 2021-04-22): reuse unused 'context' variables to minimize stack usage
  336. // This has to be done manually since the optimizer cannot determine when this is possible
  337. bool create_new = true;
  338. for_array(i, p->context_stack) {
  339. lbContextData *ctx_data = &p->context_stack[i];
  340. if (ctx_data->ctx.addr.value == old_addr.addr.value) {
  341. if (ctx_data->uses > 0) {
  342. create_new = true;
  343. } else if (p->scope_index > ctx_data->scope_index) {
  344. create_new = true;
  345. } else {
  346. // gb_printf_err("%.*s (curr:%td) (ctx:%td) (uses:%td)\n", LIT(p->name), p->scope_index, ctx_data->scope_index, ctx_data->uses);
  347. create_new = false;
  348. }
  349. break;
  350. }
  351. }
  352. lbValue next = {};
  353. if (create_new) {
  354. lbValue old = lb_addr_load(p, old_addr);
  355. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  356. lb_addr_store(p, next_addr, old);
  357. lb_push_context_onto_stack(p, next_addr);
  358. next = next_addr.addr;
  359. } else {
  360. next = old_addr.addr;
  361. }
  362. if (addr.ctx.sel.index.count > 0) {
  363. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  364. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  365. lb_emit_store(p, lhs, rhs);
  366. } else {
  367. lbValue lhs = next;
  368. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  369. lb_emit_store(p, lhs, rhs);
  370. }
  371. return;
  372. } else if (addr.kind == lbAddr_SoaVariable) {
  373. Type *t = type_deref(addr.addr.type);
  374. t = base_type(t);
  375. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  376. Type *elem_type = t->Struct.soa_elem;
  377. value = lb_emit_conv(p, value, elem_type);
  378. elem_type = base_type(elem_type);
  379. lbValue index = addr.soa.index;
  380. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  381. Type *t = base_type(type_deref(addr.addr.type));
  382. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  383. lbValue len = lb_soa_struct_len(p, addr.addr);
  384. if (addr.soa.index_expr != nullptr) {
  385. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  386. }
  387. }
  388. isize field_count = 0;
  389. switch (elem_type->kind) {
  390. case Type_Struct:
  391. field_count = elem_type->Struct.fields.count;
  392. break;
  393. case Type_Array:
  394. field_count = elem_type->Array.count;
  395. break;
  396. }
  397. for (isize i = 0; i < field_count; i++) {
  398. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  399. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  400. if (t->Struct.soa_kind == StructSoa_Fixed) {
  401. dst = lb_emit_array_ep(p, dst, index);
  402. lb_emit_store(p, dst, src);
  403. } else {
  404. lbValue field = lb_emit_load(p, dst);
  405. dst = lb_emit_ptr_offset(p, field, index);
  406. lb_emit_store(p, dst, src);
  407. }
  408. }
  409. return;
  410. }
  411. GB_ASSERT(value.value != nullptr);
  412. value = lb_emit_conv(p, value, lb_addr_type(addr));
  413. // if (lb_is_const_or_global(value)) {
  414. // // NOTE(bill): Just bypass the actual storage and set the initializer
  415. // if (LLVMGetValueKind(addr.addr.value) == LLVMGlobalVariableValueKind) {
  416. // LLVMValueRef dst = addr.addr.value;
  417. // LLVMValueRef src = value.value;
  418. // LLVMSetInitializer(dst, src);
  419. // return;
  420. // }
  421. // }
  422. lb_emit_store(p, addr.addr, value);
  423. }
  424. void lb_const_store(lbValue ptr, lbValue value) {
  425. GB_ASSERT(lb_is_const(ptr));
  426. GB_ASSERT(lb_is_const(value));
  427. GB_ASSERT(is_type_pointer(ptr.type));
  428. LLVMSetInitializer(ptr.value, value.value);
  429. }
  430. bool lb_is_type_proc_recursive(Type *t) {
  431. for (;;) {
  432. if (t == nullptr) {
  433. return false;
  434. }
  435. switch (t->kind) {
  436. case Type_Named:
  437. t = t->Named.base;
  438. break;
  439. case Type_Pointer:
  440. t = t->Pointer.elem;
  441. break;
  442. case Type_Array:
  443. t = t->Array.elem;
  444. break;
  445. case Type_EnumeratedArray:
  446. t = t->EnumeratedArray.elem;
  447. break;
  448. case Type_Slice:
  449. t = t->Slice.elem;
  450. break;
  451. case Type_DynamicArray:
  452. t = t->DynamicArray.elem;
  453. break;
  454. case Type_Proc:
  455. return true;
  456. default:
  457. return false;
  458. }
  459. }
  460. }
  461. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  462. GB_ASSERT(value.value != nullptr);
  463. Type *a = type_deref(ptr.type);
  464. if (is_type_boolean(a)) {
  465. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  466. value = lb_emit_conv(p, value, a);
  467. }
  468. Type *ca = core_type(a);
  469. if (ca->kind == Type_Basic) {
  470. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  471. }
  472. if (lb_is_type_proc_recursive(a)) {
  473. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  474. // stored as regular pointer with no procedure information
  475. LLVMTypeRef src_t = LLVMGetElementType(LLVMTypeOf(ptr.value));
  476. LLVMValueRef v = LLVMBuildPointerCast(p->builder, value.value, src_t, "");
  477. LLVMBuildStore(p->builder, v, ptr.value);
  478. } else {
  479. Type *ca = core_type(a);
  480. if (ca->kind == Type_Basic || ca->kind == Type_Proc) {
  481. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  482. } else {
  483. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  484. }
  485. LLVMBuildStore(p->builder, value.value, ptr.value);
  486. }
  487. }
  488. LLVMTypeRef llvm_addr_type(lbValue addr_val) {
  489. return LLVMGetElementType(LLVMTypeOf(addr_val.value));
  490. }
  491. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  492. lbModule *m = p->module;
  493. GB_ASSERT(value.value != nullptr);
  494. GB_ASSERT(is_type_pointer(value.type));
  495. Type *t = type_deref(value.type);
  496. LLVMValueRef v = LLVMBuildLoad2(p->builder, llvm_addr_type(value), value.value, "");
  497. return lbValue{v, t};
  498. }
  499. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  500. GB_ASSERT(addr.addr.value != nullptr);
  501. if (addr.kind == lbAddr_RelativePointer) {
  502. Type *rel_ptr = base_type(lb_addr_type(addr));
  503. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  504. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  505. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  506. offset = lb_emit_load(p, offset);
  507. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  508. offset = lb_emit_conv(p, offset, t_i64);
  509. }
  510. offset = lb_emit_conv(p, offset, t_uintptr);
  511. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  512. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  513. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  514. // NOTE(bill): nil check
  515. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  516. lbValue final_ptr = {};
  517. final_ptr.type = absolute_ptr.type;
  518. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  519. return lb_emit_load(p, final_ptr);
  520. } else if (addr.kind == lbAddr_RelativeSlice) {
  521. Type *rel_ptr = base_type(lb_addr_type(addr));
  522. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  523. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  524. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  525. lbValue offset = lb_emit_load(p, offset_ptr);
  526. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  527. offset = lb_emit_conv(p, offset, t_i64);
  528. }
  529. offset = lb_emit_conv(p, offset, t_uintptr);
  530. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  531. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  532. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  533. Type *slice_elem = slice_type->Slice.elem;
  534. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  535. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  536. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  537. // NOTE(bill): nil check
  538. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  539. lbValue data = {};
  540. data.type = absolute_ptr.type;
  541. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  542. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  543. len = lb_emit_conv(p, len, t_int);
  544. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  545. lb_fill_slice(p, slice, data, len);
  546. return lb_addr_load(p, slice);
  547. } else if (addr.kind == lbAddr_Map) {
  548. Type *map_type = base_type(addr.map.type);
  549. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  550. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  551. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  552. auto args = array_make<lbValue>(permanent_allocator(), 2);
  553. args[0] = h;
  554. args[1] = key;
  555. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  556. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  557. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  558. lbBlock *then = lb_create_block(p, "map.get.then");
  559. lbBlock *done = lb_create_block(p, "map.get.done");
  560. lb_emit_if(p, ok, then, done);
  561. lb_start_block(p, then);
  562. {
  563. // TODO(bill): mem copy it instead?
  564. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  565. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  566. lb_emit_store(p, gep0, lb_emit_load(p, value));
  567. }
  568. lb_emit_jump(p, done);
  569. lb_start_block(p, done);
  570. if (is_type_tuple(addr.map.result)) {
  571. return lb_addr_load(p, v);
  572. } else {
  573. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  574. return lb_emit_load(p, single);
  575. }
  576. } else if (addr.kind == lbAddr_Context) {
  577. lbValue a = addr.addr;
  578. for_array(i, p->context_stack) {
  579. lbContextData *ctx_data = &p->context_stack[i];
  580. if (ctx_data->ctx.addr.value == a.value) {
  581. ctx_data->uses += 1;
  582. break;
  583. }
  584. }
  585. a.value = LLVMBuildPointerCast(p->builder, a.value, lb_type(p->module, t_context_ptr), "");
  586. if (addr.ctx.sel.index.count > 0) {
  587. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  588. return lb_emit_load(p, b);
  589. } else {
  590. return lb_emit_load(p, a);
  591. }
  592. } else if (addr.kind == lbAddr_SoaVariable) {
  593. Type *t = type_deref(addr.addr.type);
  594. t = base_type(t);
  595. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  596. Type *elem = t->Struct.soa_elem;
  597. lbValue len = {};
  598. if (t->Struct.soa_kind == StructSoa_Fixed) {
  599. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  600. } else {
  601. lbValue v = lb_emit_load(p, addr.addr);
  602. len = lb_soa_struct_len(p, v);
  603. }
  604. lbAddr res = lb_add_local_generated(p, elem, true);
  605. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  606. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  607. }
  608. if (t->Struct.soa_kind == StructSoa_Fixed) {
  609. for_array(i, t->Struct.fields) {
  610. Entity *field = t->Struct.fields[i];
  611. Type *base_type = field->type;
  612. GB_ASSERT(base_type->kind == Type_Array);
  613. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  614. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  615. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  616. lbValue src = lb_emit_load(p, src_ptr);
  617. lb_emit_store(p, dst, src);
  618. }
  619. } else {
  620. isize field_count = t->Struct.fields.count;
  621. if (t->Struct.soa_kind == StructSoa_Slice) {
  622. field_count -= 1;
  623. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  624. field_count -= 3;
  625. }
  626. for (isize i = 0; i < field_count; i++) {
  627. Entity *field = t->Struct.fields[i];
  628. Type *base_type = field->type;
  629. GB_ASSERT(base_type->kind == Type_Pointer);
  630. Type *elem = base_type->Pointer.elem;
  631. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  632. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  633. lbValue src = lb_emit_load(p, src_ptr);
  634. src = lb_emit_ptr_offset(p, src, addr.soa.index);
  635. src = lb_emit_load(p, src);
  636. lb_emit_store(p, dst, src);
  637. }
  638. }
  639. return lb_addr_load(p, res);
  640. }
  641. if (is_type_proc(addr.addr.type)) {
  642. return addr.addr;
  643. }
  644. return lb_emit_load(p, addr.addr);
  645. }
  646. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  647. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  648. }
  649. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  650. Type *t = u.type;
  651. GB_ASSERT_MSG(is_type_pointer(t) &&
  652. is_type_union(type_deref(t)), "%s", type_to_string(t));
  653. Type *ut = type_deref(t);
  654. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  655. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  656. GB_ASSERT(type_size_of(ut) > 0);
  657. Type *tag_type = union_tag_type(ut);
  658. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  659. unsigned element_count = LLVMCountStructElementTypes(uvt);
  660. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  661. lbValue tag_ptr = {};
  662. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  663. tag_ptr.type = alloc_type_pointer(tag_type);
  664. return tag_ptr;
  665. }
  666. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  667. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  668. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  669. return lb_emit_load(p, tag_ptr);
  670. }
  671. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  672. Type *t = type_deref(parent.type);
  673. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  674. // No tag needed!
  675. } else {
  676. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  677. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  678. }
  679. }
  680. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  681. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  682. lb_emit_store(p, underlying, variant);
  683. lb_emit_store_union_variant_tag(p, parent, variant_type);
  684. }
  685. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  686. unsigned field_count = LLVMCountStructElementTypes(src);
  687. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  688. LLVMGetStructElementTypes(src, fields);
  689. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  690. }
  691. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  692. switch (alignment) {
  693. case 1:
  694. return LLVMArrayType(lb_type(m, t_u8), 0);
  695. case 2:
  696. return LLVMArrayType(lb_type(m, t_u16), 0);
  697. case 4:
  698. return LLVMArrayType(lb_type(m, t_u32), 0);
  699. case 8:
  700. return LLVMArrayType(lb_type(m, t_u64), 0);
  701. case 16:
  702. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  703. default:
  704. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  705. break;
  706. }
  707. return nullptr;
  708. }
  709. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  710. if (!elem_type_can_be_constant(elem_type)) {
  711. return false;
  712. }
  713. if (elem->kind == Ast_FieldValue) {
  714. elem = elem->FieldValue.value;
  715. }
  716. TypeAndValue tav = type_and_value_of_expr(elem);
  717. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  718. return tav.value.kind != ExactValue_Invalid;
  719. }
  720. String lb_mangle_name(lbModule *m, Entity *e) {
  721. String name = e->token.string;
  722. AstPackage *pkg = e->pkg;
  723. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  724. String pkgn = pkg->name;
  725. GB_ASSERT(!rune_is_digit(pkgn[0]));
  726. if (pkgn == "llvm") {
  727. pkgn = str_lit("llvm$");
  728. }
  729. isize max_len = pkgn.len + 1 + name.len + 1;
  730. bool require_suffix_id = is_type_polymorphic(e->type, true);
  731. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  732. require_suffix_id = true;
  733. } else if (is_blank_ident(e->token)) {
  734. require_suffix_id = true;
  735. }if (e->flags & EntityFlag_NotExported) {
  736. require_suffix_id = true;
  737. }
  738. if (require_suffix_id) {
  739. max_len += 21;
  740. }
  741. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  742. isize new_name_len = gb_snprintf(
  743. new_name, max_len,
  744. "%.*s.%.*s", LIT(pkgn), LIT(name)
  745. );
  746. if (require_suffix_id) {
  747. char *str = new_name + new_name_len-1;
  748. isize len = max_len-new_name_len;
  749. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  750. new_name_len += extra-1;
  751. }
  752. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  753. return mangled_name;
  754. }
  755. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  756. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  757. // and as a result, the declaration does not have time to determine what it should be
  758. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  759. if (e->TypeName.ir_mangled_name.len != 0) {
  760. return e->TypeName.ir_mangled_name;
  761. }
  762. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  763. if (p == nullptr) {
  764. Entity *proc = nullptr;
  765. if (e->parent_proc_decl != nullptr) {
  766. proc = e->parent_proc_decl->entity;
  767. } else {
  768. Scope *scope = e->scope;
  769. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  770. scope = scope->parent;
  771. }
  772. GB_ASSERT(scope != nullptr);
  773. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  774. proc = scope->procedure_entity;
  775. }
  776. GB_ASSERT(proc->kind == Entity_Procedure);
  777. if (proc->code_gen_procedure != nullptr) {
  778. p = proc->code_gen_procedure;
  779. }
  780. }
  781. // NOTE(bill): Generate a new name
  782. // parent_proc.name-guid
  783. String ts_name = e->token.string;
  784. if (p != nullptr) {
  785. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  786. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  787. u32 guid = ++p->module->nested_type_name_guid;
  788. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  789. String name = make_string(cast(u8 *)name_text, name_len-1);
  790. e->TypeName.ir_mangled_name = name;
  791. return name;
  792. } else {
  793. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  794. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  795. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  796. static u32 guid = 0;
  797. guid += 1;
  798. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  799. String name = make_string(cast(u8 *)name_text, name_len-1);
  800. e->TypeName.ir_mangled_name = name;
  801. return name;
  802. }
  803. }
  804. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  805. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  806. return e->TypeName.ir_mangled_name;
  807. }
  808. GB_ASSERT(e != nullptr);
  809. if (e->pkg == nullptr) {
  810. return e->token.string;
  811. }
  812. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  813. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  814. }
  815. String name = {};
  816. bool no_name_mangle = false;
  817. if (e->kind == Entity_Variable) {
  818. bool is_foreign = e->Variable.is_foreign;
  819. bool is_export = e->Variable.is_export;
  820. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  821. if (e->Variable.link_name.len > 0) {
  822. return e->Variable.link_name;
  823. }
  824. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  825. return e->Procedure.link_name;
  826. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  827. no_name_mangle = true;
  828. }
  829. if (!no_name_mangle) {
  830. name = lb_mangle_name(m, e);
  831. }
  832. if (name.len == 0) {
  833. name = e->token.string;
  834. }
  835. if (e->kind == Entity_TypeName) {
  836. e->TypeName.ir_mangled_name = name;
  837. } else if (e->kind == Entity_Procedure) {
  838. e->Procedure.link_name = name;
  839. }
  840. return name;
  841. }
  842. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  843. Type *original_type = type;
  844. LLVMContextRef ctx = m->ctx;
  845. i64 size = type_size_of(type); // Check size
  846. GB_ASSERT(type != t_invalid);
  847. switch (type->kind) {
  848. case Type_Basic:
  849. switch (type->Basic.kind) {
  850. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  851. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  852. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  853. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  854. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  855. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  856. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  857. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  858. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  859. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  860. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  861. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  862. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  863. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  864. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  865. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  866. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  867. case Basic_f16: return LLVMHalfTypeInContext(ctx);
  868. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  869. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  870. case Basic_f16le: return LLVMHalfTypeInContext(ctx);
  871. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  872. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  873. case Basic_f16be: return LLVMHalfTypeInContext(ctx);
  874. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  875. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  876. case Basic_complex32:
  877. {
  878. char const *name = "..complex32";
  879. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  880. if (type != nullptr) {
  881. return type;
  882. }
  883. type = LLVMStructCreateNamed(ctx, name);
  884. LLVMTypeRef fields[2] = {
  885. lb_type(m, t_f16),
  886. lb_type(m, t_f16),
  887. };
  888. LLVMStructSetBody(type, fields, 2, false);
  889. return type;
  890. }
  891. case Basic_complex64:
  892. {
  893. char const *name = "..complex64";
  894. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  895. if (type != nullptr) {
  896. return type;
  897. }
  898. type = LLVMStructCreateNamed(ctx, name);
  899. LLVMTypeRef fields[2] = {
  900. lb_type(m, t_f32),
  901. lb_type(m, t_f32),
  902. };
  903. LLVMStructSetBody(type, fields, 2, false);
  904. return type;
  905. }
  906. case Basic_complex128:
  907. {
  908. char const *name = "..complex128";
  909. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  910. if (type != nullptr) {
  911. return type;
  912. }
  913. type = LLVMStructCreateNamed(ctx, name);
  914. LLVMTypeRef fields[2] = {
  915. lb_type(m, t_f64),
  916. lb_type(m, t_f64),
  917. };
  918. LLVMStructSetBody(type, fields, 2, false);
  919. return type;
  920. }
  921. case Basic_quaternion64:
  922. {
  923. char const *name = "..quaternion64";
  924. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  925. if (type != nullptr) {
  926. return type;
  927. }
  928. type = LLVMStructCreateNamed(ctx, name);
  929. LLVMTypeRef fields[4] = {
  930. lb_type(m, t_f16),
  931. lb_type(m, t_f16),
  932. lb_type(m, t_f16),
  933. lb_type(m, t_f16),
  934. };
  935. LLVMStructSetBody(type, fields, 4, false);
  936. return type;
  937. }
  938. case Basic_quaternion128:
  939. {
  940. char const *name = "..quaternion128";
  941. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  942. if (type != nullptr) {
  943. return type;
  944. }
  945. type = LLVMStructCreateNamed(ctx, name);
  946. LLVMTypeRef fields[4] = {
  947. lb_type(m, t_f32),
  948. lb_type(m, t_f32),
  949. lb_type(m, t_f32),
  950. lb_type(m, t_f32),
  951. };
  952. LLVMStructSetBody(type, fields, 4, false);
  953. return type;
  954. }
  955. case Basic_quaternion256:
  956. {
  957. char const *name = "..quaternion256";
  958. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  959. if (type != nullptr) {
  960. return type;
  961. }
  962. type = LLVMStructCreateNamed(ctx, name);
  963. LLVMTypeRef fields[4] = {
  964. lb_type(m, t_f64),
  965. lb_type(m, t_f64),
  966. lb_type(m, t_f64),
  967. lb_type(m, t_f64),
  968. };
  969. LLVMStructSetBody(type, fields, 4, false);
  970. return type;
  971. }
  972. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  973. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  974. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  975. case Basic_rawptr: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  976. case Basic_string:
  977. {
  978. char const *name = "..string";
  979. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  980. if (type != nullptr) {
  981. return type;
  982. }
  983. type = LLVMStructCreateNamed(ctx, name);
  984. LLVMTypeRef fields[2] = {
  985. LLVMPointerType(lb_type(m, t_u8), 0),
  986. lb_type(m, t_int),
  987. };
  988. LLVMStructSetBody(type, fields, 2, false);
  989. return type;
  990. }
  991. case Basic_cstring: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  992. case Basic_any:
  993. {
  994. char const *name = "..any";
  995. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  996. if (type != nullptr) {
  997. return type;
  998. }
  999. type = LLVMStructCreateNamed(ctx, name);
  1000. LLVMTypeRef fields[2] = {
  1001. lb_type(m, t_rawptr),
  1002. lb_type(m, t_typeid),
  1003. };
  1004. LLVMStructSetBody(type, fields, 2, false);
  1005. return type;
  1006. }
  1007. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.word_size);
  1008. // Endian Specific Types
  1009. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  1010. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  1011. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  1012. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  1013. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  1014. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  1015. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  1016. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  1017. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  1018. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  1019. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  1020. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  1021. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  1022. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  1023. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  1024. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  1025. // Untyped types
  1026. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1027. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1028. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1029. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1030. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1031. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1032. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1033. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1034. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1035. }
  1036. break;
  1037. case Type_Named:
  1038. {
  1039. Type *base = base_type(type->Named.base);
  1040. switch (base->kind) {
  1041. case Type_Basic:
  1042. return lb_type_internal(m, base);
  1043. case Type_Named:
  1044. case Type_Generic:
  1045. GB_PANIC("INVALID TYPE");
  1046. break;
  1047. case Type_Pointer:
  1048. case Type_Array:
  1049. case Type_EnumeratedArray:
  1050. case Type_Slice:
  1051. case Type_DynamicArray:
  1052. case Type_Map:
  1053. case Type_Enum:
  1054. case Type_BitSet:
  1055. case Type_SimdVector:
  1056. return lb_type_internal(m, base);
  1057. // TODO(bill): Deal with this correctly. Can this be named?
  1058. case Type_Proc:
  1059. return lb_type_internal(m, base);
  1060. case Type_Tuple:
  1061. return lb_type_internal(m, base);
  1062. }
  1063. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  1064. if (found) {
  1065. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1066. if (kind == LLVMStructTypeKind) {
  1067. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1068. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1069. if (llvm_type != nullptr) {
  1070. return llvm_type;
  1071. }
  1072. llvm_type = LLVMStructCreateNamed(ctx, name);
  1073. map_set(&m->types, hash_type(type), llvm_type);
  1074. lb_clone_struct_type(llvm_type, *found);
  1075. return llvm_type;
  1076. }
  1077. }
  1078. switch (base->kind) {
  1079. case Type_Struct:
  1080. case Type_Union:
  1081. {
  1082. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1083. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1084. if (llvm_type != nullptr) {
  1085. return llvm_type;
  1086. }
  1087. llvm_type = LLVMStructCreateNamed(ctx, name);
  1088. map_set(&m->types, hash_type(type), llvm_type);
  1089. lb_clone_struct_type(llvm_type, lb_type(m, base));
  1090. return llvm_type;
  1091. }
  1092. }
  1093. return lb_type_internal(m, base);
  1094. }
  1095. case Type_Pointer:
  1096. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1097. case Type_Array: {
  1098. m->internal_type_level -= 1;
  1099. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1100. m->internal_type_level += 1;
  1101. return t;
  1102. }
  1103. case Type_EnumeratedArray: {
  1104. m->internal_type_level -= 1;
  1105. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1106. m->internal_type_level += 1;
  1107. return t;
  1108. }
  1109. case Type_Slice:
  1110. {
  1111. LLVMTypeRef fields[2] = {
  1112. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1113. lb_type(m, t_int), // len
  1114. };
  1115. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1116. }
  1117. break;
  1118. case Type_DynamicArray:
  1119. {
  1120. LLVMTypeRef fields[4] = {
  1121. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1122. lb_type(m, t_int), // len
  1123. lb_type(m, t_int), // cap
  1124. lb_type(m, t_allocator), // allocator
  1125. };
  1126. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1127. }
  1128. break;
  1129. case Type_Map:
  1130. return lb_type(m, type->Map.internal_type);
  1131. case Type_Struct:
  1132. {
  1133. if (type->Struct.is_raw_union) {
  1134. unsigned field_count = 2;
  1135. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1136. i64 alignment = type_align_of(type);
  1137. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1138. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1139. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1140. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1141. }
  1142. isize offset = 0;
  1143. if (type->Struct.custom_align > 0) {
  1144. offset = 1;
  1145. }
  1146. m->internal_type_level += 1;
  1147. defer (m->internal_type_level -= 1);
  1148. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1149. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1150. for_array(i, type->Struct.fields) {
  1151. Entity *field = type->Struct.fields[i];
  1152. fields[i+offset] = lb_type(m, field->type);
  1153. }
  1154. if (type->Struct.custom_align > 0) {
  1155. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1156. }
  1157. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1158. }
  1159. break;
  1160. case Type_Union:
  1161. if (type->Union.variants.count == 0) {
  1162. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1163. } else {
  1164. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1165. // LLVM takes the first element's alignment as the entire alignment (like C)
  1166. i64 align = type_align_of(type);
  1167. i64 size = type_size_of(type);
  1168. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1169. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1170. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1171. }
  1172. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1173. LLVMTypeRef fields[3] = {};
  1174. unsigned field_count = 1;
  1175. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1176. if (is_type_union_maybe_pointer(type)) {
  1177. field_count += 1;
  1178. fields[1] = lb_type(m, type->Union.variants[0]);
  1179. } else {
  1180. field_count += 2;
  1181. if (block_size == align) {
  1182. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1183. } else {
  1184. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1185. }
  1186. fields[2] = lb_type(m, union_tag_type(type));
  1187. }
  1188. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1189. }
  1190. break;
  1191. case Type_Enum:
  1192. return lb_type(m, base_enum_type(type));
  1193. case Type_Tuple:
  1194. if (type->Tuple.variables.count == 1) {
  1195. return lb_type(m, type->Tuple.variables[0]->type);
  1196. } else {
  1197. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1198. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1199. for_array(i, type->Tuple.variables) {
  1200. Entity *field = type->Tuple.variables[i];
  1201. LLVMTypeRef param_type = nullptr;
  1202. param_type = lb_type(m, field->type);
  1203. fields[i] = param_type;
  1204. }
  1205. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1206. }
  1207. case Type_Proc:
  1208. // if (m->internal_type_level > 256) { // TODO HACK(bill): is this really enough?
  1209. if (m->internal_type_level > 1) { // TODO HACK(bill): is this really enough?
  1210. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1211. } else {
  1212. unsigned param_count = 0;
  1213. if (type->Proc.calling_convention == ProcCC_Odin) {
  1214. param_count += 1;
  1215. }
  1216. if (type->Proc.param_count != 0) {
  1217. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1218. for_array(i, type->Proc.params->Tuple.variables) {
  1219. Entity *e = type->Proc.params->Tuple.variables[i];
  1220. if (e->kind != Entity_Variable) {
  1221. continue;
  1222. }
  1223. if (e->flags & EntityFlag_CVarArg) {
  1224. continue;
  1225. }
  1226. param_count += 1;
  1227. }
  1228. }
  1229. m->internal_type_level += 1;
  1230. defer (m->internal_type_level -= 1);
  1231. LLVMTypeRef ret = nullptr;
  1232. LLVMTypeRef *params = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1233. if (type->Proc.result_count != 0) {
  1234. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1235. ret = lb_type(m, single_ret);
  1236. if (ret != nullptr) {
  1237. if (is_type_boolean(single_ret) &&
  1238. is_calling_convention_none(type->Proc.calling_convention) &&
  1239. type_size_of(single_ret) <= 1) {
  1240. ret = LLVMInt1TypeInContext(m->ctx);
  1241. }
  1242. }
  1243. }
  1244. isize param_index = 0;
  1245. if (type->Proc.param_count != 0) {
  1246. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1247. for_array(i, type->Proc.params->Tuple.variables) {
  1248. Entity *e = type->Proc.params->Tuple.variables[i];
  1249. if (e->kind != Entity_Variable) {
  1250. continue;
  1251. }
  1252. if (e->flags & EntityFlag_CVarArg) {
  1253. continue;
  1254. }
  1255. Type *e_type = reduce_tuple_to_single_type(e->type);
  1256. LLVMTypeRef param_type = nullptr;
  1257. if (is_type_boolean(e_type) &&
  1258. type_size_of(e_type) <= 1) {
  1259. param_type = LLVMInt1TypeInContext(m->ctx);
  1260. } else {
  1261. if (is_type_proc(e_type)) {
  1262. param_type = lb_type(m, t_rawptr);
  1263. } else {
  1264. param_type = lb_type(m, e_type);
  1265. }
  1266. }
  1267. params[param_index++] = param_type;
  1268. }
  1269. }
  1270. if (param_index < param_count) {
  1271. params[param_index++] = lb_type(m, t_rawptr);
  1272. }
  1273. GB_ASSERT(param_index == param_count);
  1274. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1275. {
  1276. for_array(j, ft->args) {
  1277. auto arg = ft->args[j];
  1278. GB_ASSERT_MSG(LLVMGetTypeContext(arg.type) == ft->ctx,
  1279. "\n\t%s %td/%td"
  1280. "\n\tArgTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1281. LLVMPrintTypeToString(arg.type),
  1282. j, ft->args.count,
  1283. LLVMGetTypeContext(arg.type), ft->ctx, LLVMGetGlobalContext());
  1284. }
  1285. GB_ASSERT_MSG(LLVMGetTypeContext(ft->ret.type) == ft->ctx,
  1286. "\n\t%s"
  1287. "\n\tRetTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1288. LLVMPrintTypeToString(ft->ret.type),
  1289. LLVMGetTypeContext(ft->ret.type), ft->ctx, LLVMGetGlobalContext());
  1290. }
  1291. map_set(&m->function_type_map, hash_type(type), ft);
  1292. LLVMTypeRef new_abi_fn_ptr_type = lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1293. LLVMTypeRef new_abi_fn_type = LLVMGetElementType(new_abi_fn_ptr_type);
  1294. GB_ASSERT_MSG(LLVMGetTypeContext(new_abi_fn_type) == m->ctx,
  1295. "\n\tFuncTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1296. LLVMGetTypeContext(new_abi_fn_type), m->ctx, LLVMGetGlobalContext());
  1297. return new_abi_fn_ptr_type;
  1298. }
  1299. break;
  1300. case Type_BitSet:
  1301. {
  1302. Type *ut = bit_set_to_int(type);
  1303. return lb_type(m, ut);
  1304. }
  1305. case Type_SimdVector:
  1306. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1307. case Type_RelativePointer:
  1308. return lb_type_internal(m, type->RelativePointer.base_integer);
  1309. case Type_RelativeSlice:
  1310. {
  1311. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1312. unsigned field_count = 2;
  1313. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1314. fields[0] = base_integer;
  1315. fields[1] = base_integer;
  1316. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1317. }
  1318. }
  1319. GB_PANIC("Invalid type %s", type_to_string(type));
  1320. return LLVMInt32TypeInContext(ctx);
  1321. }
  1322. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1323. type = default_type(type);
  1324. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1325. if (found) {
  1326. return *found;
  1327. }
  1328. LLVMTypeRef llvm_type = nullptr;
  1329. m->internal_type_level += 1;
  1330. llvm_type = lb_type_internal(m, type);
  1331. m->internal_type_level -= 1;
  1332. if (m->internal_type_level == 0) {
  1333. map_set(&m->types, hash_type(type), llvm_type);
  1334. if (is_type_named(type)) {
  1335. map_set(&m->llvm_types, hash_pointer(llvm_type), type);
  1336. }
  1337. }
  1338. return llvm_type;
  1339. }
  1340. lbFunctionType *lb_get_function_type(lbModule *m, lbProcedure *p, Type *pt) {
  1341. lbFunctionType **ft_found = nullptr;
  1342. ft_found = map_get(&m->function_type_map, hash_type(pt));
  1343. if (!ft_found) {
  1344. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  1345. ft_found = map_get(&m->function_type_map, hash_type(pt));
  1346. }
  1347. GB_ASSERT(ft_found != nullptr);
  1348. return *ft_found;
  1349. }
  1350. LLVMMetadataRef lb_get_llvm_metadata(lbModule *m, void *key) {
  1351. if (key == nullptr) {
  1352. return nullptr;
  1353. }
  1354. auto found = map_get(&m->debug_values, hash_pointer(key));
  1355. if (found) {
  1356. return *found;
  1357. }
  1358. return nullptr;
  1359. }
  1360. void lb_set_llvm_metadata(lbModule *m, void *key, LLVMMetadataRef value) {
  1361. if (key != nullptr) {
  1362. map_set(&m->debug_values, hash_pointer(key), value);
  1363. }
  1364. }
  1365. LLVMMetadataRef lb_get_llvm_file_metadata_from_node(lbModule *m, Ast *node) {
  1366. if (node == nullptr) {
  1367. return nullptr;
  1368. }
  1369. return lb_get_llvm_metadata(m, node->file);
  1370. }
  1371. LLVMMetadataRef lb_get_current_debug_scope(lbProcedure *p) {
  1372. GB_ASSERT_MSG(p->debug_info != nullptr, "missing debug information for %.*s", LIT(p->name));
  1373. for (isize i = p->scope_stack.count-1; i >= 0; i--) {
  1374. Scope *s = p->scope_stack[i];
  1375. LLVMMetadataRef md = lb_get_llvm_metadata(p->module, s);
  1376. if (md) {
  1377. return md;
  1378. }
  1379. }
  1380. return p->debug_info;
  1381. }
  1382. LLVMMetadataRef lb_debug_location_from_token_pos(lbProcedure *p, TokenPos pos) {
  1383. LLVMMetadataRef scope = lb_get_current_debug_scope(p);
  1384. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  1385. return LLVMDIBuilderCreateDebugLocation(p->module->ctx, cast(unsigned)pos.line, cast(unsigned)pos.column, scope, nullptr);
  1386. }
  1387. LLVMMetadataRef lb_debug_location_from_ast(lbProcedure *p, Ast *node) {
  1388. GB_ASSERT(node != nullptr);
  1389. return lb_debug_location_from_token_pos(p, ast_token(node).pos);
  1390. }
  1391. LLVMMetadataRef lb_debug_type_internal_proc(lbModule *m, Type *type) {
  1392. Type *original_type = type;
  1393. LLVMContextRef ctx = m->ctx;
  1394. i64 size = type_size_of(type); // Check size
  1395. GB_ASSERT(type != t_invalid);
  1396. unsigned const word_size = cast(unsigned)build_context.word_size;
  1397. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1398. GB_ASSERT(type->kind == Type_Proc);
  1399. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1400. unsigned parameter_count = 1;
  1401. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1402. Entity *e = type->Proc.params->Tuple.variables[i];
  1403. if (e->kind == Entity_Variable) {
  1404. parameter_count += 1;
  1405. }
  1406. }
  1407. LLVMMetadataRef *parameters = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, parameter_count);
  1408. unsigned param_index = 0;
  1409. if (type->Proc.result_count == 0) {
  1410. parameters[param_index++] = nullptr;
  1411. } else {
  1412. parameters[param_index++] = lb_debug_type(m, type->Proc.results);
  1413. }
  1414. LLVMMetadataRef parent_scope = nullptr;
  1415. LLVMMetadataRef scope = nullptr;
  1416. LLVMMetadataRef file = nullptr;
  1417. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1418. Entity *e = type->Proc.params->Tuple.variables[i];
  1419. if (e->kind != Entity_Variable) {
  1420. continue;
  1421. }
  1422. parameters[param_index] = lb_debug_type(m, e->type);
  1423. param_index += 1;
  1424. }
  1425. LLVMDIFlags flags = LLVMDIFlagZero;
  1426. if (type->Proc.diverging) {
  1427. flags = LLVMDIFlagNoReturn;
  1428. }
  1429. return LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, parameters, parameter_count, flags);
  1430. }
  1431. LLVMMetadataRef lb_debug_struct_field(lbModule *m, String const &name, Type *type, u64 offset_in_bits) {
  1432. unsigned field_line = 1;
  1433. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1434. AstPackage *pkg = m->info->runtime_package;
  1435. GB_ASSERT(pkg->files.count != 0);
  1436. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1437. LLVMMetadataRef scope = file;
  1438. return LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1439. 8*cast(u64)type_size_of(type), 8*cast(u32)type_align_of(type), offset_in_bits,
  1440. field_flags, lb_debug_type(m, type)
  1441. );
  1442. }
  1443. LLVMMetadataRef lb_debug_basic_struct(lbModule *m, String const &name, u64 size_in_bits, u32 align_in_bits, LLVMMetadataRef *elements, unsigned element_count) {
  1444. AstPackage *pkg = m->info->runtime_package;
  1445. GB_ASSERT(pkg->files.count != 0);
  1446. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1447. LLVMMetadataRef scope = file;
  1448. return LLVMDIBuilderCreateStructType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, 1, size_in_bits, align_in_bits, LLVMDIFlagZero, nullptr, elements, element_count, 0, nullptr, "", 0);
  1449. }
  1450. LLVMMetadataRef lb_debug_type_basic_type(lbModule *m, String const &name, u64 size_in_bits, LLVMDWARFTypeEncoding encoding, LLVMDIFlags flags = LLVMDIFlagZero) {
  1451. LLVMMetadataRef basic_type = LLVMDIBuilderCreateBasicType(m->debug_builder, cast(char const *)name.text, name.len, size_in_bits, encoding, flags);
  1452. #if 1
  1453. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, basic_type, cast(char const *)name.text, name.len, nullptr, 0, nullptr, cast(u32)size_in_bits);
  1454. return final_decl;
  1455. #else
  1456. return basic_type;
  1457. #endif
  1458. }
  1459. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1460. Type *original_type = type;
  1461. LLVMContextRef ctx = m->ctx;
  1462. i64 size = type_size_of(type); // Check size
  1463. GB_ASSERT(type != t_invalid);
  1464. unsigned const word_size = cast(unsigned)build_context.word_size;
  1465. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1466. switch (type->kind) {
  1467. case Type_Basic:
  1468. switch (type->Basic.kind) {
  1469. case Basic_llvm_bool: return lb_debug_type_basic_type(m, str_lit("llvm bool"), 1, LLVMDWARFTypeEncoding_Boolean);
  1470. case Basic_bool: return lb_debug_type_basic_type(m, str_lit("bool"), 8, LLVMDWARFTypeEncoding_Boolean);
  1471. case Basic_b8: return lb_debug_type_basic_type(m, str_lit("b8"), 8, LLVMDWARFTypeEncoding_Boolean);
  1472. case Basic_b16: return lb_debug_type_basic_type(m, str_lit("b16"), 16, LLVMDWARFTypeEncoding_Boolean);
  1473. case Basic_b32: return lb_debug_type_basic_type(m, str_lit("b32"), 32, LLVMDWARFTypeEncoding_Boolean);
  1474. case Basic_b64: return lb_debug_type_basic_type(m, str_lit("b64"), 64, LLVMDWARFTypeEncoding_Boolean);
  1475. case Basic_i8: return lb_debug_type_basic_type(m, str_lit("i8"), 8, LLVMDWARFTypeEncoding_Signed);
  1476. case Basic_u8: return lb_debug_type_basic_type(m, str_lit("u8"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1477. case Basic_i16: return lb_debug_type_basic_type(m, str_lit("i16"), 16, LLVMDWARFTypeEncoding_Signed);
  1478. case Basic_u16: return lb_debug_type_basic_type(m, str_lit("u16"), 16, LLVMDWARFTypeEncoding_Unsigned);
  1479. case Basic_i32: return lb_debug_type_basic_type(m, str_lit("i32"), 32, LLVMDWARFTypeEncoding_Signed);
  1480. case Basic_u32: return lb_debug_type_basic_type(m, str_lit("u32"), 32, LLVMDWARFTypeEncoding_Unsigned);
  1481. case Basic_i64: return lb_debug_type_basic_type(m, str_lit("i64"), 64, LLVMDWARFTypeEncoding_Signed);
  1482. case Basic_u64: return lb_debug_type_basic_type(m, str_lit("u64"), 64, LLVMDWARFTypeEncoding_Unsigned);
  1483. case Basic_i128: return lb_debug_type_basic_type(m, str_lit("i128"), 128, LLVMDWARFTypeEncoding_Signed);
  1484. case Basic_u128: return lb_debug_type_basic_type(m, str_lit("u128"), 128, LLVMDWARFTypeEncoding_Unsigned);
  1485. case Basic_rune: return lb_debug_type_basic_type(m, str_lit("rune"), 32, LLVMDWARFTypeEncoding_Utf);
  1486. case Basic_f16: return lb_debug_type_basic_type(m, str_lit("f16"), 16, LLVMDWARFTypeEncoding_Float);
  1487. case Basic_f32: return lb_debug_type_basic_type(m, str_lit("f32"), 32, LLVMDWARFTypeEncoding_Float);
  1488. case Basic_f64: return lb_debug_type_basic_type(m, str_lit("f64"), 64, LLVMDWARFTypeEncoding_Float);
  1489. case Basic_int: return lb_debug_type_basic_type(m, str_lit("int"), word_bits, LLVMDWARFTypeEncoding_Signed);
  1490. case Basic_uint: return lb_debug_type_basic_type(m, str_lit("uint"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1491. case Basic_uintptr: return lb_debug_type_basic_type(m, str_lit("uintptr"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1492. case Basic_typeid:
  1493. return lb_debug_type_basic_type(m, str_lit("typeid"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1494. // Endian Specific Types
  1495. case Basic_i16le: return lb_debug_type_basic_type(m, str_lit("i16le"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1496. case Basic_u16le: return lb_debug_type_basic_type(m, str_lit("u16le"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1497. case Basic_i32le: return lb_debug_type_basic_type(m, str_lit("i32le"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1498. case Basic_u32le: return lb_debug_type_basic_type(m, str_lit("u32le"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1499. case Basic_i64le: return lb_debug_type_basic_type(m, str_lit("i64le"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1500. case Basic_u64le: return lb_debug_type_basic_type(m, str_lit("u64le"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1501. case Basic_i128le: return lb_debug_type_basic_type(m, str_lit("i128le"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1502. case Basic_u128le: return lb_debug_type_basic_type(m, str_lit("u128le"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1503. case Basic_f16le: return lb_debug_type_basic_type(m, str_lit("f16le"), 16, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1504. case Basic_f32le: return lb_debug_type_basic_type(m, str_lit("f32le"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1505. case Basic_f64le: return lb_debug_type_basic_type(m, str_lit("f64le"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1506. case Basic_i16be: return lb_debug_type_basic_type(m, str_lit("i16be"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1507. case Basic_u16be: return lb_debug_type_basic_type(m, str_lit("u16be"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1508. case Basic_i32be: return lb_debug_type_basic_type(m, str_lit("i32be"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1509. case Basic_u32be: return lb_debug_type_basic_type(m, str_lit("u32be"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1510. case Basic_i64be: return lb_debug_type_basic_type(m, str_lit("i64be"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1511. case Basic_u64be: return lb_debug_type_basic_type(m, str_lit("u64be"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1512. case Basic_i128be: return lb_debug_type_basic_type(m, str_lit("i128be"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1513. case Basic_u128be: return lb_debug_type_basic_type(m, str_lit("u128be"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1514. case Basic_f16be: return lb_debug_type_basic_type(m, str_lit("f16be"), 16, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1515. case Basic_f32be: return lb_debug_type_basic_type(m, str_lit("f32be"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1516. case Basic_f64be: return lb_debug_type_basic_type(m, str_lit("f64be"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1517. case Basic_complex32:
  1518. {
  1519. LLVMMetadataRef elements[2] = {};
  1520. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f16, 0);
  1521. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f16, 4);
  1522. return lb_debug_basic_struct(m, str_lit("complex32"), 64, 32, elements, gb_count_of(elements));
  1523. }
  1524. case Basic_complex64:
  1525. {
  1526. LLVMMetadataRef elements[2] = {};
  1527. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f32, 0);
  1528. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 4);
  1529. return lb_debug_basic_struct(m, str_lit("complex64"), 64, 32, elements, gb_count_of(elements));
  1530. }
  1531. case Basic_complex128:
  1532. {
  1533. LLVMMetadataRef elements[2] = {};
  1534. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f64, 0);
  1535. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 8);
  1536. return lb_debug_basic_struct(m, str_lit("complex128"), 128, 64, elements, gb_count_of(elements));
  1537. }
  1538. case Basic_quaternion64:
  1539. {
  1540. LLVMMetadataRef elements[4] = {};
  1541. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f16, 0);
  1542. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f16, 4);
  1543. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f16, 8);
  1544. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f16, 12);
  1545. return lb_debug_basic_struct(m, str_lit("quaternion64"), 128, 32, elements, gb_count_of(elements));
  1546. }
  1547. case Basic_quaternion128:
  1548. {
  1549. LLVMMetadataRef elements[4] = {};
  1550. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 0);
  1551. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f32, 4);
  1552. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f32, 8);
  1553. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f32, 12);
  1554. return lb_debug_basic_struct(m, str_lit("quaternion128"), 128, 32, elements, gb_count_of(elements));
  1555. }
  1556. case Basic_quaternion256:
  1557. {
  1558. LLVMMetadataRef elements[4] = {};
  1559. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 0);
  1560. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f64, 8);
  1561. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f64, 16);
  1562. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f64, 24);
  1563. return lb_debug_basic_struct(m, str_lit("quaternion256"), 256, 32, elements, gb_count_of(elements));
  1564. }
  1565. case Basic_rawptr:
  1566. {
  1567. LLVMMetadataRef void_type = lb_debug_type_basic_type(m, str_lit("void"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1568. return LLVMDIBuilderCreatePointerType(m->debug_builder, void_type, word_bits, word_bits, LLVMDWARFTypeEncoding_Address, "rawptr", 6);
  1569. }
  1570. case Basic_string:
  1571. {
  1572. LLVMMetadataRef elements[2] = {};
  1573. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_u8_ptr, 0);
  1574. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, word_bits);
  1575. return lb_debug_basic_struct(m, str_lit("string"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1576. }
  1577. case Basic_cstring:
  1578. {
  1579. LLVMMetadataRef char_type = lb_debug_type_basic_type(m, str_lit("char"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1580. return LLVMDIBuilderCreatePointerType(m->debug_builder, char_type, word_bits, word_bits, 0, "cstring", 7);
  1581. }
  1582. case Basic_any:
  1583. {
  1584. LLVMMetadataRef elements[2] = {};
  1585. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_rawptr, 0);
  1586. elements[1] = lb_debug_struct_field(m, str_lit("id"), t_typeid, word_bits);
  1587. return lb_debug_basic_struct(m, str_lit("any"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1588. }
  1589. // Untyped types
  1590. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1591. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1592. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1593. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1594. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1595. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1596. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1597. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1598. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1599. default: GB_PANIC("Basic Unhandled"); break;
  1600. }
  1601. break;
  1602. case Type_Named:
  1603. GB_PANIC("Type_Named should be handled in lb_debug_type separately");
  1604. case Type_Pointer:
  1605. return LLVMDIBuilderCreatePointerType(m->debug_builder, lb_debug_type(m, type->Pointer.elem), word_bits, word_bits, 0, nullptr, 0);
  1606. case Type_Array: {
  1607. LLVMMetadataRef subscripts[1] = {};
  1608. subscripts[0] = LLVMDIBuilderGetOrCreateSubrange(m->debug_builder,
  1609. 0ll,
  1610. type->Array.count
  1611. );
  1612. return LLVMDIBuilderCreateArrayType(m->debug_builder,
  1613. 8*cast(uint64_t)type_size_of(type),
  1614. 8*cast(unsigned)type_align_of(type),
  1615. lb_debug_type(m, type->Array.elem),
  1616. subscripts, gb_count_of(subscripts));
  1617. }
  1618. case Type_EnumeratedArray: {
  1619. LLVMMetadataRef subscripts[1] = {};
  1620. subscripts[0] = LLVMDIBuilderGetOrCreateSubrange(m->debug_builder,
  1621. 0ll,
  1622. type->EnumeratedArray.count
  1623. );
  1624. LLVMMetadataRef array_type = LLVMDIBuilderCreateArrayType(m->debug_builder,
  1625. 8*cast(uint64_t)type_size_of(type),
  1626. 8*cast(unsigned)type_align_of(type),
  1627. lb_debug_type(m, type->EnumeratedArray.elem),
  1628. subscripts, gb_count_of(subscripts));
  1629. gbString name = type_to_string(type, temporary_allocator());
  1630. return LLVMDIBuilderCreateTypedef(m->debug_builder, array_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1631. }
  1632. case Type_Struct:
  1633. case Type_Union:
  1634. case Type_Slice:
  1635. case Type_DynamicArray:
  1636. case Type_Map:
  1637. case Type_BitSet:
  1638. {
  1639. unsigned tag = DW_TAG_structure_type;
  1640. if (is_type_raw_union(type) || is_type_union(type)) {
  1641. tag = DW_TAG_union_type;
  1642. }
  1643. u64 size_in_bits = cast(u64)(8*type_size_of(type));
  1644. u32 align_in_bits = cast(u32)(8*type_size_of(type));
  1645. LLVMDIFlags flags = LLVMDIFlagZero;
  1646. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1647. m->debug_builder, tag, "", 0, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1648. );
  1649. lbIncompleteDebugType idt = {};
  1650. idt.type = type;
  1651. idt.metadata = temp_forward_decl;
  1652. array_add(&m->debug_incomplete_types, idt);
  1653. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1654. return temp_forward_decl;
  1655. }
  1656. case Type_Enum:
  1657. {
  1658. LLVMMetadataRef scope = nullptr;
  1659. LLVMMetadataRef file = nullptr;
  1660. unsigned line = 0;
  1661. unsigned element_count = cast(unsigned)type->Enum.fields.count;
  1662. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1663. Type *bt = base_enum_type(type);
  1664. LLVMBool is_unsigned = is_type_unsigned(bt);
  1665. for (unsigned i = 0; i < element_count; i++) {
  1666. Entity *f = type->Enum.fields[i];
  1667. GB_ASSERT(f->kind == Entity_Constant);
  1668. String name = f->token.string;
  1669. i64 value = exact_value_to_i64(f->Constant.value);
  1670. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1671. }
  1672. LLVMMetadataRef class_type = lb_debug_type(m, bt);
  1673. return LLVMDIBuilderCreateEnumerationType(m->debug_builder, scope, "", 0, file, line, 8*type_size_of(type), 8*cast(unsigned)type_align_of(type), elements, element_count, class_type);
  1674. }
  1675. case Type_Tuple:
  1676. if (type->Tuple.variables.count == 1) {
  1677. return lb_debug_type(m, type->Tuple.variables[0]->type);
  1678. } else {
  1679. type_set_offsets(type);
  1680. LLVMMetadataRef parent_scope = nullptr;
  1681. LLVMMetadataRef scope = nullptr;
  1682. LLVMMetadataRef file = nullptr;
  1683. unsigned line = 0;
  1684. u64 size_in_bits = 8*cast(u64)type_size_of(type);
  1685. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1686. LLVMDIFlags flags = LLVMDIFlagZero;
  1687. unsigned element_count = cast(unsigned)type->Tuple.variables.count;
  1688. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1689. for (unsigned i = 0; i < element_count; i++) {
  1690. Entity *f = type->Tuple.variables[i];
  1691. GB_ASSERT(f->kind == Entity_Variable);
  1692. String name = f->token.string;
  1693. unsigned field_line = 0;
  1694. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1695. u64 offset_in_bits = 8*cast(u64)type->Tuple.offsets[i];
  1696. elements[i] = LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1697. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type), offset_in_bits,
  1698. field_flags, lb_debug_type(m, f->type)
  1699. );
  1700. }
  1701. return LLVMDIBuilderCreateStructType(m->debug_builder, parent_scope, "", 0, file, line,
  1702. size_in_bits, align_in_bits, flags,
  1703. nullptr, elements, element_count, 0, nullptr,
  1704. "", 0
  1705. );
  1706. }
  1707. case Type_Proc:
  1708. {
  1709. LLVMMetadataRef proc_underlying_type = lb_debug_type_internal_proc(m, type);
  1710. LLVMMetadataRef pointer_type = LLVMDIBuilderCreatePointerType(m->debug_builder, proc_underlying_type, word_bits, word_bits, 0, nullptr, 0);
  1711. gbString name = type_to_string(type, temporary_allocator());
  1712. return LLVMDIBuilderCreateTypedef(m->debug_builder, pointer_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1713. }
  1714. break;
  1715. case Type_SimdVector:
  1716. return LLVMDIBuilderCreateVectorType(m->debug_builder, cast(unsigned)type->SimdVector.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->SimdVector.elem), nullptr, 0);
  1717. case Type_RelativePointer: {
  1718. LLVMMetadataRef base_integer = lb_debug_type(m, type->RelativePointer.base_integer);
  1719. gbString name = type_to_string(type, temporary_allocator());
  1720. return LLVMDIBuilderCreateTypedef(m->debug_builder, base_integer, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1721. }
  1722. case Type_RelativeSlice:
  1723. {
  1724. unsigned element_count = 0;
  1725. LLVMMetadataRef elements[2] = {};
  1726. Type *base_integer = type->RelativeSlice.base_integer;
  1727. elements[0] = lb_debug_struct_field(m, str_lit("data_offset"), base_integer, 0);
  1728. elements[1] = lb_debug_struct_field(m, str_lit("len"), base_integer, 8*type_size_of(base_integer));
  1729. gbString name = type_to_string(type, temporary_allocator());
  1730. return LLVMDIBuilderCreateStructType(m->debug_builder, nullptr, name, gb_string_length(name), nullptr, 0, 2*word_bits, word_bits, LLVMDIFlagZero, nullptr, elements, element_count, 0, nullptr, "", 0);
  1731. }
  1732. }
  1733. GB_PANIC("Invalid type %s", type_to_string(type));
  1734. return nullptr;
  1735. }
  1736. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1737. GB_ASSERT(type != nullptr);
  1738. LLVMMetadataRef found = lb_get_llvm_metadata(m, type);
  1739. if (found != nullptr) {
  1740. return found;
  1741. }
  1742. if (type->kind == Type_Named) {
  1743. LLVMMetadataRef file = nullptr;
  1744. unsigned line = 0;
  1745. LLVMMetadataRef scope = nullptr;
  1746. if (type->Named.type_name != nullptr) {
  1747. Entity *e = type->Named.type_name;
  1748. scope = lb_get_llvm_metadata(m, e->scope);
  1749. if (scope != nullptr) {
  1750. file = LLVMDIScopeGetFile(scope);
  1751. }
  1752. line = cast(unsigned)e->token.pos.line;
  1753. }
  1754. // TODO(bill): location data for Type_Named
  1755. u64 size_in_bits = 8*type_size_of(type);
  1756. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1757. String name = type->Named.name;
  1758. char const *name_text = cast(char const *)name.text;
  1759. size_t name_len = cast(size_t)name.len;
  1760. unsigned tag = DW_TAG_structure_type;
  1761. if (is_type_raw_union(type) || is_type_union(type)) {
  1762. tag = DW_TAG_union_type;
  1763. }
  1764. LLVMDIFlags flags = LLVMDIFlagZero;
  1765. Type *bt = base_type(type->Named.base);
  1766. lbIncompleteDebugType idt = {};
  1767. idt.type = type;
  1768. switch (bt->kind) {
  1769. case Type_Enum:
  1770. {
  1771. LLVMMetadataRef scope = nullptr;
  1772. LLVMMetadataRef file = nullptr;
  1773. unsigned line = 0;
  1774. unsigned element_count = cast(unsigned)bt->Enum.fields.count;
  1775. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1776. Type *ct = base_enum_type(type);
  1777. LLVMBool is_unsigned = is_type_unsigned(ct);
  1778. for (unsigned i = 0; i < element_count; i++) {
  1779. Entity *f = bt->Enum.fields[i];
  1780. GB_ASSERT(f->kind == Entity_Constant);
  1781. String name = f->token.string;
  1782. i64 value = exact_value_to_i64(f->Constant.value);
  1783. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1784. }
  1785. LLVMMetadataRef class_type = lb_debug_type(m, ct);
  1786. return LLVMDIBuilderCreateEnumerationType(m->debug_builder, scope, name_text, name_len, file, line, 8*type_size_of(type), 8*cast(unsigned)type_align_of(type), elements, element_count, class_type);
  1787. }
  1788. case Type_Basic:
  1789. case Type_Pointer:
  1790. case Type_Array:
  1791. case Type_EnumeratedArray:
  1792. case Type_Tuple:
  1793. case Type_Proc:
  1794. case Type_SimdVector:
  1795. case Type_RelativePointer:
  1796. case Type_RelativeSlice:
  1797. {
  1798. LLVMMetadataRef debug_bt = lb_debug_type(m, bt);
  1799. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, debug_bt, name_text, name_len, file, line, scope, align_in_bits);
  1800. lb_set_llvm_metadata(m, type, final_decl);
  1801. return final_decl;
  1802. }
  1803. case Type_Slice:
  1804. case Type_DynamicArray:
  1805. case Type_Map:
  1806. case Type_Struct:
  1807. case Type_Union:
  1808. case Type_BitSet:
  1809. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1810. m->debug_builder, tag, name_text, name_len, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1811. );
  1812. idt.metadata = temp_forward_decl;
  1813. array_add(&m->debug_incomplete_types, idt);
  1814. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1815. return temp_forward_decl;
  1816. }
  1817. }
  1818. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1819. lb_set_llvm_metadata(m, type, dt);
  1820. return dt;
  1821. }
  1822. void lb_debug_complete_types(lbModule *m) {
  1823. unsigned const word_size = cast(unsigned)build_context.word_size;
  1824. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1825. for_array(debug_incomplete_type_index, m->debug_incomplete_types) {
  1826. auto const &idt = m->debug_incomplete_types[debug_incomplete_type_index];
  1827. GB_ASSERT(idt.type != nullptr);
  1828. GB_ASSERT(idt.metadata != nullptr);
  1829. Type *t = idt.type;
  1830. Type *bt = base_type(t);
  1831. LLVMMetadataRef parent_scope = nullptr;
  1832. LLVMMetadataRef file = nullptr;
  1833. unsigned line_number = 0;
  1834. u64 size_in_bits = 8*type_size_of(t);
  1835. u32 align_in_bits = cast(u32)(8*type_align_of(t));
  1836. LLVMDIFlags flags = LLVMDIFlagZero;
  1837. LLVMMetadataRef derived_from = nullptr;
  1838. LLVMMetadataRef *elements = nullptr;
  1839. unsigned element_count = 0;
  1840. unsigned runtime_lang = 0; // Objective-C runtime version
  1841. char const *unique_id = "";
  1842. LLVMMetadataRef vtable_holder = nullptr;
  1843. size_t unique_id_len = 0;
  1844. LLVMMetadataRef record_scope = nullptr;
  1845. switch (bt->kind) {
  1846. case Type_Slice:
  1847. case Type_DynamicArray:
  1848. case Type_Map:
  1849. case Type_Struct:
  1850. case Type_Union:
  1851. case Type_BitSet: {
  1852. bool is_union = is_type_raw_union(bt) || is_type_union(bt);
  1853. String name = str_lit("<anonymous-struct>");
  1854. if (t->kind == Type_Named) {
  1855. name = t->Named.name;
  1856. if (t->Named.type_name && t->Named.type_name->pkg && t->Named.type_name->pkg->name.len != 0) {
  1857. name = concatenate3_strings(temporary_allocator(), t->Named.type_name->pkg->name, str_lit("."), t->Named.name);
  1858. }
  1859. LLVMMetadataRef file = nullptr;
  1860. unsigned line = 0;
  1861. LLVMMetadataRef file_scope = nullptr;
  1862. if (t->Named.type_name != nullptr) {
  1863. Entity *e = t->Named.type_name;
  1864. file_scope = lb_get_llvm_metadata(m, e->scope);
  1865. if (file_scope != nullptr) {
  1866. file = LLVMDIScopeGetFile(file_scope);
  1867. }
  1868. line = cast(unsigned)e->token.pos.line;
  1869. }
  1870. // TODO(bill): location data for Type_Named
  1871. } else {
  1872. name = make_string_c(type_to_string(t, temporary_allocator()));
  1873. }
  1874. switch (bt->kind) {
  1875. case Type_Slice:
  1876. element_count = 2;
  1877. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1878. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->Slice.elem), 0*word_bits);
  1879. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1880. break;
  1881. case Type_DynamicArray:
  1882. element_count = 4;
  1883. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1884. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->DynamicArray.elem), 0*word_bits);
  1885. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1886. elements[2] = lb_debug_struct_field(m, str_lit("cap"), t_int, 2*word_bits);
  1887. elements[3] = lb_debug_struct_field(m, str_lit("allocator"), t_allocator, 3*word_bits);
  1888. break;
  1889. case Type_Map:
  1890. bt = bt->Map.internal_type;
  1891. /*fallthrough*/
  1892. case Type_Struct:
  1893. if (file == nullptr) {
  1894. if (bt->Struct.node) {
  1895. file = lb_get_llvm_metadata(m, bt->Struct.node->file);
  1896. line_number = cast(unsigned)ast_token(bt->Struct.node).pos.line;
  1897. }
  1898. }
  1899. type_set_offsets(bt);
  1900. {
  1901. isize element_offset = 0;
  1902. record_scope = lb_get_llvm_metadata(m, bt->Struct.scope);
  1903. switch (bt->Struct.soa_kind) {
  1904. case StructSoa_Slice: element_offset = 1; break;
  1905. case StructSoa_Dynamic: element_offset = 3; break;
  1906. }
  1907. element_count = cast(unsigned)(bt->Struct.fields.count + element_offset);
  1908. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1909. switch (bt->Struct.soa_kind) {
  1910. case StructSoa_Slice:
  1911. elements[0] = LLVMDIBuilderCreateMemberType(
  1912. m->debug_builder, record_scope,
  1913. ".len", 4,
  1914. file, 0,
  1915. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1916. 8*type_size_of(bt)-word_bits,
  1917. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1918. );
  1919. break;
  1920. case StructSoa_Dynamic:
  1921. elements[0] = LLVMDIBuilderCreateMemberType(
  1922. m->debug_builder, record_scope,
  1923. ".len", 4,
  1924. file, 0,
  1925. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1926. 8*type_size_of(bt)-word_bits + 0*word_bits,
  1927. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1928. );
  1929. elements[1] = LLVMDIBuilderCreateMemberType(
  1930. m->debug_builder, record_scope,
  1931. ".cap", 4,
  1932. file, 0,
  1933. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1934. 8*type_size_of(bt)-word_bits + 1*word_bits,
  1935. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1936. );
  1937. elements[2] = LLVMDIBuilderCreateMemberType(
  1938. m->debug_builder, record_scope,
  1939. ".allocator", 12,
  1940. file, 0,
  1941. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1942. 8*type_size_of(bt)-word_bits + 2*word_bits,
  1943. LLVMDIFlagZero, lb_debug_type(m, t_allocator)
  1944. );
  1945. break;
  1946. }
  1947. for_array(j, bt->Struct.fields) {
  1948. Entity *f = bt->Struct.fields[j];
  1949. String fname = f->token.string;
  1950. unsigned field_line = 0;
  1951. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1952. u64 offset_in_bits = 8*cast(u64)bt->Struct.offsets[j];
  1953. elements[element_offset+j] = LLVMDIBuilderCreateMemberType(
  1954. m->debug_builder, record_scope,
  1955. cast(char const *)fname.text, cast(size_t)fname.len,
  1956. file, field_line,
  1957. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type),
  1958. offset_in_bits,
  1959. field_flags, lb_debug_type(m, f->type)
  1960. );
  1961. }
  1962. }
  1963. break;
  1964. case Type_Union:
  1965. {
  1966. if (file == nullptr) {
  1967. GB_ASSERT(bt->Union.node != nullptr);
  1968. file = lb_get_llvm_metadata(m, bt->Union.node->file);
  1969. line_number = cast(unsigned)ast_token(bt->Union.node).pos.line;
  1970. }
  1971. isize index_offset = 1;
  1972. if (is_type_union_maybe_pointer(bt)) {
  1973. index_offset = 0;
  1974. }
  1975. record_scope = lb_get_llvm_metadata(m, bt->Union.scope);
  1976. element_count = cast(unsigned)bt->Union.variants.count;
  1977. if (index_offset > 0) {
  1978. element_count += 1;
  1979. }
  1980. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1981. if (index_offset > 0) {
  1982. Type *tag_type = union_tag_type(bt);
  1983. unsigned field_line = 0;
  1984. u64 offset_in_bits = 8*cast(u64)bt->Union.variant_block_size;
  1985. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1986. elements[0] = LLVMDIBuilderCreateMemberType(
  1987. m->debug_builder, record_scope,
  1988. "tag", 3,
  1989. file, field_line,
  1990. 8*cast(u64)type_size_of(tag_type), 8*cast(u32)type_align_of(tag_type),
  1991. offset_in_bits,
  1992. field_flags, lb_debug_type(m, tag_type)
  1993. );
  1994. }
  1995. for_array(j, bt->Union.variants) {
  1996. Type *variant = bt->Union.variants[j];
  1997. unsigned field_index = cast(unsigned)(index_offset+j);
  1998. char name[16] = {};
  1999. gb_snprintf(name, gb_size_of(name), "v%u", field_index);
  2000. isize name_len = gb_strlen(name);
  2001. unsigned field_line = 0;
  2002. LLVMDIFlags field_flags = LLVMDIFlagZero;
  2003. u64 offset_in_bits = 0;
  2004. elements[field_index] = LLVMDIBuilderCreateMemberType(
  2005. m->debug_builder, record_scope,
  2006. name, name_len,
  2007. file, field_line,
  2008. 8*cast(u64)type_size_of(variant), 8*cast(u32)type_align_of(variant),
  2009. offset_in_bits,
  2010. field_flags, lb_debug_type(m, variant)
  2011. );
  2012. }
  2013. }
  2014. break;
  2015. case Type_BitSet:
  2016. {
  2017. if (file == nullptr) {
  2018. GB_ASSERT(bt->BitSet.node != nullptr);
  2019. file = lb_get_llvm_metadata(m, bt->BitSet.node->file);
  2020. line_number = cast(unsigned)ast_token(bt->BitSet.node).pos.line;
  2021. }
  2022. LLVMMetadataRef bit_set_field_type = lb_debug_type(m, t_bool);
  2023. LLVMMetadataRef scope = file;
  2024. Type *elem = base_type(bt->BitSet.elem);
  2025. if (elem->kind == Type_Enum) {
  2026. element_count = cast(unsigned)elem->Enum.fields.count;
  2027. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  2028. for_array(i, elem->Enum.fields) {
  2029. Entity *f = elem->Enum.fields[i];
  2030. GB_ASSERT(f->kind == Entity_Constant);
  2031. i64 val = exact_value_to_i64(f->Constant.value);
  2032. String name = f->token.string;
  2033. u64 offset_in_bits = cast(u64)(val - bt->BitSet.lower);
  2034. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  2035. m->debug_builder,
  2036. scope,
  2037. cast(char const *)name.text, name.len,
  2038. file, line_number,
  2039. 1,
  2040. offset_in_bits,
  2041. 0,
  2042. LLVMDIFlagZero,
  2043. bit_set_field_type
  2044. );
  2045. }
  2046. } else {
  2047. char name[32] = {};
  2048. GB_ASSERT(is_type_integer(elem));
  2049. i64 count = bt->BitSet.upper - bt->BitSet.lower + 1;
  2050. GB_ASSERT(0 <= count);
  2051. element_count = cast(unsigned)count;
  2052. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  2053. for (unsigned i = 0; i < element_count; i++) {
  2054. u64 offset_in_bits = i;
  2055. i64 val = bt->BitSet.lower + cast(i64)i;
  2056. gb_snprintf(name, gb_count_of(name), "%lld", cast(long long)val);
  2057. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  2058. m->debug_builder,
  2059. scope,
  2060. name, gb_strlen(name),
  2061. file, line_number,
  2062. 1,
  2063. offset_in_bits,
  2064. 0,
  2065. LLVMDIFlagZero,
  2066. bit_set_field_type
  2067. );
  2068. }
  2069. }
  2070. }
  2071. }
  2072. LLVMMetadataRef final_metadata = nullptr;
  2073. if (is_union) {
  2074. final_metadata = LLVMDIBuilderCreateUnionType(
  2075. m->debug_builder,
  2076. parent_scope,
  2077. cast(char const *)name.text, cast(size_t)name.len,
  2078. file, line_number,
  2079. size_in_bits, align_in_bits,
  2080. flags,
  2081. elements, element_count,
  2082. runtime_lang,
  2083. unique_id, unique_id_len
  2084. );
  2085. } else {
  2086. final_metadata = LLVMDIBuilderCreateStructType(
  2087. m->debug_builder,
  2088. parent_scope,
  2089. cast(char const *)name.text, cast(size_t)name.len,
  2090. file, line_number,
  2091. size_in_bits, align_in_bits,
  2092. flags,
  2093. derived_from,
  2094. elements, element_count,
  2095. runtime_lang,
  2096. vtable_holder,
  2097. unique_id, unique_id_len
  2098. );
  2099. }
  2100. LLVMMetadataReplaceAllUsesWith(idt.metadata, final_metadata);
  2101. lb_set_llvm_metadata(m, idt.type, final_metadata);
  2102. } break;
  2103. default:
  2104. GB_PANIC("invalid incomplete debug type");
  2105. break;
  2106. }
  2107. }
  2108. array_clear(&m->debug_incomplete_types);
  2109. }
  2110. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  2111. if (e != nullptr) {
  2112. map_set(&m->values, hash_entity(e), val);
  2113. }
  2114. }
  2115. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  2116. if (name.len > 0) {
  2117. string_map_set(&m->members, name, val);
  2118. }
  2119. }
  2120. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  2121. string_map_set(&m->members, key, val);
  2122. }
  2123. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  2124. if (p->entity != nullptr) {
  2125. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  2126. }
  2127. string_map_set(&m->procedures, p->name, p);
  2128. }
  2129. LLVMValueRef llvm_const_cast(LLVMValueRef val, LLVMTypeRef dst) {
  2130. LLVMTypeRef src = LLVMTypeOf(val);
  2131. if (src == dst) {
  2132. return val;
  2133. }
  2134. if (LLVMIsNull(val)) {
  2135. return LLVMConstNull(dst);
  2136. }
  2137. GB_ASSERT(LLVMSizeOf(dst) == LLVMSizeOf(src));
  2138. LLVMTypeKind kind = LLVMGetTypeKind(dst);
  2139. switch (kind) {
  2140. case LLVMPointerTypeKind:
  2141. return LLVMConstPointerCast(val, dst);
  2142. case LLVMStructTypeKind:
  2143. return LLVMConstBitCast(val, dst);
  2144. default:
  2145. GB_PANIC("Unhandled const cast %s to %s", LLVMPrintTypeToString(src), LLVMPrintTypeToString(dst));
  2146. }
  2147. return val;
  2148. }
  2149. LLVMValueRef llvm_const_named_struct(LLVMTypeRef t, LLVMValueRef *values, isize value_count_) {
  2150. unsigned value_count = cast(unsigned)value_count_;
  2151. unsigned elem_count = LLVMCountStructElementTypes(t);
  2152. GB_ASSERT(value_count == elem_count);
  2153. for (unsigned i = 0; i < elem_count; i++) {
  2154. LLVMTypeRef elem_type = LLVMStructGetTypeAtIndex(t, i);
  2155. values[i] = llvm_const_cast(values[i], elem_type);
  2156. }
  2157. return LLVMConstNamedStruct(t, values, value_count);
  2158. }
  2159. LLVMValueRef llvm_const_array(LLVMTypeRef elem_type, LLVMValueRef *values, isize value_count_) {
  2160. unsigned value_count = cast(unsigned)value_count_;
  2161. for (unsigned i = 0; i < value_count; i++) {
  2162. values[i] = llvm_const_cast(values[i], elem_type);
  2163. }
  2164. return LLVMConstArray(elem_type, values, value_count);
  2165. }
  2166. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  2167. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  2168. LLVMValueRef values[2] = {
  2169. str_elem.value,
  2170. str_len.value,
  2171. };
  2172. lbValue res = {};
  2173. res.type = t_string;
  2174. res.value = llvm_const_named_struct(lb_type(p->module, t_string), values, gb_count_of(values));
  2175. return res;
  2176. } else {
  2177. lbAddr res = lb_add_local_generated(p, t_string, false);
  2178. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  2179. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  2180. return lb_addr_load(p, res);
  2181. }
  2182. }
  2183. LLVMAttributeRef lb_create_enum_attribute_with_type(LLVMContextRef ctx, char const *name, LLVMTypeRef type) {
  2184. String s = make_string_c(name);
  2185. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  2186. // and the current LLVM C API does not expose this functionality yet.
  2187. // It is better to ignore the attributes for the time being
  2188. if (s == "byval") {
  2189. // return nullptr;
  2190. } else if (s == "byref") {
  2191. return nullptr;
  2192. } else if (s == "preallocated") {
  2193. return nullptr;
  2194. } else if (s == "sret") {
  2195. // return nullptr;
  2196. }
  2197. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  2198. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  2199. return LLVMCreateEnumAttribute(ctx, kind, 0);
  2200. }
  2201. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  2202. String s = make_string_c(name);
  2203. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  2204. // and the current LLVM C API does not expose this functionality yet.
  2205. // It is better to ignore the attributes for the time being
  2206. if (s == "byval") {
  2207. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2208. } else if (s == "byref") {
  2209. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2210. } else if (s == "preallocated") {
  2211. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2212. } else if (s == "sret") {
  2213. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2214. }
  2215. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  2216. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  2217. return LLVMCreateEnumAttribute(ctx, kind, value);
  2218. }
  2219. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  2220. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  2221. GB_ASSERT(attr != nullptr);
  2222. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  2223. }
  2224. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  2225. lb_add_proc_attribute_at_index(p, index, name, 0);
  2226. }
  2227. void lb_add_attribute_to_proc(lbModule *m, LLVMValueRef proc_value, char const *name, u64 value=0) {
  2228. LLVMAddAttributeAtIndex(proc_value, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(m->ctx, name, value));
  2229. }
  2230. void lb_ensure_abi_function_type(lbModule *m, lbProcedure *p) {
  2231. if (p->abi_function_type != nullptr) {
  2232. return;
  2233. }
  2234. auto hash = hash_type(p->type);
  2235. lbFunctionType **ft_found = map_get(&m->function_type_map, hash);
  2236. if (ft_found == nullptr) {
  2237. LLVMTypeRef llvm_proc_type = lb_type(p->module, p->type);
  2238. ft_found = map_get(&m->function_type_map, hash);
  2239. }
  2240. GB_ASSERT(ft_found != nullptr);
  2241. p->abi_function_type = *ft_found;
  2242. GB_ASSERT(p->abi_function_type != nullptr);
  2243. }
  2244. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity, bool ignore_body) {
  2245. GB_ASSERT(entity != nullptr);
  2246. GB_ASSERT(entity->kind == Entity_Procedure);
  2247. String link_name = {};
  2248. if (ignore_body) {
  2249. lbModule *other_module = lb_pkg_module(m->gen, entity->pkg);
  2250. link_name = lb_get_entity_name(other_module, entity);
  2251. } else {
  2252. link_name = lb_get_entity_name(m, entity);
  2253. }
  2254. {
  2255. StringHashKey key = string_hash_string(link_name);
  2256. lbValue *found = string_map_get(&m->members, key);
  2257. if (found) {
  2258. lb_add_entity(m, entity, *found);
  2259. lbProcedure **p_found = string_map_get(&m->procedures, key);
  2260. GB_ASSERT(p_found != nullptr);
  2261. return *p_found;
  2262. }
  2263. }
  2264. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2265. p->module = m;
  2266. entity->code_gen_module = m;
  2267. entity->code_gen_procedure = p;
  2268. p->entity = entity;
  2269. p->name = link_name;
  2270. DeclInfo *decl = entity->decl_info;
  2271. ast_node(pl, ProcLit, decl->proc_lit);
  2272. Type *pt = base_type(entity->type);
  2273. GB_ASSERT(pt->kind == Type_Proc);
  2274. p->type = entity->type;
  2275. p->type_expr = decl->type_expr;
  2276. p->body = pl->body;
  2277. p->inlining = pl->inlining;
  2278. p->is_foreign = entity->Procedure.is_foreign;
  2279. p->is_export = entity->Procedure.is_export;
  2280. p->is_entry_point = false;
  2281. gbAllocator a = heap_allocator();
  2282. p->children.allocator = a;
  2283. p->params.allocator = a;
  2284. p->defer_stmts.allocator = a;
  2285. p->blocks.allocator = a;
  2286. p->branch_blocks.allocator = a;
  2287. p->context_stack.allocator = a;
  2288. p->scope_stack.allocator = a;
  2289. if (p->is_foreign) {
  2290. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  2291. }
  2292. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2293. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2294. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2295. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2296. lb_ensure_abi_function_type(m, p);
  2297. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  2298. if (false) {
  2299. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2300. // TODO(bill): Clean up this logic
  2301. if (build_context.metrics.os != TargetOs_js) {
  2302. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2303. }
  2304. LLVMSetFunctionCallConv(p->value, cc_kind);
  2305. }
  2306. if (pt->Proc.diverging) {
  2307. lb_add_attribute_to_proc(m, p->value, "noreturn");
  2308. }
  2309. if (pt->Proc.calling_convention == ProcCC_Naked) {
  2310. lb_add_attribute_to_proc(m, p->value, "naked");
  2311. }
  2312. switch (p->inlining) {
  2313. case ProcInlining_inline:
  2314. lb_add_attribute_to_proc(m, p->value, "alwaysinline");
  2315. break;
  2316. case ProcInlining_no_inline:
  2317. lb_add_attribute_to_proc(m, p->value, "noinline");
  2318. break;
  2319. }
  2320. if (entity->flags & EntityFlag_Cold) {
  2321. lb_add_attribute_to_proc(m, p->value, "cold");
  2322. }
  2323. switch (entity->Procedure.optimization_mode) {
  2324. case ProcedureOptimizationMode_None:
  2325. lb_add_attribute_to_proc(m, p->value, "optnone");
  2326. break;
  2327. case ProcedureOptimizationMode_Minimal:
  2328. lb_add_attribute_to_proc(m, p->value, "optnone");
  2329. break;
  2330. case ProcedureOptimizationMode_Size:
  2331. lb_add_attribute_to_proc(m, p->value, "optsize");
  2332. break;
  2333. case ProcedureOptimizationMode_Speed:
  2334. // TODO(bill): handle this correctly
  2335. lb_add_attribute_to_proc(m, p->value, "optsize");
  2336. break;
  2337. }
  2338. // lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2339. // // TODO(bill): Clean up this logic
  2340. // if (build_context.metrics.os != TargetOs_js) {
  2341. // cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2342. // }
  2343. // LLVMSetFunctionCallConv(p->value, cc_kind);
  2344. lbValue proc_value = {p->value, p->type};
  2345. lb_add_entity(m, entity, proc_value);
  2346. lb_add_member(m, p->name, proc_value);
  2347. lb_add_procedure_value(m, p);
  2348. if (p->is_export) {
  2349. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  2350. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  2351. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  2352. if (build_context.metrics.os == TargetOs_js) {
  2353. char const *export_name = alloc_cstring(permanent_allocator(), p->name);
  2354. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  2355. }
  2356. }
  2357. if (p->is_foreign) {
  2358. if (build_context.metrics.os == TargetOs_js) {
  2359. char const *import_name = alloc_cstring(permanent_allocator(), p->name);
  2360. char const *module_name = "env";
  2361. if (entity->Procedure.foreign_library != nullptr) {
  2362. Entity *foreign_library = entity->Procedure.foreign_library;
  2363. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  2364. if (foreign_library->LibraryName.paths.count > 0) {
  2365. module_name = alloc_cstring(permanent_allocator(), foreign_library->LibraryName.paths[0]);
  2366. }
  2367. }
  2368. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  2369. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  2370. }
  2371. }
  2372. // NOTE(bill): offset==0 is the return value
  2373. isize offset = 1;
  2374. if (pt->Proc.return_by_pointer) {
  2375. offset = 2;
  2376. }
  2377. isize parameter_index = 0;
  2378. if (pt->Proc.param_count) {
  2379. TypeTuple *params = &pt->Proc.params->Tuple;
  2380. for (isize i = 0; i < pt->Proc.param_count; i++) {
  2381. Entity *e = params->variables[i];
  2382. Type *original_type = e->type;
  2383. if (e->kind != Entity_Variable) continue;
  2384. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  2385. continue;
  2386. }
  2387. if (e->flags&EntityFlag_NoAlias) {
  2388. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2389. }
  2390. parameter_index += 1;
  2391. }
  2392. }
  2393. if (ignore_body) {
  2394. p->body = nullptr;
  2395. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  2396. }
  2397. if (m->debug_builder) { // Debug Information
  2398. Type *bt = base_type(p->type);
  2399. unsigned line = cast(unsigned)entity->token.pos.line;
  2400. LLVMMetadataRef scope = nullptr;
  2401. LLVMMetadataRef file = nullptr;
  2402. LLVMMetadataRef type = nullptr;
  2403. scope = p->module->debug_compile_unit;
  2404. type = lb_debug_type_internal_proc(m, bt);
  2405. if (entity->file != nullptr) {
  2406. file = lb_get_llvm_metadata(m, entity->file);
  2407. scope = file;
  2408. } else if (entity->identifier != nullptr && entity->identifier->file != nullptr) {
  2409. file = lb_get_llvm_metadata(m, entity->identifier->file);
  2410. scope = file;
  2411. } else if (entity->scope != nullptr) {
  2412. file = lb_get_llvm_metadata(m, entity->scope->file);
  2413. scope = file;
  2414. }
  2415. GB_ASSERT_MSG(file != nullptr, "%.*s", LIT(entity->token.string));
  2416. // LLVMBool is_local_to_unit = !entity->Procedure.is_export;
  2417. LLVMBool is_local_to_unit = false;
  2418. LLVMBool is_definition = p->body != nullptr;
  2419. unsigned scope_line = line;
  2420. u32 flags = LLVMDIFlagStaticMember;
  2421. LLVMBool is_optimized = false;
  2422. if (bt->Proc.diverging) {
  2423. flags |= LLVMDIFlagNoReturn;
  2424. }
  2425. if (p->body == nullptr) {
  2426. flags |= LLVMDIFlagPrototyped;
  2427. is_optimized = false;
  2428. }
  2429. if (p->body != nullptr) {
  2430. p->debug_info = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  2431. cast(char const *)entity->token.string.text, entity->token.string.len,
  2432. cast(char const *)p->name.text, p->name.len,
  2433. file, line, type,
  2434. is_local_to_unit, is_definition,
  2435. scope_line, cast(LLVMDIFlags)flags, is_optimized
  2436. );
  2437. GB_ASSERT(p->debug_info != nullptr);
  2438. LLVMSetSubprogram(p->value, p->debug_info);
  2439. lb_set_llvm_metadata(m, p, p->debug_info);
  2440. }
  2441. }
  2442. return p;
  2443. }
  2444. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  2445. {
  2446. lbValue *found = string_map_get(&m->members, link_name);
  2447. GB_ASSERT(found == nullptr);
  2448. }
  2449. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2450. p->module = m;
  2451. p->name = link_name;
  2452. p->type = type;
  2453. p->type_expr = nullptr;
  2454. p->body = nullptr;
  2455. p->tags = 0;
  2456. p->inlining = ProcInlining_none;
  2457. p->is_foreign = false;
  2458. p->is_export = false;
  2459. p->is_entry_point = false;
  2460. gbAllocator a = permanent_allocator();
  2461. p->children.allocator = a;
  2462. p->params.allocator = a;
  2463. p->defer_stmts.allocator = a;
  2464. p->blocks.allocator = a;
  2465. p->branch_blocks.allocator = a;
  2466. p->context_stack.allocator = a;
  2467. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2468. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2469. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2470. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2471. Type *pt = p->type;
  2472. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2473. // TODO(bill): Clean up this logic
  2474. if (build_context.metrics.os != TargetOs_js) {
  2475. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2476. }
  2477. LLVMSetFunctionCallConv(p->value, cc_kind);
  2478. lbValue proc_value = {p->value, p->type};
  2479. lb_add_member(m, p->name, proc_value);
  2480. lb_add_procedure_value(m, p);
  2481. // NOTE(bill): offset==0 is the return value
  2482. isize offset = 1;
  2483. if (pt->Proc.return_by_pointer) {
  2484. lb_add_proc_attribute_at_index(p, 1, "sret");
  2485. lb_add_proc_attribute_at_index(p, 1, "noalias");
  2486. offset = 2;
  2487. }
  2488. isize parameter_index = 0;
  2489. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2490. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2491. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  2492. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  2493. }
  2494. return p;
  2495. }
  2496. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  2497. lbParamPasskind kind = lbParamPass_Value;
  2498. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  2499. if (is_type_pointer(abi_type)) {
  2500. GB_ASSERT(e->kind == Entity_Variable);
  2501. Type *av = core_type(type_deref(abi_type));
  2502. if (are_types_identical(av, core_type(e->type))) {
  2503. kind = lbParamPass_Pointer;
  2504. if (e->flags&EntityFlag_Value) {
  2505. kind = lbParamPass_ConstRef;
  2506. }
  2507. } else {
  2508. kind = lbParamPass_BitCast;
  2509. }
  2510. } else if (is_type_integer(abi_type)) {
  2511. kind = lbParamPass_Integer;
  2512. } else if (abi_type == t_llvm_bool) {
  2513. kind = lbParamPass_Value;
  2514. } else if (is_type_boolean(abi_type)) {
  2515. kind = lbParamPass_Integer;
  2516. } else if (is_type_simd_vector(abi_type)) {
  2517. kind = lbParamPass_BitCast;
  2518. } else if (is_type_float(abi_type)) {
  2519. kind = lbParamPass_BitCast;
  2520. } else if (is_type_tuple(abi_type)) {
  2521. kind = lbParamPass_Tuple;
  2522. } else if (is_type_proc(abi_type)) {
  2523. kind = lbParamPass_Value;
  2524. } else {
  2525. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  2526. }
  2527. }
  2528. if (kind_) *kind_ = kind;
  2529. lbValue res = {};
  2530. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  2531. res.type = abi_type;
  2532. return res;
  2533. }
  2534. Type *struct_type_from_systemv_distribute_struct_fields(Type *abi_type) {
  2535. GB_ASSERT(is_type_tuple(abi_type));
  2536. Type *final_type = alloc_type_struct();
  2537. final_type->Struct.fields = abi_type->Tuple.variables;
  2538. return final_type;
  2539. }
  2540. void lb_start_block(lbProcedure *p, lbBlock *b) {
  2541. GB_ASSERT(b != nullptr);
  2542. if (!b->appended) {
  2543. b->appended = true;
  2544. LLVMAppendExistingBasicBlock(p->value, b->block);
  2545. }
  2546. LLVMPositionBuilderAtEnd(p->builder, b->block);
  2547. p->curr_block = b;
  2548. }
  2549. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  2550. LLVMContextRef ctx = p->module->ctx;
  2551. LLVMTypeRef src_type = LLVMTypeOf(val);
  2552. if (src_type == dst_type) {
  2553. return val;
  2554. }
  2555. i64 src_size = lb_sizeof(src_type);
  2556. i64 dst_size = lb_sizeof(dst_type);
  2557. i64 src_align = lb_alignof(src_type);
  2558. i64 dst_align = lb_alignof(dst_type);
  2559. if (LLVMIsALoadInst(val)) {
  2560. src_align = gb_min(src_align, LLVMGetAlignment(val));
  2561. }
  2562. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  2563. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  2564. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  2565. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2566. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  2567. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  2568. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2569. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  2570. }
  2571. if (src_size != dst_size) {
  2572. if ((lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  2573. // Okay
  2574. } else {
  2575. goto general_end;
  2576. }
  2577. }
  2578. if (src_kind == dst_kind) {
  2579. if (src_kind == LLVMPointerTypeKind) {
  2580. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  2581. } else if (src_kind == LLVMArrayTypeKind) {
  2582. // ignore
  2583. } else if (src_kind != LLVMStructTypeKind) {
  2584. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  2585. }
  2586. } else {
  2587. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  2588. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  2589. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  2590. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  2591. }
  2592. }
  2593. general_end:;
  2594. // make the alignment big if necessary
  2595. if (LLVMIsALoadInst(val) && src_align < dst_align) {
  2596. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2597. if (LLVMGetInstructionOpcode(val_ptr) == LLVMAlloca) {
  2598. src_align = gb_max(LLVMGetAlignment(val_ptr), dst_align);
  2599. LLVMSetAlignment(val_ptr, cast(unsigned)src_align);
  2600. }
  2601. }
  2602. src_size = align_formula(src_size, src_align);
  2603. dst_size = align_formula(dst_size, dst_align);
  2604. if (LLVMIsALoadInst(val) && (src_size >= dst_size && src_align >= dst_align)) {
  2605. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2606. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  2607. LLVMValueRef loaded_val = LLVMBuildLoad(p->builder, val_ptr, "");
  2608. // LLVMSetAlignment(loaded_val, gb_min(src_align, dst_align));
  2609. return loaded_val;
  2610. } else {
  2611. GB_ASSERT(p->decl_block != p->curr_block);
  2612. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2613. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  2614. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2615. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2616. max_align = gb_max(max_align, 4);
  2617. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  2618. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2619. LLVMBuildStore(p->builder, val, nptr);
  2620. return LLVMBuildLoad(p->builder, ptr, "");
  2621. }
  2622. }
  2623. void lb_add_debug_local_variable(lbProcedure *p, LLVMValueRef ptr, Type *type, Token const &token) {
  2624. if (p->debug_info == nullptr) {
  2625. return;
  2626. }
  2627. if (type == nullptr) {
  2628. return;
  2629. }
  2630. if (type == t_invalid) {
  2631. return;
  2632. }
  2633. if (p->body == nullptr) {
  2634. return;
  2635. }
  2636. lbModule *m = p->module;
  2637. String const &name = token.string;
  2638. if (name == "" || name == "_") {
  2639. return;
  2640. }
  2641. if (lb_get_llvm_metadata(m, ptr) != nullptr) {
  2642. // Already been set
  2643. return;
  2644. }
  2645. AstFile *file = p->body->file;
  2646. LLVMMetadataRef llvm_scope = lb_get_current_debug_scope(p);
  2647. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, file);
  2648. GB_ASSERT(llvm_scope != nullptr);
  2649. if (llvm_file == nullptr) {
  2650. llvm_file = LLVMDIScopeGetFile(llvm_scope);
  2651. }
  2652. if (llvm_file == nullptr) {
  2653. return;
  2654. }
  2655. unsigned alignment_in_bits = cast(unsigned)(8*type_align_of(type));
  2656. LLVMDIFlags flags = LLVMDIFlagZero;
  2657. LLVMBool always_preserve = build_context.optimization_level == 0;
  2658. LLVMMetadataRef debug_type = lb_debug_type(m, type);
  2659. LLVMMetadataRef var_info = LLVMDIBuilderCreateAutoVariable(
  2660. m->debug_builder, llvm_scope,
  2661. cast(char const *)name.text, cast(size_t)name.len,
  2662. llvm_file, token.pos.line,
  2663. debug_type,
  2664. always_preserve, flags, alignment_in_bits
  2665. );
  2666. LLVMValueRef storage = ptr;
  2667. LLVMValueRef instr = ptr;
  2668. LLVMMetadataRef llvm_debug_loc = lb_debug_location_from_token_pos(p, token.pos);
  2669. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  2670. lb_set_llvm_metadata(m, ptr, llvm_expr);
  2671. LLVMDIBuilderInsertDeclareBefore(m->debug_builder, storage, var_info, llvm_expr, llvm_debug_loc, instr);
  2672. }
  2673. void lb_add_debug_context_variable(lbProcedure *p, lbAddr const &ctx) {
  2674. if (!p->debug_info || !p->body) {
  2675. return;
  2676. }
  2677. LLVMMetadataRef loc = LLVMGetCurrentDebugLocation2(p->builder);
  2678. if (!loc) {
  2679. return;
  2680. }
  2681. TokenPos pos = {};
  2682. pos.file_id = p->body->file ? p->body->file->id : 0;
  2683. pos.line = LLVMDILocationGetLine(loc);
  2684. pos.column = LLVMDILocationGetColumn(loc);
  2685. Token token = {};
  2686. token.kind = Token_context;
  2687. token.string = str_lit("context");
  2688. token.pos = pos;
  2689. lb_add_debug_local_variable(p, ctx.addr.value, t_context, token);
  2690. }
  2691. void lb_begin_procedure_body(lbProcedure *p) {
  2692. DeclInfo *decl = decl_info_of_entity(p->entity);
  2693. if (decl != nullptr) {
  2694. for_array(i, decl->labels) {
  2695. BlockLabel bl = decl->labels[i];
  2696. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2697. array_add(&p->branch_blocks, bb);
  2698. }
  2699. }
  2700. p->builder = LLVMCreateBuilderInContext(p->module->ctx);
  2701. p->decl_block = lb_create_block(p, "decls", true);
  2702. p->entry_block = lb_create_block(p, "entry", true);
  2703. lb_start_block(p, p->entry_block);
  2704. GB_ASSERT(p->type != nullptr);
  2705. lb_ensure_abi_function_type(p->module, p);
  2706. {
  2707. lbFunctionType *ft = p->abi_function_type;
  2708. unsigned param_offset = 0;
  2709. lbValue return_ptr_value = {};
  2710. if (ft->ret.kind == lbArg_Indirect) {
  2711. // NOTE(bill): this must be parameter 0
  2712. String name = str_lit("agg.result");
  2713. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2714. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), ptr_type, false, false);
  2715. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2716. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2717. LLVMSetValueName2(return_ptr_value.value, cast(char const *)name.text, name.len);
  2718. return_ptr_value.type = ptr_type;
  2719. p->return_ptr = lb_addr(return_ptr_value);
  2720. lb_add_entity(p->module, e, return_ptr_value);
  2721. param_offset += 1;
  2722. }
  2723. if (p->type->Proc.params != nullptr) {
  2724. TypeTuple *params = &p->type->Proc.params->Tuple;
  2725. unsigned param_index = 0;
  2726. for_array(i, params->variables) {
  2727. Entity *e = params->variables[i];
  2728. if (e->kind != Entity_Variable) {
  2729. continue;
  2730. }
  2731. lbArgType *arg_type = &ft->args[param_index];
  2732. if (arg_type->kind == lbArg_Ignore) {
  2733. continue;
  2734. } else if (arg_type->kind == lbArg_Direct) {
  2735. lbParamPasskind kind = lbParamPass_Value;
  2736. LLVMTypeRef param_type = lb_type(p->module, e->type);
  2737. if (param_type != arg_type->type) {
  2738. kind = lbParamPass_BitCast;
  2739. }
  2740. LLVMValueRef value = LLVMGetParam(p->value, param_offset+param_index);
  2741. value = OdinLLVMBuildTransmute(p, value, param_type);
  2742. lbValue param = {};
  2743. param.value = value;
  2744. param.type = e->type;
  2745. array_add(&p->params, param);
  2746. if (e->token.string.len != 0) {
  2747. lbAddr l = lb_add_local(p, e->type, e, false, param_index);
  2748. lb_addr_store(p, l, param);
  2749. }
  2750. param_index += 1;
  2751. } else if (arg_type->kind == lbArg_Indirect) {
  2752. LLVMValueRef value_ptr = LLVMGetParam(p->value, param_offset+param_index);
  2753. LLVMValueRef value = LLVMBuildLoad(p->builder, value_ptr, "");
  2754. lbValue param = {};
  2755. param.value = value;
  2756. param.type = e->type;
  2757. array_add(&p->params, param);
  2758. lbValue ptr = {};
  2759. ptr.value = value_ptr;
  2760. ptr.type = alloc_type_pointer(e->type);
  2761. lb_add_entity(p->module, e, ptr);
  2762. param_index += 1;
  2763. }
  2764. }
  2765. }
  2766. if (p->type->Proc.has_named_results) {
  2767. GB_ASSERT(p->type->Proc.result_count > 0);
  2768. TypeTuple *results = &p->type->Proc.results->Tuple;
  2769. for_array(i, results->variables) {
  2770. Entity *e = results->variables[i];
  2771. GB_ASSERT(e->kind == Entity_Variable);
  2772. if (e->token.string != "") {
  2773. GB_ASSERT(!is_blank_ident(e->token));
  2774. lbAddr res = {};
  2775. if (return_ptr_value.value) {
  2776. lbValue ptr = return_ptr_value;
  2777. if (results->variables.count != 1) {
  2778. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2779. }
  2780. res = lb_addr(ptr);
  2781. lb_add_entity(p->module, e, ptr);
  2782. } else {
  2783. res = lb_add_local(p, e->type, e);
  2784. }
  2785. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2786. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2787. lb_addr_store(p, res, c);
  2788. }
  2789. }
  2790. }
  2791. }
  2792. }
  2793. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2794. lb_push_context_onto_stack_from_implicit_parameter(p);
  2795. }
  2796. lb_start_block(p, p->entry_block);
  2797. if (p->debug_info != nullptr) {
  2798. TokenPos pos = {};
  2799. if (p->body != nullptr) {
  2800. pos = ast_token(p->body).pos;
  2801. } else if (p->type_expr != nullptr) {
  2802. pos = ast_token(p->type_expr).pos;
  2803. } else if (p->entity != nullptr) {
  2804. pos = p->entity->token.pos;
  2805. }
  2806. if (pos.file_id != 0) {
  2807. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  2808. }
  2809. if (p->context_stack.count != 0) {
  2810. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  2811. }
  2812. }
  2813. }
  2814. void lb_end_procedure_body(lbProcedure *p) {
  2815. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2816. LLVMBuildBr(p->builder, p->entry_block->block);
  2817. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2818. LLVMValueRef instr = nullptr;
  2819. // Make sure there is a "ret void" at the end of a procedure with no return type
  2820. if (p->type->Proc.result_count == 0) {
  2821. instr = LLVMGetLastInstruction(p->curr_block->block);
  2822. if (!lb_is_instr_terminating(instr)) {
  2823. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2824. LLVMBuildRetVoid(p->builder);
  2825. }
  2826. }
  2827. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  2828. LLVMBasicBlockRef block = nullptr;
  2829. // Make sure every block terminates, and if not, make it unreachable
  2830. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  2831. instr = LLVMGetLastInstruction(block);
  2832. if (instr == nullptr || !lb_is_instr_terminating(instr)) {
  2833. LLVMPositionBuilderAtEnd(p->builder, block);
  2834. LLVMBuildUnreachable(p->builder);
  2835. }
  2836. }
  2837. p->curr_block = nullptr;
  2838. p->state_flags = 0;
  2839. }
  2840. void lb_end_procedure(lbProcedure *p) {
  2841. LLVMDisposeBuilder(p->builder);
  2842. }
  2843. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2844. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2845. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2846. array_add(&from->succs, to);
  2847. array_add(&to->preds, from);
  2848. }
  2849. }
  2850. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2851. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  2852. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2853. b->appended = false;
  2854. if (append) {
  2855. b->appended = true;
  2856. LLVMAppendExistingBasicBlock(p->value, b->block);
  2857. }
  2858. b->scope = p->curr_scope;
  2859. b->scope_index = p->scope_index;
  2860. b->preds.allocator = heap_allocator();
  2861. b->succs.allocator = heap_allocator();
  2862. array_add(&p->blocks, b);
  2863. return b;
  2864. }
  2865. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2866. if (p->curr_block == nullptr) {
  2867. return;
  2868. }
  2869. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2870. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2871. return;
  2872. }
  2873. lb_add_edge(p->curr_block, target_block);
  2874. LLVMBuildBr(p->builder, target_block->block);
  2875. p->curr_block = nullptr;
  2876. }
  2877. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2878. lbBlock *b = p->curr_block;
  2879. if (b == nullptr) {
  2880. return;
  2881. }
  2882. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2883. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2884. return;
  2885. }
  2886. lb_add_edge(b, true_block);
  2887. lb_add_edge(b, false_block);
  2888. LLVMValueRef cv = cond.value;
  2889. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2890. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2891. }
  2892. bool lb_is_expr_untyped_const(Ast *expr) {
  2893. auto const &tv = type_and_value_of_expr(expr);
  2894. if (is_type_untyped(tv.type)) {
  2895. return tv.value.kind != ExactValue_Invalid;
  2896. }
  2897. return false;
  2898. }
  2899. lbValue lb_expr_untyped_const_to_typed(lbModule *m, Ast *expr, Type *t) {
  2900. GB_ASSERT(is_type_typed(t));
  2901. auto const &tv = type_and_value_of_expr(expr);
  2902. return lb_const_value(m, t, tv.value);
  2903. }
  2904. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2905. GB_ASSERT(cond != nullptr);
  2906. GB_ASSERT(true_block != nullptr);
  2907. GB_ASSERT(false_block != nullptr);
  2908. switch (cond->kind) {
  2909. case_ast_node(pe, ParenExpr, cond);
  2910. return lb_build_cond(p, pe->expr, true_block, false_block);
  2911. case_end;
  2912. case_ast_node(ue, UnaryExpr, cond);
  2913. if (ue->op.kind == Token_Not) {
  2914. return lb_build_cond(p, ue->expr, false_block, true_block);
  2915. }
  2916. case_end;
  2917. case_ast_node(be, BinaryExpr, cond);
  2918. if (be->op.kind == Token_CmpAnd) {
  2919. lbBlock *block = lb_create_block(p, "cmp.and");
  2920. lb_build_cond(p, be->left, block, false_block);
  2921. lb_start_block(p, block);
  2922. return lb_build_cond(p, be->right, true_block, false_block);
  2923. } else if (be->op.kind == Token_CmpOr) {
  2924. lbBlock *block = lb_create_block(p, "cmp.or");
  2925. lb_build_cond(p, be->left, true_block, block);
  2926. lb_start_block(p, block);
  2927. return lb_build_cond(p, be->right, true_block, false_block);
  2928. }
  2929. case_end;
  2930. }
  2931. lbValue v = {};
  2932. if (lb_is_expr_untyped_const(cond)) {
  2933. v = lb_expr_untyped_const_to_typed(p->module, cond, t_llvm_bool);
  2934. } else {
  2935. v = lb_build_expr(p, cond);
  2936. }
  2937. v = lb_emit_conv(p, v, t_llvm_bool);
  2938. lb_emit_if(p, v, true_block, false_block);
  2939. return v;
  2940. }
  2941. void lb_mem_zero_ptr_internal(lbProcedure *p, LLVMValueRef ptr, LLVMValueRef len, unsigned alignment) {
  2942. bool is_inlinable = false;
  2943. i64 const_len = 0;
  2944. if (LLVMIsConstant(len)) {
  2945. const_len = cast(i64)LLVMConstIntGetSExtValue(len);
  2946. // TODO(bill): Determine when it is better to do the `*.inline` versions
  2947. if (const_len <= 4*build_context.word_size) {
  2948. is_inlinable = true;
  2949. }
  2950. }
  2951. char const *name = "llvm.memset";
  2952. if (is_inlinable) {
  2953. name = "llvm.memset.inline";
  2954. }
  2955. LLVMTypeRef types[2] = {
  2956. lb_type(p->module, t_rawptr),
  2957. lb_type(p->module, t_int)
  2958. };
  2959. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  2960. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s.%s.%s", name, LLVMPrintTypeToString(types[0]), LLVMPrintTypeToString(types[1]), LLVMPrintTypeToString(types[2]));
  2961. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  2962. LLVMValueRef args[4] = {};
  2963. args[0] = LLVMBuildPointerCast(p->builder, ptr, types[0], "");
  2964. args[1] = LLVMConstInt(LLVMInt8TypeInContext(p->module->ctx), 0, false);
  2965. args[2] = LLVMBuildIntCast2(p->builder, len, types[1], /*signed*/false, "");
  2966. args[3] = LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, false); // is_volatile parameter
  2967. LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  2968. }
  2969. void lb_mem_zero_ptr(lbProcedure *p, LLVMValueRef ptr, Type *type, unsigned alignment) {
  2970. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2971. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  2972. switch (kind) {
  2973. case LLVMStructTypeKind:
  2974. case LLVMArrayTypeKind:
  2975. {
  2976. // NOTE(bill): Enforce zeroing through memset to make sure padding is zeroed too
  2977. i32 sz = cast(i32)type_size_of(type);
  2978. lb_mem_zero_ptr_internal(p, ptr, lb_const_int(p->module, t_int, sz).value, alignment);
  2979. }
  2980. break;
  2981. default:
  2982. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  2983. break;
  2984. }
  2985. }
  2986. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  2987. GB_ASSERT(p->decl_block != p->curr_block);
  2988. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2989. char const *name = "";
  2990. if (e != nullptr) {
  2991. // name = alloc_cstring(permanent_allocator(), e->token.string);
  2992. }
  2993. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2994. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2995. // unsigned alignment = 16; // TODO(bill): Make this configurable
  2996. unsigned alignment = cast(unsigned)lb_alignof(llvm_type);
  2997. LLVMSetAlignment(ptr, alignment);
  2998. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2999. if (!zero_init) {
  3000. // If there is any padding of any kind, just zero init regardless of zero_init parameter
  3001. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  3002. if (kind == LLVMStructTypeKind) {
  3003. i64 sz = type_size_of(type);
  3004. if (type_size_of_struct_pretend_is_packed(type) != sz) {
  3005. zero_init = true;
  3006. }
  3007. } else if (kind == LLVMArrayTypeKind) {
  3008. zero_init = true;
  3009. }
  3010. }
  3011. if (zero_init) {
  3012. lb_mem_zero_ptr(p, ptr, type, alignment);
  3013. }
  3014. lbValue val = {};
  3015. val.value = ptr;
  3016. val.type = alloc_type_pointer(type);
  3017. if (e != nullptr) {
  3018. lb_add_entity(p->module, e, val);
  3019. lb_add_debug_local_variable(p, ptr, type, e->token);
  3020. }
  3021. return lb_addr(val);
  3022. }
  3023. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  3024. return lb_add_local(p, type, nullptr, zero_init);
  3025. }
  3026. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  3027. GB_ASSERT(pd->body != nullptr);
  3028. lbModule *m = p->module;
  3029. auto *min_dep_set = &m->info->minimum_dependency_set;
  3030. if (ptr_set_exists(min_dep_set, e) == false) {
  3031. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  3032. return;
  3033. }
  3034. // NOTE(bill): Generate a new name
  3035. // parent.name-guid
  3036. String original_name = e->token.string;
  3037. String pd_name = original_name;
  3038. if (e->Procedure.link_name.len > 0) {
  3039. pd_name = e->Procedure.link_name;
  3040. }
  3041. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  3042. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  3043. i32 guid = cast(i32)p->children.count;
  3044. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  3045. String name = make_string(cast(u8 *)name_text, name_len-1);
  3046. e->Procedure.link_name = name;
  3047. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  3048. e->code_gen_procedure = nested_proc;
  3049. lbValue value = {};
  3050. value.value = nested_proc->value;
  3051. value.type = nested_proc->type;
  3052. lb_add_entity(m, e, value);
  3053. array_add(&p->children, nested_proc);
  3054. array_add(&m->procedures_to_generate, nested_proc);
  3055. }
  3056. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  3057. if (e == nullptr) {
  3058. return;
  3059. }
  3060. GB_ASSERT(e->kind == Entity_LibraryName);
  3061. GB_ASSERT(e->flags & EntityFlag_Used);
  3062. for_array(i, e->LibraryName.paths) {
  3063. String library_path = e->LibraryName.paths[i];
  3064. if (library_path.len == 0) {
  3065. continue;
  3066. }
  3067. bool ok = true;
  3068. for_array(path_index, m->foreign_library_paths) {
  3069. String path = m->foreign_library_paths[path_index];
  3070. #if defined(GB_SYSTEM_WINDOWS)
  3071. if (str_eq_ignore_case(path, library_path)) {
  3072. #else
  3073. if (str_eq(path, library_path)) {
  3074. #endif
  3075. ok = false;
  3076. break;
  3077. }
  3078. }
  3079. if (ok) {
  3080. array_add(&m->foreign_library_paths, library_path);
  3081. }
  3082. }
  3083. }
  3084. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  3085. if (vd == nullptr || vd->is_mutable) {
  3086. return;
  3087. }
  3088. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  3089. static i32 global_guid = 0;
  3090. for_array(i, vd->names) {
  3091. Ast *ident = vd->names[i];
  3092. GB_ASSERT(ident->kind == Ast_Ident);
  3093. Entity *e = entity_of_node(ident);
  3094. GB_ASSERT(e != nullptr);
  3095. if (e->kind != Entity_TypeName) {
  3096. continue;
  3097. }
  3098. bool polymorphic_struct = false;
  3099. if (e->type != nullptr && e->kind == Entity_TypeName) {
  3100. Type *bt = base_type(e->type);
  3101. if (bt->kind == Type_Struct) {
  3102. polymorphic_struct = bt->Struct.is_polymorphic;
  3103. }
  3104. }
  3105. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  3106. continue;
  3107. }
  3108. if (e->TypeName.ir_mangled_name.len != 0) {
  3109. // NOTE(bill): Already set
  3110. continue;
  3111. }
  3112. lb_set_nested_type_name_ir_mangled_name(e, p);
  3113. }
  3114. for_array(i, vd->names) {
  3115. Ast *ident = vd->names[i];
  3116. GB_ASSERT(ident->kind == Ast_Ident);
  3117. Entity *e = entity_of_node(ident);
  3118. GB_ASSERT(e != nullptr);
  3119. if (e->kind != Entity_Procedure) {
  3120. continue;
  3121. }
  3122. GB_ASSERT (vd->values[i] != nullptr);
  3123. Ast *value = unparen_expr(vd->values[i]);
  3124. if (value->kind != Ast_ProcLit) {
  3125. continue; // It's an alias
  3126. }
  3127. CheckerInfo *info = p->module->info;
  3128. DeclInfo *decl = decl_info_of_entity(e);
  3129. ast_node(pl, ProcLit, decl->proc_lit);
  3130. if (pl->body != nullptr) {
  3131. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  3132. if (found) {
  3133. auto procs = *found;
  3134. for_array(i, procs) {
  3135. Entity *e = procs[i];
  3136. if (!ptr_set_exists(min_dep_set, e)) {
  3137. continue;
  3138. }
  3139. DeclInfo *d = decl_info_of_entity(e);
  3140. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  3141. }
  3142. } else {
  3143. lb_build_nested_proc(p, pl, e);
  3144. }
  3145. } else {
  3146. // FFI - Foreign function interace
  3147. String original_name = e->token.string;
  3148. String name = original_name;
  3149. if (e->Procedure.is_foreign) {
  3150. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  3151. }
  3152. if (e->Procedure.link_name.len > 0) {
  3153. name = e->Procedure.link_name;
  3154. }
  3155. lbValue *prev_value = string_map_get(&p->module->members, name);
  3156. if (prev_value != nullptr) {
  3157. // NOTE(bill): Don't do mutliple declarations in the IR
  3158. return;
  3159. }
  3160. e->Procedure.link_name = name;
  3161. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  3162. lbValue value = {};
  3163. value.value = nested_proc->value;
  3164. value.type = nested_proc->type;
  3165. array_add(&p->module->procedures_to_generate, nested_proc);
  3166. array_add(&p->children, nested_proc);
  3167. string_map_set(&p->module->members, name, value);
  3168. }
  3169. }
  3170. }
  3171. void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  3172. for_array(i, stmts) {
  3173. Ast *stmt = stmts[i];
  3174. switch (stmt->kind) {
  3175. case_ast_node(vd, ValueDecl, stmt);
  3176. lb_build_constant_value_decl(p, vd);
  3177. case_end;
  3178. case_ast_node(fb, ForeignBlockDecl, stmt);
  3179. ast_node(block, BlockStmt, fb->body);
  3180. lb_build_stmt_list(p, block->stmts);
  3181. case_end;
  3182. }
  3183. }
  3184. for_array(i, stmts) {
  3185. lb_build_stmt(p, stmts[i]);
  3186. }
  3187. }
  3188. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  3189. GB_ASSERT(ident->kind == Ast_Ident);
  3190. Entity *e = entity_of_node(ident);
  3191. GB_ASSERT(e->kind == Entity_Label);
  3192. for_array(i, p->branch_blocks) {
  3193. lbBranchBlocks *b = &p->branch_blocks[i];
  3194. if (b->label == e->Label.node) {
  3195. return *b;
  3196. }
  3197. }
  3198. GB_PANIC("Unreachable");
  3199. lbBranchBlocks empty = {};
  3200. return empty;
  3201. }
  3202. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  3203. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  3204. tl->prev = p->target_list;
  3205. tl->break_ = break_;
  3206. tl->continue_ = continue_;
  3207. tl->fallthrough_ = fallthrough_;
  3208. p->target_list = tl;
  3209. if (label != nullptr) { // Set label blocks
  3210. GB_ASSERT(label->kind == Ast_Label);
  3211. for_array(i, p->branch_blocks) {
  3212. lbBranchBlocks *b = &p->branch_blocks[i];
  3213. GB_ASSERT(b->label != nullptr && label != nullptr);
  3214. GB_ASSERT(b->label->kind == Ast_Label);
  3215. if (b->label == label) {
  3216. b->break_ = break_;
  3217. b->continue_ = continue_;
  3218. return tl;
  3219. }
  3220. }
  3221. GB_PANIC("Unreachable");
  3222. }
  3223. return tl;
  3224. }
  3225. void lb_pop_target_list(lbProcedure *p) {
  3226. p->target_list = p->target_list->prev;
  3227. }
  3228. void lb_open_scope(lbProcedure *p, Scope *s) {
  3229. lbModule *m = p->module;
  3230. if (m->debug_builder) {
  3231. LLVMMetadataRef curr_metadata = lb_get_llvm_metadata(m, s);
  3232. if (s != nullptr && s->node != nullptr && curr_metadata == nullptr) {
  3233. Token token = ast_token(s->node);
  3234. unsigned line = cast(unsigned)token.pos.line;
  3235. unsigned column = cast(unsigned)token.pos.column;
  3236. LLVMMetadataRef file = nullptr;
  3237. if (s->node->file != nullptr) {
  3238. file = lb_get_llvm_metadata(m, s->node->file);
  3239. }
  3240. LLVMMetadataRef scope = nullptr;
  3241. if (p->scope_stack.count > 0) {
  3242. scope = lb_get_llvm_metadata(m, p->scope_stack[p->scope_stack.count-1]);
  3243. }
  3244. if (scope == nullptr) {
  3245. scope = lb_get_llvm_metadata(m, p);
  3246. }
  3247. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  3248. if (m->debug_builder) {
  3249. LLVMMetadataRef res = LLVMDIBuilderCreateLexicalBlock(m->debug_builder, scope,
  3250. file, line, column
  3251. );
  3252. lb_set_llvm_metadata(m, s, res);
  3253. }
  3254. }
  3255. }
  3256. p->scope_index += 1;
  3257. array_add(&p->scope_stack, s);
  3258. }
  3259. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  3260. lb_emit_defer_stmts(p, kind, block);
  3261. GB_ASSERT(p->scope_index > 0);
  3262. // NOTE(bill): Remove `context`s made in that scope
  3263. while (p->context_stack.count > 0) {
  3264. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  3265. if (ctx->scope_index >= p->scope_index) {
  3266. array_pop(&p->context_stack);
  3267. } else {
  3268. break;
  3269. }
  3270. }
  3271. p->scope_index -= 1;
  3272. array_pop(&p->scope_stack);
  3273. }
  3274. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  3275. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  3276. GB_ASSERT(is_type_boolean(tv.type));
  3277. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  3278. if (tv.value.value_bool) {
  3279. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  3280. } else if (ws->else_stmt) {
  3281. switch (ws->else_stmt->kind) {
  3282. case Ast_BlockStmt:
  3283. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  3284. break;
  3285. case Ast_WhenStmt:
  3286. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  3287. break;
  3288. default:
  3289. GB_PANIC("Invalid 'else' statement in 'when' statement");
  3290. break;
  3291. }
  3292. }
  3293. }
  3294. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  3295. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3296. lbModule *m = p->module;
  3297. lbValue count = {};
  3298. Type *expr_type = base_type(type_deref(expr.type));
  3299. switch (expr_type->kind) {
  3300. case Type_Array:
  3301. count = lb_const_int(m, t_int, expr_type->Array.count);
  3302. break;
  3303. }
  3304. lbValue val = {};
  3305. lbValue idx = {};
  3306. lbBlock *loop = nullptr;
  3307. lbBlock *done = nullptr;
  3308. lbBlock *body = nullptr;
  3309. lbAddr index = lb_add_local_generated(p, t_int, false);
  3310. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  3311. loop = lb_create_block(p, "for.index.loop");
  3312. lb_emit_jump(p, loop);
  3313. lb_start_block(p, loop);
  3314. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  3315. lb_addr_store(p, index, incr);
  3316. body = lb_create_block(p, "for.index.body");
  3317. done = lb_create_block(p, "for.index.done");
  3318. if (count.value == nullptr) {
  3319. GB_ASSERT(count_ptr.value != nullptr);
  3320. count = lb_emit_load(p, count_ptr);
  3321. }
  3322. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3323. lb_emit_if(p, cond, body, done);
  3324. lb_start_block(p, body);
  3325. idx = lb_addr_load(p, index);
  3326. switch (expr_type->kind) {
  3327. case Type_Array: {
  3328. if (val_type != nullptr) {
  3329. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3330. }
  3331. break;
  3332. }
  3333. case Type_EnumeratedArray: {
  3334. if (val_type != nullptr) {
  3335. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3336. // NOTE(bill): Override the idx value for the enumeration
  3337. Type *index_type = expr_type->EnumeratedArray.index;
  3338. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  3339. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  3340. }
  3341. }
  3342. break;
  3343. }
  3344. case Type_Slice: {
  3345. if (val_type != nullptr) {
  3346. lbValue elem = lb_slice_elem(p, expr);
  3347. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3348. }
  3349. break;
  3350. }
  3351. case Type_DynamicArray: {
  3352. if (val_type != nullptr) {
  3353. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  3354. elem = lb_emit_load(p, elem);
  3355. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3356. }
  3357. break;
  3358. }
  3359. case Type_Map: {
  3360. lbValue entries = lb_map_entries_ptr(p, expr);
  3361. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  3362. elem = lb_emit_load(p, elem);
  3363. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  3364. idx = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  3365. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 3));
  3366. break;
  3367. }
  3368. case Type_Struct: {
  3369. GB_ASSERT(is_type_soa_struct(expr_type));
  3370. break;
  3371. }
  3372. default:
  3373. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  3374. break;
  3375. }
  3376. if (val_) *val_ = val;
  3377. if (idx_) *idx_ = idx;
  3378. if (loop_) *loop_ = loop;
  3379. if (done_) *done_ = done;
  3380. }
  3381. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  3382. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3383. lbModule *m = p->module;
  3384. lbValue count = lb_const_int(m, t_int, 0);
  3385. Type *expr_type = base_type(expr.type);
  3386. switch (expr_type->kind) {
  3387. case Type_Basic:
  3388. count = lb_string_len(p, expr);
  3389. break;
  3390. default:
  3391. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  3392. break;
  3393. }
  3394. lbValue val = {};
  3395. lbValue idx = {};
  3396. lbBlock *loop = nullptr;
  3397. lbBlock *done = nullptr;
  3398. lbBlock *body = nullptr;
  3399. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3400. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3401. loop = lb_create_block(p, "for.string.loop");
  3402. lb_emit_jump(p, loop);
  3403. lb_start_block(p, loop);
  3404. body = lb_create_block(p, "for.string.body");
  3405. done = lb_create_block(p, "for.string.done");
  3406. lbValue offset = lb_addr_load(p, offset_);
  3407. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  3408. lb_emit_if(p, cond, body, done);
  3409. lb_start_block(p, body);
  3410. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  3411. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  3412. auto args = array_make<lbValue>(permanent_allocator(), 1);
  3413. args[0] = lb_emit_string(p, str_elem, str_len);
  3414. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  3415. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  3416. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  3417. idx = offset;
  3418. if (val_type != nullptr) {
  3419. val = lb_emit_struct_ev(p, rune_and_len, 0);
  3420. }
  3421. if (val_) *val_ = val;
  3422. if (idx_) *idx_ = idx;
  3423. if (loop_) *loop_ = loop;
  3424. if (done_) *done_ = done;
  3425. }
  3426. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node,
  3427. AstRangeStmt *rs, Scope *scope) {
  3428. bool ADD_EXTRA_WRAPPING_CHECK = true;
  3429. lbModule *m = p->module;
  3430. lb_open_scope(p, scope);
  3431. Type *val0_type = nullptr;
  3432. Type *val1_type = nullptr;
  3433. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3434. val0_type = type_of_expr(rs->vals[0]);
  3435. }
  3436. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3437. val1_type = type_of_expr(rs->vals[1]);
  3438. }
  3439. if (val0_type != nullptr) {
  3440. Entity *e = entity_of_node(rs->vals[0]);
  3441. lb_add_local(p, e->type, e, true);
  3442. }
  3443. if (val1_type != nullptr) {
  3444. Entity *e = entity_of_node(rs->vals[1]);
  3445. lb_add_local(p, e->type, e, true);
  3446. }
  3447. TokenKind op = Token_Lt;
  3448. switch (node->op.kind) {
  3449. case Token_Ellipsis: op = Token_LtEq; break;
  3450. case Token_RangeFull: op = Token_LtEq; break;
  3451. case Token_RangeHalf: op = Token_Lt; break;
  3452. default: GB_PANIC("Invalid interval operator"); break;
  3453. }
  3454. lbValue lower = lb_build_expr(p, node->left);
  3455. lbValue upper = {}; // initialized each time in the loop
  3456. lbAddr value = lb_add_local_generated(p, val0_type ? val0_type : lower.type, false);
  3457. lb_addr_store(p, value, lower);
  3458. lbAddr index = lb_add_local_generated(p, t_int, false);
  3459. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  3460. lbBlock *loop = lb_create_block(p, "for.interval.loop");
  3461. lbBlock *body = lb_create_block(p, "for.interval.body");
  3462. lbBlock *done = lb_create_block(p, "for.interval.done");
  3463. lb_emit_jump(p, loop);
  3464. lb_start_block(p, loop);
  3465. upper = lb_build_expr(p, node->right);
  3466. lbValue curr_value = lb_addr_load(p, value);
  3467. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  3468. lb_emit_if(p, cond, body, done);
  3469. lb_start_block(p, body);
  3470. lbValue val = lb_addr_load(p, value);
  3471. lbValue idx = lb_addr_load(p, index);
  3472. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], val);
  3473. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], idx);
  3474. {
  3475. // NOTE: this check block will most likely be optimized out, and is here
  3476. // to make this code easier to read
  3477. lbBlock *check = nullptr;
  3478. lbBlock *post = lb_create_block(p, "for.interval.post");
  3479. lbBlock *continue_block = post;
  3480. if (ADD_EXTRA_WRAPPING_CHECK &&
  3481. op == Token_LtEq) {
  3482. check = lb_create_block(p, "for.interval.check");
  3483. continue_block = check;
  3484. }
  3485. lb_push_target_list(p, rs->label, done, continue_block, nullptr);
  3486. lb_build_stmt(p, rs->body);
  3487. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3488. lb_pop_target_list(p);
  3489. if (check != nullptr) {
  3490. lb_emit_jump(p, check);
  3491. lb_start_block(p, check);
  3492. lbValue check_cond = lb_emit_comp(p, Token_NotEq, curr_value, upper);
  3493. lb_emit_if(p, check_cond, post, done);
  3494. } else {
  3495. lb_emit_jump(p, post);
  3496. }
  3497. lb_start_block(p, post);
  3498. lb_emit_increment(p, value.addr);
  3499. lb_emit_increment(p, index.addr);
  3500. lb_emit_jump(p, loop);
  3501. }
  3502. lb_start_block(p, done);
  3503. }
  3504. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3505. lbModule *m = p->module;
  3506. Type *t = enum_type;
  3507. GB_ASSERT(is_type_enum(t));
  3508. Type *enum_ptr = alloc_type_pointer(t);
  3509. t = base_type(t);
  3510. Type *core_elem = core_type(t);
  3511. GB_ASSERT(t->kind == Type_Enum);
  3512. i64 enum_count = t->Enum.fields.count;
  3513. lbValue max_count = lb_const_int(m, t_int, enum_count);
  3514. lbValue ti = lb_type_info(m, t);
  3515. lbValue variant = lb_emit_struct_ep(p, ti, 4);
  3516. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  3517. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  3518. lbValue values_data = lb_slice_elem(p, values);
  3519. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3520. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3521. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  3522. lb_emit_jump(p, loop);
  3523. lb_start_block(p, loop);
  3524. lbBlock *body = lb_create_block(p, "for.enum.body");
  3525. lbBlock *done = lb_create_block(p, "for.enum.done");
  3526. lbValue offset = lb_addr_load(p, offset_);
  3527. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  3528. lb_emit_if(p, cond, body, done);
  3529. lb_start_block(p, body);
  3530. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  3531. lb_emit_increment(p, offset_.addr);
  3532. lbValue val = {};
  3533. if (val_type != nullptr) {
  3534. GB_ASSERT(are_types_identical(enum_type, val_type));
  3535. if (is_type_integer(core_elem)) {
  3536. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  3537. val = lb_emit_conv(p, i, t);
  3538. } else {
  3539. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  3540. }
  3541. }
  3542. if (val_) *val_ = val;
  3543. if (idx_) *idx_ = offset;
  3544. if (loop_) *loop_ = loop;
  3545. if (done_) *done_ = done;
  3546. }
  3547. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  3548. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  3549. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  3550. lb_emit_jump(p, loop);
  3551. lb_start_block(p, loop);
  3552. lbBlock *body = lb_create_block(p, "for.tuple.body");
  3553. lbBlock *done = lb_create_block(p, "for.tuple.done");
  3554. lbValue tuple_value = lb_build_expr(p, expr);
  3555. Type *tuple = tuple_value.type;
  3556. GB_ASSERT(tuple->kind == Type_Tuple);
  3557. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  3558. i32 cond_index = tuple_count-1;
  3559. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  3560. lb_emit_if(p, cond, body, done);
  3561. lb_start_block(p, body);
  3562. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  3563. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  3564. if (loop_) *loop_ = loop;
  3565. if (done_) *done_ = done;
  3566. }
  3567. void lb_build_range_stmt_struct_soa(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3568. Ast *expr = unparen_expr(rs->expr);
  3569. TypeAndValue tav = type_and_value_of_expr(expr);
  3570. lbBlock *loop = nullptr;
  3571. lbBlock *body = nullptr;
  3572. lbBlock *done = nullptr;
  3573. lb_open_scope(p, scope);
  3574. Type *val_types[2] = {};
  3575. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3576. val_types[0] = type_of_expr(rs->vals[0]);
  3577. }
  3578. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3579. val_types[1] = type_of_expr(rs->vals[1]);
  3580. }
  3581. lbAddr array = lb_build_addr(p, expr);
  3582. if (is_type_pointer(type_deref(lb_addr_type(array)))) {
  3583. array = lb_addr(lb_addr_load(p, array));
  3584. }
  3585. lbValue count = lb_soa_struct_len(p, lb_addr_load(p, array));
  3586. lbAddr index = lb_add_local_generated(p, t_int, false);
  3587. lb_addr_store(p, index, lb_const_int(p->module, t_int, cast(u64)-1));
  3588. loop = lb_create_block(p, "for.soa.loop");
  3589. lb_emit_jump(p, loop);
  3590. lb_start_block(p, loop);
  3591. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(p->module, t_int, 1), t_int);
  3592. lb_addr_store(p, index, incr);
  3593. body = lb_create_block(p, "for.soa.body");
  3594. done = lb_create_block(p, "for.soa.done");
  3595. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3596. lb_emit_if(p, cond, body, done);
  3597. lb_start_block(p, body);
  3598. if (val_types[0]) {
  3599. Entity *e = entity_of_node(rs->vals[0]);
  3600. if (e != nullptr) {
  3601. lbAddr soa_val = lb_addr_soa_variable(array.addr, lb_addr_load(p, index), nullptr);
  3602. map_set(&p->module->soa_values, hash_entity(e), soa_val);
  3603. }
  3604. }
  3605. if (val_types[1]) {
  3606. lb_store_range_stmt_val(p, rs->vals[1], lb_addr_load(p, index));
  3607. }
  3608. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3609. lb_build_stmt(p, rs->body);
  3610. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3611. lb_pop_target_list(p);
  3612. lb_emit_jump(p, loop);
  3613. lb_start_block(p, done);
  3614. }
  3615. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3616. Ast *expr = unparen_expr(rs->expr);
  3617. if (is_ast_range(expr)) {
  3618. lb_build_range_interval(p, &expr->BinaryExpr, rs, scope);
  3619. return;
  3620. }
  3621. Type *expr_type = type_of_expr(expr);
  3622. if (expr_type != nullptr) {
  3623. Type *et = base_type(type_deref(expr_type));
  3624. if (is_type_soa_struct(et)) {
  3625. lb_build_range_stmt_struct_soa(p, rs, scope);
  3626. return;
  3627. }
  3628. }
  3629. lb_open_scope(p, scope);
  3630. Type *val0_type = nullptr;
  3631. Type *val1_type = nullptr;
  3632. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3633. val0_type = type_of_expr(rs->vals[0]);
  3634. }
  3635. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3636. val1_type = type_of_expr(rs->vals[1]);
  3637. }
  3638. if (val0_type != nullptr) {
  3639. Entity *e = entity_of_node(rs->vals[0]);
  3640. lb_add_local(p, e->type, e, true);
  3641. }
  3642. if (val1_type != nullptr) {
  3643. Entity *e = entity_of_node(rs->vals[1]);
  3644. lb_add_local(p, e->type, e, true);
  3645. }
  3646. lbValue val = {};
  3647. lbValue key = {};
  3648. lbBlock *loop = nullptr;
  3649. lbBlock *done = nullptr;
  3650. bool is_map = false;
  3651. TypeAndValue tav = type_and_value_of_expr(expr);
  3652. if (tav.mode == Addressing_Type) {
  3653. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  3654. } else {
  3655. Type *expr_type = type_of_expr(expr);
  3656. Type *et = base_type(type_deref(expr_type));
  3657. switch (et->kind) {
  3658. case Type_Map: {
  3659. is_map = true;
  3660. lbValue map = lb_build_addr_ptr(p, expr);
  3661. if (is_type_pointer(type_deref(map.type))) {
  3662. map = lb_emit_load(p, map);
  3663. }
  3664. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  3665. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  3666. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  3667. break;
  3668. }
  3669. case Type_Array: {
  3670. lbValue array = lb_build_addr_ptr(p, expr);
  3671. if (is_type_pointer(type_deref(array.type))) {
  3672. array = lb_emit_load(p, array);
  3673. }
  3674. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3675. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  3676. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3677. break;
  3678. }
  3679. case Type_EnumeratedArray: {
  3680. lbValue array = lb_build_addr_ptr(p, expr);
  3681. if (is_type_pointer(type_deref(array.type))) {
  3682. array = lb_emit_load(p, array);
  3683. }
  3684. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3685. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  3686. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3687. break;
  3688. }
  3689. case Type_DynamicArray: {
  3690. lbValue count_ptr = {};
  3691. lbValue array = lb_build_addr_ptr(p, expr);
  3692. if (is_type_pointer(type_deref(array.type))) {
  3693. array = lb_emit_load(p, array);
  3694. }
  3695. count_ptr = lb_emit_struct_ep(p, array, 1);
  3696. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  3697. break;
  3698. }
  3699. case Type_Slice: {
  3700. lbValue count_ptr = {};
  3701. lbValue slice = lb_build_expr(p, expr);
  3702. if (is_type_pointer(slice.type)) {
  3703. count_ptr = lb_emit_struct_ep(p, slice, 1);
  3704. slice = lb_emit_load(p, slice);
  3705. } else {
  3706. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  3707. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  3708. }
  3709. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  3710. break;
  3711. }
  3712. case Type_Basic: {
  3713. lbValue string = lb_build_expr(p, expr);
  3714. if (is_type_pointer(string.type)) {
  3715. string = lb_emit_load(p, string);
  3716. }
  3717. if (is_type_untyped(expr_type)) {
  3718. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  3719. lb_addr_store(p, s, string);
  3720. string = lb_addr_load(p, s);
  3721. }
  3722. Type *t = base_type(string.type);
  3723. GB_ASSERT(!is_type_cstring(t));
  3724. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  3725. break;
  3726. }
  3727. case Type_Tuple:
  3728. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  3729. break;
  3730. default:
  3731. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  3732. break;
  3733. }
  3734. }
  3735. if (is_map) {
  3736. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], key);
  3737. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], val);
  3738. } else {
  3739. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], val);
  3740. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], key);
  3741. }
  3742. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3743. lb_build_stmt(p, rs->body);
  3744. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3745. lb_pop_target_list(p);
  3746. lb_emit_jump(p, loop);
  3747. lb_start_block(p, done);
  3748. }
  3749. void lb_build_unroll_range_stmt(lbProcedure *p, AstUnrollRangeStmt *rs, Scope *scope) {
  3750. lbModule *m = p->module;
  3751. lb_open_scope(p, scope); // Open scope here
  3752. Type *val0_type = nullptr;
  3753. Type *val1_type = nullptr;
  3754. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  3755. val0_type = type_of_expr(rs->val0);
  3756. }
  3757. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  3758. val1_type = type_of_expr(rs->val1);
  3759. }
  3760. if (val0_type != nullptr) {
  3761. Entity *e = entity_of_node(rs->val0);
  3762. lb_add_local(p, e->type, e, true);
  3763. }
  3764. if (val1_type != nullptr) {
  3765. Entity *e = entity_of_node(rs->val1);
  3766. lb_add_local(p, e->type, e, true);
  3767. }
  3768. lbValue val = {};
  3769. lbValue key = {};
  3770. lbBlock *loop = nullptr;
  3771. lbBlock *done = nullptr;
  3772. Ast *expr = unparen_expr(rs->expr);
  3773. TypeAndValue tav = type_and_value_of_expr(expr);
  3774. if (is_ast_range(expr)) {
  3775. lbAddr val0_addr = {};
  3776. lbAddr val1_addr = {};
  3777. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3778. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3779. TokenKind op = expr->BinaryExpr.op.kind;
  3780. Ast *start_expr = expr->BinaryExpr.left;
  3781. Ast *end_expr = expr->BinaryExpr.right;
  3782. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  3783. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  3784. ExactValue start = start_expr->tav.value;
  3785. ExactValue end = end_expr->tav.value;
  3786. if (op != Token_RangeHalf) { // .. [start, end] (or ..=)
  3787. ExactValue index = exact_value_i64(0);
  3788. for (ExactValue val = start;
  3789. compare_exact_values(Token_LtEq, val, end);
  3790. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3791. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3792. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3793. lb_build_stmt(p, rs->body);
  3794. }
  3795. } else { // ..< [start, end)
  3796. ExactValue index = exact_value_i64(0);
  3797. for (ExactValue val = start;
  3798. compare_exact_values(Token_Lt, val, end);
  3799. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3800. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3801. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3802. lb_build_stmt(p, rs->body);
  3803. }
  3804. }
  3805. } else if (tav.mode == Addressing_Type) {
  3806. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  3807. Type *et = type_deref(tav.type);
  3808. Type *bet = base_type(et);
  3809. lbAddr val0_addr = {};
  3810. lbAddr val1_addr = {};
  3811. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3812. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3813. for_array(i, bet->Enum.fields) {
  3814. Entity *field = bet->Enum.fields[i];
  3815. GB_ASSERT(field->kind == Entity_Constant);
  3816. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  3817. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3818. lb_build_stmt(p, rs->body);
  3819. }
  3820. } else {
  3821. lbAddr val0_addr = {};
  3822. lbAddr val1_addr = {};
  3823. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3824. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3825. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  3826. Type *t = base_type(expr->tav.type);
  3827. switch (t->kind) {
  3828. case Type_Basic:
  3829. GB_ASSERT(is_type_string(t));
  3830. {
  3831. ExactValue value = expr->tav.value;
  3832. GB_ASSERT(value.kind == ExactValue_String);
  3833. String str = value.value_string;
  3834. Rune codepoint = 0;
  3835. isize offset = 0;
  3836. do {
  3837. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  3838. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  3839. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  3840. lb_build_stmt(p, rs->body);
  3841. offset += width;
  3842. } while (offset < str.len);
  3843. }
  3844. break;
  3845. case Type_Array:
  3846. if (t->Array.count > 0) {
  3847. lbValue val = lb_build_expr(p, expr);
  3848. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3849. for (i64 i = 0; i < t->Array.count; i++) {
  3850. if (val0_type) {
  3851. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3852. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3853. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3854. }
  3855. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3856. lb_build_stmt(p, rs->body);
  3857. }
  3858. }
  3859. break;
  3860. case Type_EnumeratedArray:
  3861. if (t->EnumeratedArray.count > 0) {
  3862. lbValue val = lb_build_expr(p, expr);
  3863. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3864. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  3865. if (val0_type) {
  3866. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3867. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3868. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3869. }
  3870. if (val1_type) {
  3871. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  3872. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  3873. }
  3874. lb_build_stmt(p, rs->body);
  3875. }
  3876. }
  3877. break;
  3878. default:
  3879. GB_PANIC("Invalid '#unroll for' type");
  3880. break;
  3881. }
  3882. }
  3883. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3884. }
  3885. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss, Scope *scope) {
  3886. lb_open_scope(p, scope);
  3887. if (ss->init != nullptr) {
  3888. lb_build_stmt(p, ss->init);
  3889. }
  3890. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  3891. if (ss->tag != nullptr) {
  3892. tag = lb_build_expr(p, ss->tag);
  3893. }
  3894. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  3895. ast_node(body, BlockStmt, ss->body);
  3896. Slice<Ast *> default_stmts = {};
  3897. lbBlock *default_fall = nullptr;
  3898. lbBlock *default_block = nullptr;
  3899. lbBlock *fall = nullptr;
  3900. isize case_count = body->stmts.count;
  3901. for_array(i, body->stmts) {
  3902. Ast *clause = body->stmts[i];
  3903. ast_node(cc, CaseClause, clause);
  3904. lbBlock *body = fall;
  3905. if (body == nullptr) {
  3906. body = lb_create_block(p, "switch.case.body");
  3907. }
  3908. fall = done;
  3909. if (i+1 < case_count) {
  3910. fall = lb_create_block(p, "switch.fall.body");
  3911. }
  3912. if (cc->list.count == 0) {
  3913. // default case
  3914. default_stmts = cc->stmts;
  3915. default_fall = fall;
  3916. default_block = body;
  3917. continue;
  3918. }
  3919. lbBlock *next_cond = nullptr;
  3920. for_array(j, cc->list) {
  3921. Ast *expr = unparen_expr(cc->list[j]);
  3922. next_cond = lb_create_block(p, "switch.case.next");
  3923. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  3924. if (is_ast_range(expr)) {
  3925. ast_node(ie, BinaryExpr, expr);
  3926. TokenKind op = Token_Invalid;
  3927. switch (ie->op.kind) {
  3928. case Token_Ellipsis: op = Token_LtEq; break;
  3929. case Token_RangeFull: op = Token_LtEq; break;
  3930. case Token_RangeHalf: op = Token_Lt; break;
  3931. default: GB_PANIC("Invalid interval operator"); break;
  3932. }
  3933. lbValue lhs = lb_build_expr(p, ie->left);
  3934. lbValue rhs = lb_build_expr(p, ie->right);
  3935. // TODO(bill): do short circuit here
  3936. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  3937. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  3938. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  3939. } else {
  3940. if (expr->tav.mode == Addressing_Type) {
  3941. GB_ASSERT(is_type_typeid(tag.type));
  3942. lbValue e = lb_typeid(p->module, expr->tav.type);
  3943. e = lb_emit_conv(p, e, tag.type);
  3944. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  3945. } else {
  3946. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  3947. }
  3948. }
  3949. lb_emit_if(p, cond, body, next_cond);
  3950. lb_start_block(p, next_cond);
  3951. }
  3952. lb_start_block(p, body);
  3953. lb_push_target_list(p, ss->label, done, nullptr, fall);
  3954. lb_open_scope(p, body->scope);
  3955. lb_build_stmt_list(p, cc->stmts);
  3956. lb_close_scope(p, lbDeferExit_Default, body);
  3957. lb_pop_target_list(p);
  3958. lb_emit_jump(p, done);
  3959. lb_start_block(p, next_cond);
  3960. }
  3961. if (default_block != nullptr) {
  3962. lb_emit_jump(p, default_block);
  3963. lb_start_block(p, default_block);
  3964. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  3965. lb_open_scope(p, default_block->scope);
  3966. lb_build_stmt_list(p, default_stmts);
  3967. lb_close_scope(p, lbDeferExit_Default, default_block);
  3968. lb_pop_target_list(p);
  3969. }
  3970. lb_emit_jump(p, done);
  3971. lb_close_scope(p, lbDeferExit_Default, done);
  3972. lb_start_block(p, done);
  3973. }
  3974. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  3975. Entity *e = implicit_entity_of_node(clause);
  3976. GB_ASSERT(e != nullptr);
  3977. if (e->flags & EntityFlag_Value) {
  3978. // by value
  3979. GB_ASSERT(are_types_identical(e->type, value.type));
  3980. lbAddr x = lb_add_local(p, e->type, e, false);
  3981. lb_addr_store(p, x, value);
  3982. } else {
  3983. // by reference
  3984. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  3985. lb_add_entity(p->module, e, value);
  3986. }
  3987. }
  3988. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  3989. Entity *e = entity_of_node(stmt_val);
  3990. if (e == nullptr) {
  3991. return {};
  3992. }
  3993. if ((e->flags & EntityFlag_Value) == 0) {
  3994. if (LLVMIsALoadInst(value.value)) {
  3995. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  3996. lb_add_entity(p->module, e, ptr);
  3997. return lb_addr(ptr);
  3998. }
  3999. }
  4000. // by value
  4001. lbAddr addr = lb_add_local(p, e->type, e, false);
  4002. lb_addr_store(p, addr, value);
  4003. return addr;
  4004. }
  4005. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  4006. ast_node(cc, CaseClause, clause);
  4007. lb_push_target_list(p, label, done, nullptr, nullptr);
  4008. lb_open_scope(p, body->scope);
  4009. lb_build_stmt_list(p, cc->stmts);
  4010. lb_close_scope(p, lbDeferExit_Default, body);
  4011. lb_pop_target_list(p);
  4012. lb_emit_jump(p, done);
  4013. }
  4014. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  4015. lbModule *m = p->module;
  4016. ast_node(as, AssignStmt, ss->tag);
  4017. GB_ASSERT(as->lhs.count == 1);
  4018. GB_ASSERT(as->rhs.count == 1);
  4019. lbValue parent = lb_build_expr(p, as->rhs[0]);
  4020. bool is_parent_ptr = is_type_pointer(parent.type);
  4021. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  4022. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  4023. lbValue parent_value = parent;
  4024. lbValue parent_ptr = parent;
  4025. if (!is_parent_ptr) {
  4026. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  4027. }
  4028. lbValue tag_index = {};
  4029. lbValue union_data = {};
  4030. if (switch_kind == TypeSwitch_Union) {
  4031. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  4032. if (is_type_union_maybe_pointer(type_deref(parent_ptr.type))) {
  4033. tag_index = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, union_data), t_int);
  4034. } else {
  4035. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  4036. tag_index = lb_emit_load(p, tag_ptr);
  4037. }
  4038. }
  4039. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  4040. lb_emit_jump(p, start_block);
  4041. lb_start_block(p, start_block);
  4042. // NOTE(bill): Append this later
  4043. lbBlock *done = lb_create_block(p, "typeswitch.done");
  4044. Ast *default_ = nullptr;
  4045. ast_node(body, BlockStmt, ss->body);
  4046. gb_local_persist i32 weird_count = 0;
  4047. for_array(i, body->stmts) {
  4048. Ast *clause = body->stmts[i];
  4049. ast_node(cc, CaseClause, clause);
  4050. if (cc->list.count == 0) {
  4051. default_ = clause;
  4052. continue;
  4053. }
  4054. lbBlock *body = lb_create_block(p, "typeswitch.body");
  4055. lbBlock *next = nullptr;
  4056. Type *case_type = nullptr;
  4057. for_array(type_index, cc->list) {
  4058. next = lb_create_block(p, "typeswitch.next");
  4059. case_type = type_of_expr(cc->list[type_index]);
  4060. lbValue cond = {};
  4061. if (switch_kind == TypeSwitch_Union) {
  4062. Type *ut = base_type(type_deref(parent.type));
  4063. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  4064. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  4065. } else if (switch_kind == TypeSwitch_Any) {
  4066. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  4067. lbValue case_typeid = lb_typeid(m, case_type);
  4068. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  4069. }
  4070. GB_ASSERT(cond.value != nullptr);
  4071. lb_emit_if(p, cond, body, next);
  4072. lb_start_block(p, next);
  4073. }
  4074. Entity *case_entity = implicit_entity_of_node(clause);
  4075. lbValue value = parent_value;
  4076. lb_start_block(p, body);
  4077. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  4078. if (cc->list.count == 1) {
  4079. lbValue data = {};
  4080. if (switch_kind == TypeSwitch_Union) {
  4081. data = union_data;
  4082. } else if (switch_kind == TypeSwitch_Any) {
  4083. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  4084. data = any_data;
  4085. }
  4086. Type *ct = case_entity->type;
  4087. Type *ct_ptr = alloc_type_pointer(ct);
  4088. value = lb_emit_conv(p, data, ct_ptr);
  4089. if (!by_reference) {
  4090. value = lb_emit_load(p, value);
  4091. }
  4092. }
  4093. lb_store_type_case_implicit(p, clause, value);
  4094. lb_type_case_body(p, ss->label, clause, body, done);
  4095. lb_start_block(p, next);
  4096. }
  4097. if (default_ != nullptr) {
  4098. lb_store_type_case_implicit(p, default_, parent_value);
  4099. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  4100. } else {
  4101. lb_emit_jump(p, done);
  4102. }
  4103. lb_start_block(p, done);
  4104. }
  4105. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  4106. lbModule *m = p->module;
  4107. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  4108. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  4109. type = default_type(type);
  4110. lbValue short_circuit = {};
  4111. if (op == Token_CmpAnd) {
  4112. lb_build_cond(p, left, rhs, done);
  4113. short_circuit = lb_const_bool(m, type, false);
  4114. } else if (op == Token_CmpOr) {
  4115. lb_build_cond(p, left, done, rhs);
  4116. short_circuit = lb_const_bool(m, type, true);
  4117. }
  4118. if (rhs->preds.count == 0) {
  4119. lb_start_block(p, done);
  4120. return short_circuit;
  4121. }
  4122. if (done->preds.count == 0) {
  4123. lb_start_block(p, rhs);
  4124. if (lb_is_expr_untyped_const(right)) {
  4125. return lb_expr_untyped_const_to_typed(m, right, type);
  4126. }
  4127. return lb_build_expr(p, right);
  4128. }
  4129. Array<LLVMValueRef> incoming_values = {};
  4130. Array<LLVMBasicBlockRef> incoming_blocks = {};
  4131. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  4132. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  4133. for_array(i, done->preds) {
  4134. incoming_values[i] = short_circuit.value;
  4135. incoming_blocks[i] = done->preds[i]->block;
  4136. }
  4137. lb_start_block(p, rhs);
  4138. lbValue edge = {};
  4139. if (lb_is_expr_untyped_const(right)) {
  4140. edge = lb_expr_untyped_const_to_typed(m, right, type);
  4141. } else {
  4142. edge = lb_build_expr(p, right);
  4143. }
  4144. incoming_values[done->preds.count] = edge.value;
  4145. incoming_blocks[done->preds.count] = p->curr_block->block;
  4146. lb_emit_jump(p, done);
  4147. lb_start_block(p, done);
  4148. lbValue res = {};
  4149. res.type = type;
  4150. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  4151. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  4152. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  4153. return res;
  4154. }
  4155. lbCopyElisionHint lb_set_copy_elision_hint(lbProcedure *p, lbAddr const &addr, Ast *ast) {
  4156. lbCopyElisionHint prev = p->copy_elision_hint;
  4157. p->copy_elision_hint.used = false;
  4158. p->copy_elision_hint.ptr = {};
  4159. p->copy_elision_hint.ast = nullptr;
  4160. #if 0
  4161. if (addr.kind == lbAddr_Default && addr.addr.value != nullptr) {
  4162. p->copy_elision_hint.ptr = lb_addr_get_ptr(p, addr);
  4163. p->copy_elision_hint.ast = unparen_expr(ast);
  4164. }
  4165. #endif
  4166. return prev;
  4167. }
  4168. void lb_reset_copy_elision_hint(lbProcedure *p, lbCopyElisionHint prev_hint) {
  4169. p->copy_elision_hint = prev_hint;
  4170. }
  4171. lbValue lb_consume_copy_elision_hint(lbProcedure *p) {
  4172. lbValue return_ptr = p->copy_elision_hint.ptr;
  4173. p->copy_elision_hint.used = true;
  4174. p->copy_elision_hint.ptr = {};
  4175. p->copy_elision_hint.ast = nullptr;
  4176. return return_ptr;
  4177. }
  4178. void lb_build_static_variables(lbProcedure *p, AstValueDecl *vd) {
  4179. for_array(i, vd->names) {
  4180. lbValue value = {};
  4181. if (vd->values.count > 0) {
  4182. GB_ASSERT(vd->names.count == vd->values.count);
  4183. Ast *ast_value = vd->values[i];
  4184. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  4185. ast_value->tav.mode == Addressing_Invalid);
  4186. bool allow_local = false;
  4187. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  4188. }
  4189. Ast *ident = vd->names[i];
  4190. GB_ASSERT(!is_blank_ident(ident));
  4191. Entity *e = entity_of_node(ident);
  4192. GB_ASSERT(e->flags & EntityFlag_Static);
  4193. String name = e->token.string;
  4194. String mangled_name = {};
  4195. {
  4196. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  4197. str = gb_string_appendc(str, "-");
  4198. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  4199. mangled_name.text = cast(u8 *)str;
  4200. mangled_name.len = gb_string_length(str);
  4201. }
  4202. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  4203. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  4204. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  4205. if (value.value != nullptr) {
  4206. LLVMSetInitializer(global, value.value);
  4207. } else {
  4208. }
  4209. if (e->Variable.thread_local_model != "") {
  4210. LLVMSetThreadLocal(global, true);
  4211. String m = e->Variable.thread_local_model;
  4212. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  4213. if (m == "default") {
  4214. mode = LLVMGeneralDynamicTLSModel;
  4215. } else if (m == "localdynamic") {
  4216. mode = LLVMLocalDynamicTLSModel;
  4217. } else if (m == "initialexec") {
  4218. mode = LLVMInitialExecTLSModel;
  4219. } else if (m == "localexec") {
  4220. mode = LLVMLocalExecTLSModel;
  4221. } else {
  4222. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  4223. }
  4224. LLVMSetThreadLocalMode(global, mode);
  4225. } else {
  4226. LLVMSetLinkage(global, LLVMInternalLinkage);
  4227. }
  4228. lbValue global_val = {global, alloc_type_pointer(e->type)};
  4229. lb_add_entity(p->module, e, global_val);
  4230. lb_add_member(p->module, mangled_name, global_val);
  4231. }
  4232. }
  4233. void lb_build_assignment(lbProcedure *p, Array<lbAddr> &lvals, Slice<Ast *> const &values) {
  4234. if (values.count == 0) {
  4235. return;
  4236. }
  4237. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  4238. for_array(i, values) {
  4239. Ast *rhs = values[i];
  4240. if (is_type_tuple(type_of_expr(rhs))) {
  4241. lbValue init = lb_build_expr(p, rhs);
  4242. Type *t = init.type;
  4243. GB_ASSERT(t->kind == Type_Tuple);
  4244. for_array(i, t->Tuple.variables) {
  4245. Entity *e = t->Tuple.variables[i];
  4246. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  4247. array_add(&inits, v);
  4248. }
  4249. } else {
  4250. auto prev_hint = lb_set_copy_elision_hint(p, lvals[inits.count], rhs);
  4251. lbValue init = lb_build_expr(p, rhs);
  4252. if (p->copy_elision_hint.used) {
  4253. lvals[inits.count] = {}; // zero lval
  4254. }
  4255. lb_reset_copy_elision_hint(p, prev_hint);
  4256. array_add(&inits, init);
  4257. }
  4258. }
  4259. GB_ASSERT(lvals.count == inits.count);
  4260. for_array(i, inits) {
  4261. lbAddr lval = lvals[i];
  4262. lbValue init = inits[i];
  4263. lb_addr_store(p, lval, init);
  4264. }
  4265. }
  4266. void lb_build_return_stmt(lbProcedure *p, AstReturnStmt *rs) {
  4267. lbValue res = {};
  4268. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  4269. isize return_count = p->type->Proc.result_count;
  4270. isize res_count = rs->results.count;
  4271. lbFunctionType *ft = lb_get_function_type(p->module, p, p->type);
  4272. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  4273. if (return_count == 0) {
  4274. // No return values
  4275. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4276. LLVMBuildRetVoid(p->builder);
  4277. return;
  4278. } else if (return_count == 1) {
  4279. Entity *e = tuple->variables[0];
  4280. if (res_count == 0) {
  4281. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4282. GB_ASSERT(found);
  4283. res = lb_emit_load(p, *found);
  4284. } else {
  4285. res = lb_build_expr(p, rs->results[0]);
  4286. res = lb_emit_conv(p, res, e->type);
  4287. }
  4288. if (p->type->Proc.has_named_results) {
  4289. // NOTE(bill): store the named values before returning
  4290. if (e->token.string != "") {
  4291. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4292. GB_ASSERT(found != nullptr);
  4293. lb_emit_store(p, *found, lb_emit_conv(p, res, e->type));
  4294. }
  4295. }
  4296. } else {
  4297. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  4298. if (res_count != 0) {
  4299. for (isize res_index = 0; res_index < res_count; res_index++) {
  4300. lbValue res = lb_build_expr(p, rs->results[res_index]);
  4301. Type *t = res.type;
  4302. if (t->kind == Type_Tuple) {
  4303. for_array(i, t->Tuple.variables) {
  4304. Entity *e = t->Tuple.variables[i];
  4305. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  4306. array_add(&results, v);
  4307. }
  4308. } else {
  4309. array_add(&results, res);
  4310. }
  4311. }
  4312. } else {
  4313. for (isize res_index = 0; res_index < return_count; res_index++) {
  4314. Entity *e = tuple->variables[res_index];
  4315. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4316. GB_ASSERT(found);
  4317. lbValue res = lb_emit_load(p, *found);
  4318. array_add(&results, res);
  4319. }
  4320. }
  4321. GB_ASSERT(results.count == return_count);
  4322. if (p->type->Proc.has_named_results) {
  4323. // NOTE(bill): store the named values before returning
  4324. for_array(i, p->type->Proc.results->Tuple.variables) {
  4325. Entity *e = p->type->Proc.results->Tuple.variables[i];
  4326. if (e->kind != Entity_Variable) {
  4327. continue;
  4328. }
  4329. if (e->token.string == "") {
  4330. continue;
  4331. }
  4332. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4333. GB_ASSERT(found != nullptr);
  4334. lb_emit_store(p, *found, lb_emit_conv(p, results[i], e->type));
  4335. }
  4336. }
  4337. Type *ret_type = p->type->Proc.results;
  4338. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4339. res = lb_add_local_generated(p, ret_type, false).addr;
  4340. for_array(i, results) {
  4341. Entity *e = tuple->variables[i];
  4342. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  4343. lbValue val = lb_emit_conv(p, results[i], e->type);
  4344. lb_emit_store(p, field, val);
  4345. }
  4346. res = lb_emit_load(p, res);
  4347. }
  4348. lb_ensure_abi_function_type(p->module, p);
  4349. if (return_by_pointer) {
  4350. if (res.value != nullptr) {
  4351. LLVMBuildStore(p->builder, res.value, p->return_ptr.addr.value);
  4352. } else {
  4353. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  4354. }
  4355. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4356. LLVMBuildRetVoid(p->builder);
  4357. } else {
  4358. LLVMValueRef ret_val = res.value;
  4359. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  4360. if (p->abi_function_type->ret.cast_type != nullptr) {
  4361. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  4362. }
  4363. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4364. LLVMBuildRet(p->builder, ret_val);
  4365. }
  4366. }
  4367. void lb_build_if_stmt(lbProcedure *p, Ast *node) {
  4368. ast_node(is, IfStmt, node);
  4369. lb_open_scope(p, node->scope); // Scope #1
  4370. if (is->init != nullptr) {
  4371. // TODO(bill): Should this have a separate block to begin with?
  4372. #if 1
  4373. lbBlock *init = lb_create_block(p, "if.init");
  4374. lb_emit_jump(p, init);
  4375. lb_start_block(p, init);
  4376. #endif
  4377. lb_build_stmt(p, is->init);
  4378. }
  4379. lbBlock *then = lb_create_block(p, "if.then");
  4380. lbBlock *done = lb_create_block(p, "if.done");
  4381. lbBlock *else_ = done;
  4382. if (is->else_stmt != nullptr) {
  4383. else_ = lb_create_block(p, "if.else");
  4384. }
  4385. lb_build_cond(p, is->cond, then, else_);
  4386. lb_start_block(p, then);
  4387. if (is->label != nullptr) {
  4388. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  4389. tl->is_block = true;
  4390. }
  4391. lb_build_stmt(p, is->body);
  4392. lb_emit_jump(p, done);
  4393. if (is->else_stmt != nullptr) {
  4394. lb_start_block(p, else_);
  4395. lb_open_scope(p, is->else_stmt->scope);
  4396. lb_build_stmt(p, is->else_stmt);
  4397. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4398. lb_emit_jump(p, done);
  4399. }
  4400. lb_start_block(p, done);
  4401. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4402. }
  4403. void lb_build_for_stmt(lbProcedure *p, Ast *node) {
  4404. ast_node(fs, ForStmt, node);
  4405. lb_open_scope(p, node->scope); // Open Scope here
  4406. if (fs->init != nullptr) {
  4407. #if 1
  4408. lbBlock *init = lb_create_block(p, "for.init");
  4409. lb_emit_jump(p, init);
  4410. lb_start_block(p, init);
  4411. #endif
  4412. lb_build_stmt(p, fs->init);
  4413. }
  4414. lbBlock *body = lb_create_block(p, "for.body");
  4415. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  4416. lbBlock *loop = body;
  4417. if (fs->cond != nullptr) {
  4418. loop = lb_create_block(p, "for.loop");
  4419. }
  4420. lbBlock *post = loop;
  4421. if (fs->post != nullptr) {
  4422. post = lb_create_block(p, "for.post");
  4423. }
  4424. lb_emit_jump(p, loop);
  4425. lb_start_block(p, loop);
  4426. if (loop != body) {
  4427. lb_build_cond(p, fs->cond, body, done);
  4428. lb_start_block(p, body);
  4429. }
  4430. lb_push_target_list(p, fs->label, done, post, nullptr);
  4431. lb_build_stmt(p, fs->body);
  4432. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4433. lb_pop_target_list(p);
  4434. lb_emit_jump(p, post);
  4435. if (fs->post != nullptr) {
  4436. lb_start_block(p, post);
  4437. lb_build_stmt(p, fs->post);
  4438. lb_emit_jump(p, loop);
  4439. }
  4440. lb_start_block(p, done);
  4441. }
  4442. void lb_build_stmt(lbProcedure *p, Ast *node) {
  4443. Ast *prev_stmt = p->curr_stmt;
  4444. defer (p->curr_stmt = prev_stmt);
  4445. p->curr_stmt = node;
  4446. if (p->curr_block != nullptr) {
  4447. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  4448. if (lb_is_instr_terminating(last_instr)) {
  4449. return;
  4450. }
  4451. }
  4452. LLVMMetadataRef prev_debug_location = nullptr;
  4453. if (p->debug_info != nullptr) {
  4454. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  4455. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, node));
  4456. }
  4457. defer (if (prev_debug_location != nullptr) {
  4458. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  4459. });
  4460. u16 prev_state_flags = p->state_flags;
  4461. defer (p->state_flags = prev_state_flags);
  4462. if (node->state_flags != 0) {
  4463. u16 in = node->state_flags;
  4464. u16 out = p->state_flags;
  4465. if (in & StateFlag_bounds_check) {
  4466. out |= StateFlag_bounds_check;
  4467. out &= ~StateFlag_no_bounds_check;
  4468. } else if (in & StateFlag_no_bounds_check) {
  4469. out |= StateFlag_no_bounds_check;
  4470. out &= ~StateFlag_bounds_check;
  4471. }
  4472. p->state_flags = out;
  4473. }
  4474. switch (node->kind) {
  4475. case_ast_node(bs, EmptyStmt, node);
  4476. case_end;
  4477. case_ast_node(us, UsingStmt, node);
  4478. case_end;
  4479. case_ast_node(ws, WhenStmt, node);
  4480. lb_build_when_stmt(p, ws);
  4481. case_end;
  4482. case_ast_node(bs, BlockStmt, node);
  4483. lbBlock *done = nullptr;
  4484. if (bs->label != nullptr) {
  4485. done = lb_create_block(p, "block.done");
  4486. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  4487. tl->is_block = true;
  4488. }
  4489. lb_open_scope(p, node->scope);
  4490. lb_build_stmt_list(p, bs->stmts);
  4491. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4492. if (done != nullptr) {
  4493. lb_emit_jump(p, done);
  4494. lb_start_block(p, done);
  4495. }
  4496. case_end;
  4497. case_ast_node(vd, ValueDecl, node);
  4498. if (!vd->is_mutable) {
  4499. return;
  4500. }
  4501. bool is_static = false;
  4502. if (vd->names.count > 0) {
  4503. Entity *e = entity_of_node(vd->names[0]);
  4504. if (e->flags & EntityFlag_Static) {
  4505. // NOTE(bill): If one of the entities is static, they all are
  4506. is_static = true;
  4507. }
  4508. }
  4509. if (is_static) {
  4510. lb_build_static_variables(p, vd);
  4511. return;
  4512. }
  4513. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, vd->names.count);
  4514. for_array(i, vd->names) {
  4515. Ast *name = vd->names[i];
  4516. lbAddr lval = {};
  4517. if (!is_blank_ident(name)) {
  4518. Entity *e = entity_of_node(name);
  4519. bool zero_init = true; // Always do it
  4520. lval = lb_add_local(p, e->type, e, zero_init);
  4521. }
  4522. array_add(&lvals, lval);
  4523. }
  4524. lb_build_assignment(p, lvals, vd->values);
  4525. case_end;
  4526. case_ast_node(as, AssignStmt, node);
  4527. if (as->op.kind == Token_Eq) {
  4528. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  4529. for_array(i, as->lhs) {
  4530. Ast *lhs = as->lhs[i];
  4531. lbAddr lval = {};
  4532. if (!is_blank_ident(lhs)) {
  4533. lval = lb_build_addr(p, lhs);
  4534. }
  4535. array_add(&lvals, lval);
  4536. }
  4537. lb_build_assignment(p, lvals, as->rhs);
  4538. } else {
  4539. GB_ASSERT(as->lhs.count == 1);
  4540. GB_ASSERT(as->rhs.count == 1);
  4541. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  4542. // +=, -=, etc
  4543. i32 op = cast(i32)as->op.kind;
  4544. op += Token_Add - Token_AddEq; // Convert += to +
  4545. if (op == Token_CmpAnd || op == Token_CmpOr) {
  4546. Type *type = as->lhs[0]->tav.type;
  4547. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  4548. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4549. lb_addr_store(p, lhs, new_value);
  4550. } else {
  4551. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4552. lbValue value = lb_build_expr(p, as->rhs[0]);
  4553. lbValue old_value = lb_addr_load(p, lhs);
  4554. Type *type = old_value.type;
  4555. lbValue change = lb_emit_conv(p, value, type);
  4556. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  4557. lb_addr_store(p, lhs, new_value);
  4558. }
  4559. return;
  4560. }
  4561. case_end;
  4562. case_ast_node(es, ExprStmt, node);
  4563. lb_build_expr(p, es->expr);
  4564. case_end;
  4565. case_ast_node(ds, DeferStmt, node);
  4566. lb_add_defer_node(p, p->scope_index, ds->stmt);
  4567. case_end;
  4568. case_ast_node(rs, ReturnStmt, node);
  4569. lb_build_return_stmt(p, rs);
  4570. case_end;
  4571. case_ast_node(is, IfStmt, node);
  4572. lb_build_if_stmt(p, node);
  4573. case_end;
  4574. case_ast_node(fs, ForStmt, node);
  4575. lb_build_for_stmt(p, node);
  4576. case_end;
  4577. case_ast_node(rs, RangeStmt, node);
  4578. lb_build_range_stmt(p, rs, node->scope);
  4579. case_end;
  4580. case_ast_node(rs, UnrollRangeStmt, node);
  4581. lb_build_unroll_range_stmt(p, rs, node->scope);
  4582. case_end;
  4583. case_ast_node(ss, SwitchStmt, node);
  4584. lb_build_switch_stmt(p, ss, node->scope);
  4585. case_end;
  4586. case_ast_node(ss, TypeSwitchStmt, node);
  4587. lb_build_type_switch_stmt(p, ss);
  4588. case_end;
  4589. case_ast_node(bs, BranchStmt, node);
  4590. lbBlock *block = nullptr;
  4591. if (bs->label != nullptr) {
  4592. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  4593. switch (bs->token.kind) {
  4594. case Token_break: block = bb.break_; break;
  4595. case Token_continue: block = bb.continue_; break;
  4596. case Token_fallthrough:
  4597. GB_PANIC("fallthrough cannot have a label");
  4598. break;
  4599. }
  4600. } else {
  4601. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  4602. if (t->is_block) {
  4603. continue;
  4604. }
  4605. switch (bs->token.kind) {
  4606. case Token_break: block = t->break_; break;
  4607. case Token_continue: block = t->continue_; break;
  4608. case Token_fallthrough: block = t->fallthrough_; break;
  4609. }
  4610. }
  4611. }
  4612. if (block != nullptr) {
  4613. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  4614. }
  4615. lb_emit_jump(p, block);
  4616. case_end;
  4617. }
  4618. }
  4619. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  4620. cond = lb_emit_conv(p, cond, t_llvm_bool);
  4621. lbValue res = {};
  4622. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  4623. res.type = x.type;
  4624. return res;
  4625. }
  4626. lbValue lb_const_nil(lbModule *m, Type *type) {
  4627. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  4628. return lbValue{v, type};
  4629. }
  4630. lbValue lb_const_undef(lbModule *m, Type *type) {
  4631. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  4632. return lbValue{v, type};
  4633. }
  4634. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  4635. lbValue res = {};
  4636. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  4637. res.type = type;
  4638. return res;
  4639. }
  4640. lbValue lb_const_string(lbModule *m, String const &value) {
  4641. return lb_const_value(m, t_string, exact_value_string(value));
  4642. }
  4643. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  4644. lbValue res = {};
  4645. res.value = LLVMConstInt(lb_type(m, type), value, false);
  4646. res.type = type;
  4647. return res;
  4648. }
  4649. LLVMValueRef lb_const_f16(lbModule *m, f32 f, Type *type=t_f16) {
  4650. GB_ASSERT(type_size_of(type) == 2);
  4651. u16 u = f32_to_f16(f);
  4652. if (is_type_different_to_arch_endianness(type)) {
  4653. u = gb_endian_swap16(u);
  4654. }
  4655. LLVMValueRef i = LLVMConstInt(LLVMInt16TypeInContext(m->ctx), u, false);
  4656. return LLVMConstBitCast(i, lb_type(m, type));
  4657. }
  4658. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  4659. GB_ASSERT(type_size_of(type) == 4);
  4660. u32 u = bit_cast<u32>(f);
  4661. if (is_type_different_to_arch_endianness(type)) {
  4662. u = gb_endian_swap32(u);
  4663. }
  4664. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  4665. return LLVMConstBitCast(i, lb_type(m, type));
  4666. }
  4667. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4668. x = lb_emit_conv(p, x, t);
  4669. y = lb_emit_conv(p, y, t);
  4670. if (is_type_float(t)) {
  4671. i64 sz = 8*type_size_of(t);
  4672. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4673. args[0] = x;
  4674. args[1] = y;
  4675. switch (sz) {
  4676. case 16: return lb_emit_runtime_call(p, "min_f16", args);
  4677. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  4678. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  4679. }
  4680. GB_PANIC("Unknown float type");
  4681. }
  4682. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  4683. }
  4684. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4685. x = lb_emit_conv(p, x, t);
  4686. y = lb_emit_conv(p, y, t);
  4687. if (is_type_float(t)) {
  4688. i64 sz = 8*type_size_of(t);
  4689. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4690. args[0] = x;
  4691. args[1] = y;
  4692. switch (sz) {
  4693. case 16: return lb_emit_runtime_call(p, "max_f16", args);
  4694. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  4695. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  4696. }
  4697. GB_PANIC("Unknown float type");
  4698. }
  4699. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  4700. }
  4701. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  4702. lbValue z = {};
  4703. z = lb_emit_max(p, t, x, min);
  4704. z = lb_emit_min(p, t, z, max);
  4705. return z;
  4706. }
  4707. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  4708. StringHashKey key = string_hash_string(str);
  4709. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  4710. if (found != nullptr) {
  4711. return *found;
  4712. } else {
  4713. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4714. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4715. cast(char const *)str.text,
  4716. cast(unsigned)str.len,
  4717. false);
  4718. isize max_len = 7+8+1;
  4719. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  4720. u32 id = cast(u32)gb_atomic32_fetch_add(&m->gen->global_array_index, 1);
  4721. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  4722. len -= 1;
  4723. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4724. LLVMSetInitializer(global_data, data);
  4725. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4726. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4727. string_map_set(&m->const_strings, key, ptr);
  4728. return ptr;
  4729. }
  4730. }
  4731. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  4732. LLVMValueRef ptr = nullptr;
  4733. if (str.len != 0) {
  4734. ptr = lb_find_or_add_entity_string_ptr(m, str);
  4735. } else {
  4736. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4737. }
  4738. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4739. LLVMValueRef values[2] = {ptr, str_len};
  4740. lbValue res = {};
  4741. res.value = llvm_const_named_struct(lb_type(m, t_string), values, 2);
  4742. res.type = t_string;
  4743. return res;
  4744. }
  4745. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  4746. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4747. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4748. cast(char const *)str.text,
  4749. cast(unsigned)str.len,
  4750. false);
  4751. char *name = nullptr;
  4752. {
  4753. isize max_len = 7+8+1;
  4754. name = gb_alloc_array(permanent_allocator(), char, max_len);
  4755. u32 id = cast(u32)gb_atomic32_fetch_add(&m->gen->global_array_index, 1);
  4756. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  4757. len -= 1;
  4758. }
  4759. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4760. LLVMSetInitializer(global_data, data);
  4761. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4762. LLVMValueRef ptr = nullptr;
  4763. if (str.len != 0) {
  4764. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4765. } else {
  4766. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4767. }
  4768. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4769. LLVMValueRef values[2] = {ptr, len};
  4770. lbValue res = {};
  4771. res.value = llvm_const_named_struct(lb_type(m, t_u8_slice), values, 2);
  4772. res.type = t_u8_slice;
  4773. return res;
  4774. }
  4775. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  4776. isize index = type_info_index(info, type, false);
  4777. if (index >= 0) {
  4778. auto *set = &info->minimum_dependency_type_info_set;
  4779. for_array(i, set->entries) {
  4780. if (set->entries[i].ptr == index) {
  4781. return i+1;
  4782. }
  4783. }
  4784. }
  4785. if (err_on_not_found) {
  4786. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  4787. }
  4788. return -1;
  4789. }
  4790. lbValue lb_typeid(lbModule *m, Type *type) {
  4791. type = default_type(type);
  4792. u64 id = cast(u64)lb_type_info_index(m->info, type);
  4793. GB_ASSERT(id >= 0);
  4794. u64 kind = Typeid_Invalid;
  4795. u64 named = is_type_named(type) && type->kind != Type_Basic;
  4796. u64 special = 0;
  4797. u64 reserved = 0;
  4798. Type *bt = base_type(type);
  4799. TypeKind tk = bt->kind;
  4800. switch (tk) {
  4801. case Type_Basic: {
  4802. u32 flags = bt->Basic.flags;
  4803. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  4804. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  4805. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  4806. if (flags & BasicFlag_Float) kind = Typeid_Float;
  4807. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  4808. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  4809. if (flags & BasicFlag_String) kind = Typeid_String;
  4810. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  4811. } break;
  4812. case Type_Pointer: kind = Typeid_Pointer; break;
  4813. case Type_Array: kind = Typeid_Array; break;
  4814. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  4815. case Type_Slice: kind = Typeid_Slice; break;
  4816. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  4817. case Type_Map: kind = Typeid_Map; break;
  4818. case Type_Struct: kind = Typeid_Struct; break;
  4819. case Type_Enum: kind = Typeid_Enum; break;
  4820. case Type_Union: kind = Typeid_Union; break;
  4821. case Type_Tuple: kind = Typeid_Tuple; break;
  4822. case Type_Proc: kind = Typeid_Procedure; break;
  4823. case Type_BitSet: kind = Typeid_Bit_Set; break;
  4824. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  4825. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  4826. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  4827. }
  4828. if (is_type_cstring(type)) {
  4829. special = 1;
  4830. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  4831. special = 1;
  4832. }
  4833. u64 data = 0;
  4834. if (build_context.word_size == 4) {
  4835. GB_ASSERT(id <= (1u<<24u));
  4836. data |= (id &~ (1u<<24)) << 0u; // index
  4837. data |= (kind &~ (1u<<5)) << 24u; // kind
  4838. data |= (named &~ (1u<<1)) << 29u; // kind
  4839. data |= (special &~ (1u<<1)) << 30u; // kind
  4840. data |= (reserved &~ (1u<<1)) << 31u; // kind
  4841. } else {
  4842. GB_ASSERT(build_context.word_size == 8);
  4843. GB_ASSERT(id <= (1ull<<56u));
  4844. data |= (id &~ (1ull<<56)) << 0ul; // index
  4845. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  4846. data |= (named &~ (1ull<<1)) << 61ull; // kind
  4847. data |= (special &~ (1ull<<1)) << 62ull; // kind
  4848. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  4849. }
  4850. lbValue res = {};
  4851. res.value = LLVMConstInt(lb_type(m, t_typeid), data, false);
  4852. res.type = t_typeid;
  4853. return res;
  4854. }
  4855. lbValue lb_type_info(lbModule *m, Type *type) {
  4856. type = default_type(type);
  4857. isize index = lb_type_info_index(m->info, type);
  4858. GB_ASSERT(index >= 0);
  4859. LLVMTypeRef it = lb_type(m, t_int);
  4860. LLVMValueRef indices[2] = {
  4861. LLVMConstInt(it, 0, false),
  4862. LLVMConstInt(it, index, true),
  4863. };
  4864. lbValue value = {};
  4865. value.value = LLVMConstGEP(lb_global_type_info_data_ptr(m).value, indices, gb_count_of(indices));
  4866. value.type = t_type_info_ptr;
  4867. return value;
  4868. }
  4869. LLVMValueRef lb_build_constant_array_values(lbModule *m, Type *type, Type *elem_type, isize count, LLVMValueRef *values, bool allow_local) {
  4870. bool is_local = allow_local && m->curr_procedure != nullptr;
  4871. bool is_const = true;
  4872. if (is_local) {
  4873. for (isize i = 0; i < count; i++) {
  4874. GB_ASSERT(values[i] != nullptr);
  4875. if (!LLVMIsConstant(values[i])) {
  4876. is_const = false;
  4877. break;
  4878. }
  4879. }
  4880. }
  4881. if (!is_const) {
  4882. lbProcedure *p = m->curr_procedure;
  4883. GB_ASSERT(p != nullptr);
  4884. lbAddr v = lb_add_local_generated(p, type, false);
  4885. lbValue ptr = lb_addr_get_ptr(p, v);
  4886. for (isize i = 0; i < count; i++) {
  4887. lbValue elem = lb_emit_array_epi(p, ptr, i);
  4888. LLVMBuildStore(p->builder, values[i], elem.value);
  4889. }
  4890. return lb_addr_load(p, v).value;
  4891. }
  4892. return llvm_const_array(lb_type(m, elem_type), values, cast(unsigned int)count);
  4893. }
  4894. lbValue lb_find_procedure_value_from_entity(lbModule *m, Entity *e) {
  4895. GB_ASSERT(is_type_proc(e->type));
  4896. e = strip_entity_wrapping(e);
  4897. GB_ASSERT(e != nullptr);
  4898. auto *found = map_get(&m->values, hash_entity(e));
  4899. if (found) {
  4900. return *found;
  4901. }
  4902. bool ignore_body = false;
  4903. if (USE_SEPARTE_MODULES) {
  4904. lbModule *other_module = lb_pkg_module(m->gen, e->pkg);
  4905. ignore_body = other_module != m;
  4906. }
  4907. lbProcedure *missing_proc = lb_create_procedure(m, e, ignore_body);
  4908. found = map_get(&m->values, hash_entity(e));
  4909. if (found) {
  4910. return *found;
  4911. }
  4912. GB_PANIC("Error in: %s, missing procedure %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  4913. return {};
  4914. }
  4915. lbValue lb_find_value_from_entity(lbModule *m, Entity *e) {
  4916. e = strip_entity_wrapping(e);
  4917. GB_ASSERT(e != nullptr);
  4918. GB_ASSERT(e->token.string != "_");
  4919. if (e->kind == Entity_Procedure) {
  4920. return lb_find_procedure_value_from_entity(m, e);
  4921. }
  4922. auto *found = map_get(&m->values, hash_entity(e));
  4923. if (found) {
  4924. return *found;
  4925. }
  4926. if (USE_SEPARTE_MODULES) {
  4927. lbModule *other_module = lb_pkg_module(m->gen, e->pkg);
  4928. // TODO(bill): correct this logic
  4929. bool is_external = other_module != m;
  4930. if (!is_external) {
  4931. if (e->code_gen_module != nullptr) {
  4932. other_module = e->code_gen_module;
  4933. } else {
  4934. other_module = nullptr;
  4935. }
  4936. is_external = other_module != m;
  4937. }
  4938. if (is_external) {
  4939. String name = lb_get_entity_name(other_module, e);
  4940. lbValue g = {};
  4941. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  4942. g.type = alloc_type_pointer(e->type);
  4943. lb_add_entity(m, e, g);
  4944. lb_add_member(m, name, g);
  4945. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  4946. // if (other_module != nullptr) {
  4947. // lbValue *other_found = string_map_get(&other_module->members, name);
  4948. // if (other_found) {
  4949. // lbValue other_g = *other_found;
  4950. // }
  4951. // }
  4952. // LLVMSetLinkage(other_g.value, LLVMExternalLinkage);
  4953. if (e->Variable.thread_local_model != "") {
  4954. LLVMSetThreadLocal(g.value, true);
  4955. String m = e->Variable.thread_local_model;
  4956. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  4957. if (m == "default") {
  4958. mode = LLVMGeneralDynamicTLSModel;
  4959. } else if (m == "localdynamic") {
  4960. mode = LLVMLocalDynamicTLSModel;
  4961. } else if (m == "initialexec") {
  4962. mode = LLVMInitialExecTLSModel;
  4963. } else if (m == "localexec") {
  4964. mode = LLVMLocalExecTLSModel;
  4965. } else {
  4966. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  4967. }
  4968. LLVMSetThreadLocalMode(g.value, mode);
  4969. }
  4970. return g;
  4971. }
  4972. }
  4973. GB_PANIC("\n\tError in: %s, missing value %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  4974. return {};
  4975. }
  4976. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  4977. LLVMContextRef ctx = m->ctx;
  4978. type = default_type(type);
  4979. Type *original_type = type;
  4980. lbValue res = {};
  4981. res.type = original_type;
  4982. type = core_type(type);
  4983. value = convert_exact_value_for_type(value, type);
  4984. if (value.kind == ExactValue_Typeid) {
  4985. return lb_typeid(m, value.value_typeid);
  4986. }
  4987. if (value.kind == ExactValue_Invalid) {
  4988. return lb_const_nil(m, type);
  4989. }
  4990. if (value.kind == ExactValue_Procedure) {
  4991. Ast *expr = unparen_expr(value.value_procedure);
  4992. if (expr->kind == Ast_ProcLit) {
  4993. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4994. }
  4995. Entity *e = entity_from_expr(expr);
  4996. return lb_find_procedure_value_from_entity(m, e);
  4997. }
  4998. bool is_local = allow_local && m->curr_procedure != nullptr;
  4999. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  5000. if (is_type_slice(type)) {
  5001. if (value.kind == ExactValue_String) {
  5002. GB_ASSERT(is_type_u8_slice(type));
  5003. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  5004. return res;
  5005. } else {
  5006. ast_node(cl, CompoundLit, value.value_compound);
  5007. isize count = cl->elems.count;
  5008. if (count == 0) {
  5009. return lb_const_nil(m, type);
  5010. }
  5011. count = gb_max(cl->max_count, count);
  5012. Type *elem = base_type(type)->Slice.elem;
  5013. Type *t = alloc_type_array(elem, count);
  5014. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  5015. LLVMValueRef array_data = nullptr;
  5016. if (is_local) {
  5017. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  5018. // its backing data on the stack
  5019. lbProcedure *p = m->curr_procedure;
  5020. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  5021. LLVMTypeRef llvm_type = lb_type(m, t);
  5022. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  5023. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  5024. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  5025. LLVMBuildStore(p->builder, backing_array.value, array_data);
  5026. {
  5027. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  5028. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  5029. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  5030. lbAddr slice = lb_add_local_generated(p, type, false);
  5031. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  5032. return lb_addr_load(p, slice);
  5033. }
  5034. } else {
  5035. isize max_len = 7+8+1;
  5036. char *str = gb_alloc_array(permanent_allocator(), char, max_len);
  5037. u32 id = cast(u32)gb_atomic32_fetch_add(&m->gen->global_array_index, 1);
  5038. isize len = gb_snprintf(str, max_len, "csba$%x", id);
  5039. String name = make_string(cast(u8 *)str, len-1);
  5040. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  5041. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  5042. LLVMSetInitializer(array_data, backing_array.value);
  5043. lbValue g = {};
  5044. g.value = array_data;
  5045. g.type = t;
  5046. lb_add_entity(m, e, g);
  5047. lb_add_member(m, name, g);
  5048. {
  5049. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  5050. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  5051. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  5052. LLVMValueRef values[2] = {ptr, len};
  5053. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  5054. return res;
  5055. }
  5056. }
  5057. }
  5058. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  5059. if (is_type_rune_array(type) && value.kind == ExactValue_String) {
  5060. i64 count = type->Array.count;
  5061. Type *elem = type->Array.elem;
  5062. LLVMTypeRef et = lb_type(m, elem);
  5063. Rune rune;
  5064. isize offset = 0;
  5065. isize width = 1;
  5066. String s = value.value_string;
  5067. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  5068. for (i64 i = 0; i < count && offset < s.len; i++) {
  5069. width = gb_utf8_decode(s.text+offset, s.len-offset, &rune);
  5070. offset += width;
  5071. elems[i] = LLVMConstInt(et, rune, true);
  5072. }
  5073. GB_ASSERT(offset == s.len);
  5074. res.value = llvm_const_array(et, elems, cast(unsigned)count);
  5075. return res;
  5076. }
  5077. GB_PANIC("This should not have happened!\n");
  5078. LLVMValueRef data = LLVMConstStringInContext(ctx,
  5079. cast(char const *)value.value_string.text,
  5080. cast(unsigned)value.value_string.len,
  5081. false /*DontNullTerminate*/);
  5082. res.value = data;
  5083. return res;
  5084. } else if (is_type_u8_array(type) && value.kind == ExactValue_String) {
  5085. GB_ASSERT(type->Array.count == value.value_string.len);
  5086. LLVMValueRef data = LLVMConstStringInContext(ctx,
  5087. cast(char const *)value.value_string.text,
  5088. cast(unsigned)value.value_string.len,
  5089. true /*DontNullTerminate*/);
  5090. res.value = data;
  5091. return res;
  5092. } else if (is_type_array(type) &&
  5093. value.kind != ExactValue_Invalid &&
  5094. value.kind != ExactValue_String &&
  5095. value.kind != ExactValue_Compound) {
  5096. i64 count = type->Array.count;
  5097. Type *elem = type->Array.elem;
  5098. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  5099. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  5100. for (i64 i = 0; i < count; i++) {
  5101. elems[i] = single_elem.value;
  5102. }
  5103. res.value = llvm_const_array(lb_type(m, elem), elems, cast(unsigned)count);
  5104. return res;
  5105. }
  5106. switch (value.kind) {
  5107. case ExactValue_Invalid:
  5108. res.value = LLVMConstNull(lb_type(m, original_type));
  5109. return res;
  5110. case ExactValue_Bool:
  5111. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  5112. return res;
  5113. case ExactValue_String:
  5114. {
  5115. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  5116. lbValue res = {};
  5117. res.type = default_type(original_type);
  5118. if (is_type_cstring(res.type)) {
  5119. res.value = ptr;
  5120. } else {
  5121. if (value.value_string.len == 0) {
  5122. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  5123. }
  5124. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  5125. LLVMValueRef values[2] = {ptr, str_len};
  5126. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  5127. }
  5128. return res;
  5129. }
  5130. case ExactValue_Integer:
  5131. if (is_type_pointer(type)) {
  5132. unsigned len = cast(unsigned)value.value_integer.len;
  5133. LLVMTypeRef t = lb_type(m, original_type);
  5134. if (len == 0) {
  5135. res.value = LLVMConstNull(t);
  5136. } else {
  5137. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), len, big_int_ptr(&value.value_integer));
  5138. res.value = LLVMConstIntToPtr(i, t);
  5139. }
  5140. } else {
  5141. unsigned len = cast(unsigned)value.value_integer.len;
  5142. if (len == 0) {
  5143. res.value = LLVMConstNull(lb_type(m, original_type));
  5144. } else {
  5145. u64 *words = big_int_ptr(&value.value_integer);
  5146. if (is_type_different_to_arch_endianness(type)) {
  5147. // NOTE(bill): Swap byte order for different endianness
  5148. i64 sz = type_size_of(type);
  5149. isize byte_len = gb_size_of(u64)*len;
  5150. u8 *old_bytes = cast(u8 *)words;
  5151. // TODO(bill): Use a different allocator here for a temporary allocation
  5152. u8 *new_bytes = cast(u8 *)gb_alloc_align(permanent_allocator(), byte_len, gb_align_of(u64));
  5153. for (i64 i = 0; i < sz; i++) {
  5154. new_bytes[i] = old_bytes[sz-1-i];
  5155. }
  5156. words = cast(u64 *)new_bytes;
  5157. }
  5158. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), len, words);
  5159. if (value.value_integer.neg) {
  5160. res.value = LLVMConstNeg(res.value);
  5161. }
  5162. }
  5163. }
  5164. return res;
  5165. case ExactValue_Float:
  5166. if (is_type_different_to_arch_endianness(type)) {
  5167. u64 u = bit_cast<u64>(value.value_float);
  5168. u = gb_endian_swap64(u);
  5169. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  5170. } else {
  5171. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  5172. }
  5173. return res;
  5174. case ExactValue_Complex:
  5175. {
  5176. LLVMValueRef values[2] = {};
  5177. switch (8*type_size_of(type)) {
  5178. case 32:
  5179. values[0] = lb_const_f16(m, cast(f32)value.value_complex->real);
  5180. values[1] = lb_const_f16(m, cast(f32)value.value_complex->imag);
  5181. break;
  5182. case 64:
  5183. values[0] = lb_const_f32(m, cast(f32)value.value_complex->real);
  5184. values[1] = lb_const_f32(m, cast(f32)value.value_complex->imag);
  5185. break;
  5186. case 128:
  5187. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->real);
  5188. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->imag);
  5189. break;
  5190. }
  5191. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  5192. return res;
  5193. }
  5194. break;
  5195. case ExactValue_Quaternion:
  5196. {
  5197. LLVMValueRef values[4] = {};
  5198. switch (8*type_size_of(type)) {
  5199. case 64:
  5200. // @QuaternionLayout
  5201. values[3] = lb_const_f16(m, cast(f32)value.value_quaternion->real);
  5202. values[0] = lb_const_f16(m, cast(f32)value.value_quaternion->imag);
  5203. values[1] = lb_const_f16(m, cast(f32)value.value_quaternion->jmag);
  5204. values[2] = lb_const_f16(m, cast(f32)value.value_quaternion->kmag);
  5205. break;
  5206. case 128:
  5207. // @QuaternionLayout
  5208. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion->real);
  5209. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion->imag);
  5210. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion->jmag);
  5211. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion->kmag);
  5212. break;
  5213. case 256:
  5214. // @QuaternionLayout
  5215. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->real);
  5216. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->imag);
  5217. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->jmag);
  5218. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->kmag);
  5219. break;
  5220. }
  5221. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 4);
  5222. return res;
  5223. }
  5224. break;
  5225. case ExactValue_Pointer:
  5226. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  5227. return res;
  5228. case ExactValue_Compound:
  5229. if (is_type_slice(type)) {
  5230. return lb_const_value(m, type, value, allow_local);
  5231. } else if (is_type_array(type)) {
  5232. ast_node(cl, CompoundLit, value.value_compound);
  5233. Type *elem_type = type->Array.elem;
  5234. isize elem_count = cl->elems.count;
  5235. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  5236. return lb_const_nil(m, original_type);
  5237. }
  5238. if (cl->elems[0]->kind == Ast_FieldValue) {
  5239. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  5240. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  5241. isize value_index = 0;
  5242. for (i64 i = 0; i < type->Array.count; i++) {
  5243. bool found = false;
  5244. for (isize j = 0; j < elem_count; j++) {
  5245. Ast *elem = cl->elems[j];
  5246. ast_node(fv, FieldValue, elem);
  5247. if (is_ast_range(fv->field)) {
  5248. ast_node(ie, BinaryExpr, fv->field);
  5249. TypeAndValue lo_tav = ie->left->tav;
  5250. TypeAndValue hi_tav = ie->right->tav;
  5251. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  5252. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  5253. TokenKind op = ie->op.kind;
  5254. i64 lo = exact_value_to_i64(lo_tav.value);
  5255. i64 hi = exact_value_to_i64(hi_tav.value);
  5256. if (op != Token_RangeHalf) {
  5257. hi += 1;
  5258. }
  5259. if (lo == i) {
  5260. TypeAndValue tav = fv->value->tav;
  5261. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5262. for (i64 k = lo; k < hi; k++) {
  5263. values[value_index++] = val;
  5264. }
  5265. found = true;
  5266. i += (hi-lo-1);
  5267. break;
  5268. }
  5269. } else {
  5270. TypeAndValue index_tav = fv->field->tav;
  5271. GB_ASSERT(index_tav.mode == Addressing_Constant);
  5272. i64 index = exact_value_to_i64(index_tav.value);
  5273. if (index == i) {
  5274. TypeAndValue tav = fv->value->tav;
  5275. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5276. values[value_index++] = val;
  5277. found = true;
  5278. break;
  5279. }
  5280. }
  5281. }
  5282. if (!found) {
  5283. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  5284. }
  5285. }
  5286. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  5287. return res;
  5288. } else {
  5289. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  5290. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  5291. for (isize i = 0; i < elem_count; i++) {
  5292. TypeAndValue tav = cl->elems[i]->tav;
  5293. GB_ASSERT(tav.mode != Addressing_Invalid);
  5294. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5295. }
  5296. for (isize i = elem_count; i < type->Array.count; i++) {
  5297. values[i] = LLVMConstNull(lb_type(m, elem_type));
  5298. }
  5299. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  5300. return res;
  5301. }
  5302. } else if (is_type_enumerated_array(type)) {
  5303. ast_node(cl, CompoundLit, value.value_compound);
  5304. Type *elem_type = type->EnumeratedArray.elem;
  5305. isize elem_count = cl->elems.count;
  5306. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  5307. return lb_const_nil(m, original_type);
  5308. }
  5309. if (cl->elems[0]->kind == Ast_FieldValue) {
  5310. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  5311. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  5312. isize value_index = 0;
  5313. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  5314. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  5315. for (i64 i = total_lo; i <= total_hi; i++) {
  5316. bool found = false;
  5317. for (isize j = 0; j < elem_count; j++) {
  5318. Ast *elem = cl->elems[j];
  5319. ast_node(fv, FieldValue, elem);
  5320. if (is_ast_range(fv->field)) {
  5321. ast_node(ie, BinaryExpr, fv->field);
  5322. TypeAndValue lo_tav = ie->left->tav;
  5323. TypeAndValue hi_tav = ie->right->tav;
  5324. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  5325. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  5326. TokenKind op = ie->op.kind;
  5327. i64 lo = exact_value_to_i64(lo_tav.value);
  5328. i64 hi = exact_value_to_i64(hi_tav.value);
  5329. if (op != Token_RangeHalf) {
  5330. hi += 1;
  5331. }
  5332. if (lo == i) {
  5333. TypeAndValue tav = fv->value->tav;
  5334. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5335. for (i64 k = lo; k < hi; k++) {
  5336. values[value_index++] = val;
  5337. }
  5338. found = true;
  5339. i += (hi-lo-1);
  5340. break;
  5341. }
  5342. } else {
  5343. TypeAndValue index_tav = fv->field->tav;
  5344. GB_ASSERT(index_tav.mode == Addressing_Constant);
  5345. i64 index = exact_value_to_i64(index_tav.value);
  5346. if (index == i) {
  5347. TypeAndValue tav = fv->value->tav;
  5348. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5349. values[value_index++] = val;
  5350. found = true;
  5351. break;
  5352. }
  5353. }
  5354. }
  5355. if (!found) {
  5356. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  5357. }
  5358. }
  5359. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  5360. return res;
  5361. } else {
  5362. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  5363. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  5364. for (isize i = 0; i < elem_count; i++) {
  5365. TypeAndValue tav = cl->elems[i]->tav;
  5366. GB_ASSERT(tav.mode != Addressing_Invalid);
  5367. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5368. }
  5369. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  5370. values[i] = LLVMConstNull(lb_type(m, elem_type));
  5371. }
  5372. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  5373. return res;
  5374. }
  5375. } else if (is_type_simd_vector(type)) {
  5376. ast_node(cl, CompoundLit, value.value_compound);
  5377. Type *elem_type = type->SimdVector.elem;
  5378. isize elem_count = cl->elems.count;
  5379. if (elem_count == 0) {
  5380. return lb_const_nil(m, original_type);
  5381. }
  5382. GB_ASSERT(elem_type_can_be_constant(elem_type));
  5383. isize total_elem_count = type->SimdVector.count;
  5384. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, total_elem_count);
  5385. for (isize i = 0; i < elem_count; i++) {
  5386. TypeAndValue tav = cl->elems[i]->tav;
  5387. GB_ASSERT(tav.mode != Addressing_Invalid);
  5388. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5389. }
  5390. LLVMTypeRef et = lb_type(m, elem_type);
  5391. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  5392. values[i] = LLVMConstNull(et);
  5393. }
  5394. for (isize i = 0; i< total_elem_count; i++) {
  5395. values[i] = llvm_const_cast(values[i], et);
  5396. }
  5397. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  5398. return res;
  5399. } else if (is_type_struct(type)) {
  5400. ast_node(cl, CompoundLit, value.value_compound);
  5401. if (cl->elems.count == 0) {
  5402. return lb_const_nil(m, original_type);
  5403. }
  5404. isize offset = 0;
  5405. if (type->Struct.custom_align > 0) {
  5406. offset = 1;
  5407. }
  5408. isize value_count = type->Struct.fields.count + offset;
  5409. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  5410. bool *visited = gb_alloc_array(temporary_allocator(), bool, value_count);
  5411. if (cl->elems.count > 0) {
  5412. if (cl->elems[0]->kind == Ast_FieldValue) {
  5413. isize elem_count = cl->elems.count;
  5414. for (isize i = 0; i < elem_count; i++) {
  5415. ast_node(fv, FieldValue, cl->elems[i]);
  5416. String name = fv->field->Ident.token.string;
  5417. TypeAndValue tav = fv->value->tav;
  5418. GB_ASSERT(tav.mode != Addressing_Invalid);
  5419. Selection sel = lookup_field(type, name, false);
  5420. Entity *f = type->Struct.fields[sel.index[0]];
  5421. if (elem_type_can_be_constant(f->type)) {
  5422. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  5423. visited[offset+f->Variable.field_index] = true;
  5424. }
  5425. }
  5426. } else {
  5427. for_array(i, cl->elems) {
  5428. Entity *f = type->Struct.fields[i];
  5429. TypeAndValue tav = cl->elems[i]->tav;
  5430. ExactValue val = {};
  5431. if (tav.mode != Addressing_Invalid) {
  5432. val = tav.value;
  5433. }
  5434. if (elem_type_can_be_constant(f->type)) {
  5435. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  5436. visited[offset+f->Variable.field_index] = true;
  5437. }
  5438. }
  5439. }
  5440. }
  5441. for (isize i = 0; i < type->Struct.fields.count; i++) {
  5442. if (!visited[offset+i]) {
  5443. GB_ASSERT(values[offset+i] == nullptr);
  5444. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  5445. }
  5446. }
  5447. if (type->Struct.custom_align > 0) {
  5448. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  5449. }
  5450. bool is_constant = true;
  5451. for (isize i = 0; i < value_count; i++) {
  5452. LLVMValueRef val = values[i];
  5453. if (!LLVMIsConstant(val)) {
  5454. GB_ASSERT(is_local);
  5455. GB_ASSERT(LLVMGetInstructionOpcode(val) == LLVMLoad);
  5456. is_constant = false;
  5457. }
  5458. }
  5459. if (is_constant) {
  5460. res.value = llvm_const_named_struct(lb_type(m, original_type), values, cast(unsigned)value_count);
  5461. return res;
  5462. } else {
  5463. // TODO(bill): THIS IS HACK BUT IT WORKS FOR WHAT I NEED
  5464. LLVMValueRef *old_values = values;
  5465. LLVMValueRef *new_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  5466. for (isize i = 0; i < value_count; i++) {
  5467. LLVMValueRef old_value = old_values[i];
  5468. if (LLVMIsConstant(old_value)) {
  5469. new_values[i] = old_value;
  5470. } else {
  5471. new_values[i] = LLVMConstNull(LLVMTypeOf(old_value));
  5472. }
  5473. }
  5474. LLVMValueRef constant_value = llvm_const_named_struct(lb_type(m, original_type), new_values, cast(unsigned)value_count);
  5475. GB_ASSERT(is_local);
  5476. lbProcedure *p = m->curr_procedure;
  5477. lbAddr v = lb_add_local_generated(p, res.type, true);
  5478. LLVMBuildStore(p->builder, constant_value, v.addr.value);
  5479. for (isize i = 0; i < value_count; i++) {
  5480. LLVMValueRef val = old_values[i];
  5481. if (!LLVMIsConstant(val)) {
  5482. LLVMValueRef dst = LLVMBuildStructGEP(p->builder, v.addr.value, cast(unsigned)i, "");
  5483. LLVMBuildStore(p->builder, val, dst);
  5484. }
  5485. }
  5486. return lb_addr_load(p, v);
  5487. }
  5488. } else if (is_type_bit_set(type)) {
  5489. ast_node(cl, CompoundLit, value.value_compound);
  5490. if (cl->elems.count == 0) {
  5491. return lb_const_nil(m, original_type);
  5492. }
  5493. i64 sz = type_size_of(type);
  5494. if (sz == 0) {
  5495. return lb_const_nil(m, original_type);
  5496. }
  5497. u64 bits = 0;
  5498. for_array(i, cl->elems) {
  5499. Ast *e = cl->elems[i];
  5500. GB_ASSERT(e->kind != Ast_FieldValue);
  5501. TypeAndValue tav = e->tav;
  5502. if (tav.mode != Addressing_Constant) {
  5503. continue;
  5504. }
  5505. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  5506. i64 v = big_int_to_i64(&tav.value.value_integer);
  5507. i64 lower = type->BitSet.lower;
  5508. bits |= 1ull<<cast(u64)(v-lower);
  5509. }
  5510. if (is_type_different_to_arch_endianness(type)) {
  5511. i64 size = type_size_of(type);
  5512. switch (size) {
  5513. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  5514. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  5515. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  5516. }
  5517. }
  5518. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  5519. return res;
  5520. } else {
  5521. return lb_const_nil(m, original_type);
  5522. }
  5523. break;
  5524. case ExactValue_Procedure:
  5525. {
  5526. Ast *expr = value.value_procedure;
  5527. GB_ASSERT(expr != nullptr);
  5528. if (expr->kind == Ast_ProcLit) {
  5529. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  5530. }
  5531. }
  5532. break;
  5533. case ExactValue_Typeid:
  5534. return lb_typeid(m, value.value_typeid);
  5535. }
  5536. return lb_const_nil(m, original_type);
  5537. }
  5538. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  5539. lbModule *m = p->module;
  5540. LLVMValueRef fields[4] = {};
  5541. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id)).value;
  5542. fields[1]/*line*/ = lb_const_int(m, t_i32, pos.line).value;
  5543. fields[2]/*column*/ = lb_const_int(m, t_i32, pos.column).value;
  5544. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  5545. lbValue res = {};
  5546. res.value = llvm_const_named_struct(lb_type(m, t_source_code_location), fields, gb_count_of(fields));
  5547. res.type = t_source_code_location;
  5548. return res;
  5549. }
  5550. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  5551. String proc_name = {};
  5552. if (p->entity) {
  5553. proc_name = p->entity->token.string;
  5554. }
  5555. TokenPos pos = {};
  5556. if (node) {
  5557. pos = ast_token(node).pos;
  5558. }
  5559. return lb_emit_source_code_location(p, proc_name, pos);
  5560. }
  5561. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  5562. switch (op) {
  5563. case Token_Add:
  5564. return x;
  5565. case Token_Not: // Boolean not
  5566. case Token_Xor: // Bitwise not
  5567. case Token_Sub: // Number negation
  5568. break;
  5569. case Token_Pointer:
  5570. GB_PANIC("This should be handled elsewhere");
  5571. break;
  5572. }
  5573. if (is_type_array(x.type)) {
  5574. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  5575. Type *tl = base_type(x.type);
  5576. lbValue val = lb_address_from_load_or_generate_local(p, x);
  5577. GB_ASSERT(is_type_array(type));
  5578. Type *elem_type = base_array_type(type);
  5579. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5580. lbAddr res_addr = lb_add_local_generated(p, type, false);
  5581. lbValue res = lb_addr_get_ptr(p, res_addr);
  5582. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5583. i32 count = cast(i32)tl->Array.count;
  5584. if (inline_array_arith) {
  5585. // inline
  5586. for (i32 i = 0; i < count; i++) {
  5587. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  5588. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5589. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  5590. }
  5591. } else {
  5592. auto loop_data = lb_loop_start(p, count, t_i32);
  5593. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  5594. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5595. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  5596. lb_loop_end(p, loop_data);
  5597. }
  5598. return lb_emit_load(p, res);
  5599. }
  5600. if (op == Token_Xor) {
  5601. lbValue cmp = {};
  5602. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  5603. cmp.type = x.type;
  5604. return lb_emit_conv(p, cmp, type);
  5605. }
  5606. if (op == Token_Not) {
  5607. lbValue cmp = {};
  5608. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  5609. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  5610. cmp.type = t_llvm_bool;
  5611. return lb_emit_conv(p, cmp, type);
  5612. }
  5613. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5614. Type *platform_type = integer_endian_type_to_platform_type(type);
  5615. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5616. lbValue res = {};
  5617. res.value = LLVMBuildNeg(p->builder, v.value, "");
  5618. res.type = platform_type;
  5619. return lb_emit_byte_swap(p, res, type);
  5620. }
  5621. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5622. Type *platform_type = integer_endian_type_to_platform_type(type);
  5623. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5624. lbValue res = {};
  5625. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  5626. res.type = platform_type;
  5627. return lb_emit_byte_swap(p, res, type);
  5628. }
  5629. lbValue res = {};
  5630. switch (op) {
  5631. case Token_Not: // Boolean not
  5632. case Token_Xor: // Bitwise not
  5633. res.value = LLVMBuildNot(p->builder, x.value, "");
  5634. res.type = x.type;
  5635. return res;
  5636. case Token_Sub: // Number negation
  5637. if (is_type_integer(x.type)) {
  5638. res.value = LLVMBuildNeg(p->builder, x.value, "");
  5639. } else if (is_type_float(x.type)) {
  5640. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  5641. } else if (is_type_complex(x.type)) {
  5642. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5643. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5644. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5645. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5646. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5647. return lb_addr_load(p, addr);
  5648. } else if (is_type_quaternion(x.type)) {
  5649. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5650. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5651. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  5652. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  5653. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5654. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5655. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5656. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  5657. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  5658. return lb_addr_load(p, addr);
  5659. } else {
  5660. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  5661. }
  5662. res.type = x.type;
  5663. return res;
  5664. }
  5665. return res;
  5666. }
  5667. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  5668. lbModule *m = p->module;
  5669. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  5670. lhs = lb_emit_conv(p, lhs, type);
  5671. rhs = lb_emit_conv(p, rhs, type);
  5672. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  5673. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  5674. GB_ASSERT(is_type_array(type));
  5675. Type *elem_type = base_array_type(type);
  5676. lbAddr res = lb_add_local_generated(p, type, false);
  5677. i64 count = base_type(type)->Array.count;
  5678. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5679. if (inline_array_arith) {
  5680. for (i64 i = 0; i < count; i++) {
  5681. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  5682. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  5683. lbValue dst_ptr = lb_emit_array_epi(p, res.addr, i);
  5684. lbValue a = lb_emit_load(p, a_ptr);
  5685. lbValue b = lb_emit_load(p, b_ptr);
  5686. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5687. lb_emit_store(p, dst_ptr, c);
  5688. }
  5689. } else {
  5690. auto loop_data = lb_loop_start(p, count, t_i32);
  5691. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  5692. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  5693. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  5694. lbValue a = lb_emit_load(p, a_ptr);
  5695. lbValue b = lb_emit_load(p, b_ptr);
  5696. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5697. lb_emit_store(p, dst_ptr, c);
  5698. lb_loop_end(p, loop_data);
  5699. }
  5700. return lb_addr_load(p, res);
  5701. } else if (is_type_complex(type)) {
  5702. lhs = lb_emit_conv(p, lhs, type);
  5703. rhs = lb_emit_conv(p, rhs, type);
  5704. Type *ft = base_complex_elem_type(type);
  5705. if (op == Token_Quo) {
  5706. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5707. args[0] = lhs;
  5708. args[1] = rhs;
  5709. switch (type_size_of(ft)) {
  5710. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  5711. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  5712. default: GB_PANIC("Unknown float type"); break;
  5713. }
  5714. }
  5715. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5716. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  5717. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  5718. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  5719. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  5720. lbValue real = {};
  5721. lbValue imag = {};
  5722. switch (op) {
  5723. case Token_Add:
  5724. real = lb_emit_arith(p, Token_Add, a, c, ft);
  5725. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  5726. break;
  5727. case Token_Sub:
  5728. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  5729. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  5730. break;
  5731. case Token_Mul: {
  5732. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  5733. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  5734. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  5735. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  5736. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  5737. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  5738. break;
  5739. }
  5740. }
  5741. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  5742. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  5743. return lb_addr_load(p, res);
  5744. } else if (is_type_quaternion(type)) {
  5745. lhs = lb_emit_conv(p, lhs, type);
  5746. rhs = lb_emit_conv(p, rhs, type);
  5747. Type *ft = base_complex_elem_type(type);
  5748. if (op == Token_Add || op == Token_Sub) {
  5749. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5750. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  5751. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  5752. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  5753. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  5754. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  5755. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  5756. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  5757. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  5758. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  5759. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  5760. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  5761. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  5762. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  5763. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  5764. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  5765. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  5766. return lb_addr_load(p, res);
  5767. } else if (op == Token_Mul) {
  5768. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5769. args[0] = lhs;
  5770. args[1] = rhs;
  5771. switch (8*type_size_of(ft)) {
  5772. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  5773. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  5774. default: GB_PANIC("Unknown float type"); break;
  5775. }
  5776. } else if (op == Token_Quo) {
  5777. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5778. args[0] = lhs;
  5779. args[1] = rhs;
  5780. switch (8*type_size_of(ft)) {
  5781. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  5782. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  5783. default: GB_PANIC("Unknown float type"); break;
  5784. }
  5785. }
  5786. }
  5787. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5788. switch (op) {
  5789. case Token_AndNot:
  5790. case Token_And:
  5791. case Token_Or:
  5792. case Token_Xor:
  5793. goto handle_op;
  5794. }
  5795. Type *platform_type = integer_endian_type_to_platform_type(type);
  5796. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5797. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5798. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5799. return lb_emit_byte_swap(p, res, type);
  5800. }
  5801. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5802. Type *platform_type = integer_endian_type_to_platform_type(type);
  5803. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5804. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5805. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5806. return lb_emit_byte_swap(p, res, type);
  5807. }
  5808. handle_op:
  5809. lhs = lb_emit_conv(p, lhs, type);
  5810. rhs = lb_emit_conv(p, rhs, type);
  5811. lbValue res = {};
  5812. res.type = type;
  5813. // NOTE(bill): Bit Set Aliases for + and -
  5814. if (is_type_bit_set(type)) {
  5815. switch (op) {
  5816. case Token_Add: op = Token_Or; break;
  5817. case Token_Sub: op = Token_AndNot; break;
  5818. }
  5819. }
  5820. switch (op) {
  5821. case Token_Add:
  5822. if (is_type_float(type)) {
  5823. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  5824. return res;
  5825. }
  5826. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  5827. return res;
  5828. case Token_Sub:
  5829. if (is_type_float(type)) {
  5830. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  5831. return res;
  5832. }
  5833. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  5834. return res;
  5835. case Token_Mul:
  5836. if (is_type_float(type)) {
  5837. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  5838. return res;
  5839. }
  5840. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  5841. return res;
  5842. case Token_Quo:
  5843. if (is_type_float(type)) {
  5844. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  5845. return res;
  5846. } else if (is_type_unsigned(type)) {
  5847. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  5848. return res;
  5849. }
  5850. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  5851. return res;
  5852. case Token_Mod:
  5853. if (is_type_float(type)) {
  5854. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  5855. return res;
  5856. } else if (is_type_unsigned(type)) {
  5857. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5858. return res;
  5859. }
  5860. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5861. return res;
  5862. case Token_ModMod:
  5863. if (is_type_unsigned(type)) {
  5864. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5865. return res;
  5866. } else {
  5867. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5868. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  5869. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  5870. res.value = c;
  5871. return res;
  5872. }
  5873. case Token_And:
  5874. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  5875. return res;
  5876. case Token_Or:
  5877. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  5878. return res;
  5879. case Token_Xor:
  5880. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  5881. return res;
  5882. case Token_Shl:
  5883. {
  5884. rhs = lb_emit_conv(p, rhs, lhs.type);
  5885. LLVMValueRef lhsval = lhs.value;
  5886. LLVMValueRef bits = rhs.value;
  5887. LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  5888. LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
  5889. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  5890. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  5891. res.value = LLVMBuildSelect(p->builder, width_test, res.value, zero, "");
  5892. return res;
  5893. }
  5894. case Token_Shr:
  5895. {
  5896. rhs = lb_emit_conv(p, rhs, lhs.type);
  5897. LLVMValueRef lhsval = lhs.value;
  5898. LLVMValueRef bits = rhs.value;
  5899. bool is_unsigned = is_type_unsigned(type);
  5900. LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  5901. LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
  5902. if (is_unsigned) {
  5903. res.value = LLVMBuildLShr(p->builder, lhsval, bits, "");
  5904. } else {
  5905. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  5906. }
  5907. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  5908. res.value = LLVMBuildSelect(p->builder, width_test, res.value, zero, "");
  5909. return res;
  5910. }
  5911. case Token_AndNot:
  5912. {
  5913. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  5914. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  5915. return res;
  5916. }
  5917. break;
  5918. }
  5919. GB_PANIC("unhandled operator of lb_emit_arith");
  5920. return {};
  5921. }
  5922. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  5923. ast_node(be, BinaryExpr, expr);
  5924. TypeAndValue tv = type_and_value_of_expr(expr);
  5925. switch (be->op.kind) {
  5926. case Token_Add:
  5927. case Token_Sub:
  5928. case Token_Mul:
  5929. case Token_Quo:
  5930. case Token_Mod:
  5931. case Token_ModMod:
  5932. case Token_And:
  5933. case Token_Or:
  5934. case Token_Xor:
  5935. case Token_AndNot: {
  5936. Type *type = default_type(tv.type);
  5937. lbValue left = lb_build_expr(p, be->left);
  5938. lbValue right = lb_build_expr(p, be->right);
  5939. return lb_emit_arith(p, be->op.kind, left, right, type);
  5940. }
  5941. case Token_Shl:
  5942. case Token_Shr: {
  5943. lbValue left, right;
  5944. Type *type = default_type(tv.type);
  5945. left = lb_build_expr(p, be->left);
  5946. if (lb_is_expr_untyped_const(be->right)) {
  5947. // NOTE(bill): RHS shift operands can still be untyped
  5948. // Just bypass the standard lb_build_expr
  5949. right = lb_expr_untyped_const_to_typed(p->module, be->right, type);
  5950. } else {
  5951. right = lb_build_expr(p, be->right);
  5952. }
  5953. return lb_emit_arith(p, be->op.kind, left, right, type);
  5954. }
  5955. case Token_CmpEq:
  5956. case Token_NotEq:
  5957. case Token_Lt:
  5958. case Token_LtEq:
  5959. case Token_Gt:
  5960. case Token_GtEq:
  5961. {
  5962. lbValue left = {};
  5963. lbValue right = {};
  5964. if (be->left->tav.mode == Addressing_Type) {
  5965. left = lb_typeid(p->module, be->left->tav.type);
  5966. }
  5967. if (be->right->tav.mode == Addressing_Type) {
  5968. right = lb_typeid(p->module, be->right->tav.type);
  5969. }
  5970. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  5971. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  5972. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  5973. Type *type = default_type(tv.type);
  5974. return lb_emit_conv(p, cmp, type);
  5975. }
  5976. case Token_CmpAnd:
  5977. case Token_CmpOr:
  5978. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  5979. case Token_in:
  5980. case Token_not_in:
  5981. {
  5982. lbValue left = lb_build_expr(p, be->left);
  5983. Type *type = default_type(tv.type);
  5984. lbValue right = lb_build_expr(p, be->right);
  5985. Type *rt = base_type(right.type);
  5986. switch (rt->kind) {
  5987. case Type_Map:
  5988. {
  5989. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  5990. lbValue h = lb_gen_map_header(p, addr, rt);
  5991. lbValue key = lb_gen_map_hash(p, left, rt->Map.key);
  5992. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5993. args[0] = h;
  5994. args[1] = key;
  5995. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  5996. if (be->op.kind == Token_in) {
  5997. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  5998. } else {
  5999. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  6000. }
  6001. }
  6002. break;
  6003. case Type_BitSet:
  6004. {
  6005. Type *key_type = rt->BitSet.elem;
  6006. GB_ASSERT(are_types_identical(left.type, key_type));
  6007. Type *it = bit_set_to_int(rt);
  6008. left = lb_emit_conv(p, left, it);
  6009. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  6010. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  6011. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  6012. bit = lb_emit_conv(p, bit, it);
  6013. lbValue old_value = lb_emit_transmute(p, right, it);
  6014. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  6015. if (be->op.kind == Token_in) {
  6016. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  6017. } else {
  6018. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  6019. }
  6020. }
  6021. break;
  6022. default:
  6023. GB_PANIC("Invalid 'in' type");
  6024. }
  6025. break;
  6026. }
  6027. break;
  6028. default:
  6029. GB_PANIC("Invalid binary expression");
  6030. break;
  6031. }
  6032. return {};
  6033. }
  6034. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  6035. Type *prev_src = src;
  6036. // Type *prev_dst = dst;
  6037. src = base_type(type_deref(src));
  6038. // dst = base_type(type_deref(dst));
  6039. bool src_is_ptr = src != prev_src;
  6040. // bool dst_is_ptr = dst != prev_dst;
  6041. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  6042. for_array(i, src->Struct.fields) {
  6043. Entity *f = src->Struct.fields[i];
  6044. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  6045. if (are_types_identical(dst, f->type)) {
  6046. return f->token.string;
  6047. }
  6048. if (src_is_ptr && is_type_pointer(dst)) {
  6049. if (are_types_identical(type_deref(dst), f->type)) {
  6050. return f->token.string;
  6051. }
  6052. }
  6053. if (is_type_struct(f->type)) {
  6054. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  6055. if (name.len > 0) {
  6056. return name;
  6057. }
  6058. }
  6059. }
  6060. }
  6061. return str_lit("");
  6062. }
  6063. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  6064. GB_ASSERT(is_type_pointer(value.type));
  6065. GB_ASSERT(is_type_pointer(t));
  6066. GB_ASSERT(lb_is_const(value));
  6067. lbValue res = {};
  6068. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  6069. res.type = t;
  6070. return res;
  6071. }
  6072. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  6073. lbModule *m = p->module;
  6074. t = reduce_tuple_to_single_type(t);
  6075. Type *src_type = value.type;
  6076. if (are_types_identical(t, src_type)) {
  6077. return value;
  6078. }
  6079. Type *src = core_type(src_type);
  6080. Type *dst = core_type(t);
  6081. GB_ASSERT(src != nullptr);
  6082. GB_ASSERT(dst != nullptr);
  6083. if (is_type_untyped_nil(src)) {
  6084. return lb_const_nil(m, t);
  6085. }
  6086. if (is_type_untyped_undef(src)) {
  6087. return lb_const_undef(m, t);
  6088. }
  6089. if (LLVMIsConstant(value.value)) {
  6090. if (is_type_any(dst)) {
  6091. Type *st = default_type(src_type);
  6092. lbAddr default_value = lb_add_local_generated(p, st, false);
  6093. lb_addr_store(p, default_value, value);
  6094. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  6095. lbValue id = lb_typeid(m, st);
  6096. lbAddr res = lb_add_local_generated(p, t, false);
  6097. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  6098. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  6099. lb_emit_store(p, a0, data);
  6100. lb_emit_store(p, a1, id);
  6101. return lb_addr_load(p, res);
  6102. } else if (dst->kind == Type_Basic) {
  6103. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  6104. String str = lb_get_const_string(m, value);
  6105. lbValue res = {};
  6106. res.type = t;
  6107. res.value = llvm_cstring(m, str);
  6108. return res;
  6109. }
  6110. // if (is_type_float(dst)) {
  6111. // return value;
  6112. // } else if (is_type_integer(dst)) {
  6113. // return value;
  6114. // }
  6115. // ExactValue ev = value->Constant.value;
  6116. // if (is_type_float(dst)) {
  6117. // ev = exact_value_to_float(ev);
  6118. // } else if (is_type_complex(dst)) {
  6119. // ev = exact_value_to_complex(ev);
  6120. // } else if (is_type_quaternion(dst)) {
  6121. // ev = exact_value_to_quaternion(ev);
  6122. // } else if (is_type_string(dst)) {
  6123. // // Handled elsewhere
  6124. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  6125. // } else if (is_type_integer(dst)) {
  6126. // ev = exact_value_to_integer(ev);
  6127. // } else if (is_type_pointer(dst)) {
  6128. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  6129. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  6130. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  6131. // }
  6132. // return lb_const_value(p->module, t, ev);
  6133. }
  6134. }
  6135. if (are_types_identical(src, dst)) {
  6136. if (!are_types_identical(src_type, t)) {
  6137. return lb_emit_transmute(p, value, t);
  6138. }
  6139. return value;
  6140. }
  6141. // bool <-> llvm bool
  6142. if (is_type_boolean(src) && dst == t_llvm_bool) {
  6143. lbValue res = {};
  6144. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  6145. res.type = dst;
  6146. return res;
  6147. }
  6148. if (src == t_llvm_bool && is_type_boolean(dst)) {
  6149. lbValue res = {};
  6150. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  6151. res.type = dst;
  6152. return res;
  6153. }
  6154. // integer -> integer
  6155. if (is_type_integer(src) && is_type_integer(dst)) {
  6156. GB_ASSERT(src->kind == Type_Basic &&
  6157. dst->kind == Type_Basic);
  6158. i64 sz = type_size_of(default_type(src));
  6159. i64 dz = type_size_of(default_type(dst));
  6160. if (sz == dz) {
  6161. if (dz > 1 && !types_have_same_internal_endian(src, dst)) {
  6162. return lb_emit_byte_swap(p, value, t);
  6163. }
  6164. lbValue res = {};
  6165. res.value = value.value;
  6166. res.type = t;
  6167. return res;
  6168. }
  6169. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  6170. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6171. value = lb_emit_byte_swap(p, value, platform_src_type);
  6172. }
  6173. LLVMOpcode op = LLVMTrunc;
  6174. if (dz < sz) {
  6175. op = LLVMTrunc;
  6176. } else if (dz == sz) {
  6177. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  6178. // NOTE(bill): Copy the value just for type correctness
  6179. op = LLVMBitCast;
  6180. } else if (dz > sz) {
  6181. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  6182. }
  6183. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  6184. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6185. lbValue res = {};
  6186. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  6187. res.type = t;
  6188. return lb_emit_byte_swap(p, res, t);
  6189. } else {
  6190. lbValue res = {};
  6191. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  6192. res.type = t;
  6193. return res;
  6194. }
  6195. }
  6196. // boolean -> boolean/integer
  6197. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  6198. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  6199. lbValue res = {};
  6200. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  6201. res.type = t;
  6202. return res;
  6203. }
  6204. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  6205. return lb_emit_transmute(p, value, dst);
  6206. }
  6207. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  6208. return lb_emit_transmute(p, value, dst);
  6209. }
  6210. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  6211. return lb_emit_transmute(p, value, dst);
  6212. }
  6213. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  6214. return lb_emit_transmute(p, value, dst);
  6215. }
  6216. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  6217. lbValue c = lb_emit_conv(p, value, t_cstring);
  6218. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6219. args[0] = c;
  6220. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  6221. return lb_emit_conv(p, s, dst);
  6222. }
  6223. // integer -> boolean
  6224. if (is_type_integer(src) && is_type_boolean(dst)) {
  6225. lbValue res = {};
  6226. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  6227. res.type = t_llvm_bool;
  6228. return lb_emit_conv(p, res, t);
  6229. }
  6230. // float -> float
  6231. if (is_type_float(src) && is_type_float(dst)) {
  6232. i64 sz = type_size_of(src);
  6233. i64 dz = type_size_of(dst);
  6234. if (dz == sz) {
  6235. if (types_have_same_internal_endian(src, dst)) {
  6236. lbValue res = {};
  6237. res.type = t;
  6238. res.value = value.value;
  6239. return res;
  6240. } else {
  6241. return lb_emit_byte_swap(p, value, t);
  6242. }
  6243. }
  6244. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6245. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6246. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6247. lbValue res = {};
  6248. res = lb_emit_conv(p, value, platform_src_type);
  6249. res = lb_emit_conv(p, res, platform_dst_type);
  6250. if (is_type_different_to_arch_endianness(dst)) {
  6251. res = lb_emit_byte_swap(p, res, t);
  6252. }
  6253. return lb_emit_conv(p, res, t);
  6254. }
  6255. lbValue res = {};
  6256. res.type = t;
  6257. if (dz >= sz) {
  6258. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  6259. } else {
  6260. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  6261. }
  6262. return res;
  6263. }
  6264. if (is_type_complex(src) && is_type_complex(dst)) {
  6265. Type *ft = base_complex_elem_type(dst);
  6266. lbAddr gen = lb_add_local_generated(p, dst, false);
  6267. lbValue gp = lb_addr_get_ptr(p, gen);
  6268. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6269. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6270. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  6271. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  6272. return lb_addr_load(p, gen);
  6273. }
  6274. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  6275. // @QuaternionLayout
  6276. Type *ft = base_complex_elem_type(dst);
  6277. lbAddr gen = lb_add_local_generated(p, dst, false);
  6278. lbValue gp = lb_addr_get_ptr(p, gen);
  6279. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6280. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6281. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  6282. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  6283. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  6284. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  6285. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  6286. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  6287. return lb_addr_load(p, gen);
  6288. }
  6289. if (is_type_float(src) && is_type_complex(dst)) {
  6290. Type *ft = base_complex_elem_type(dst);
  6291. lbAddr gen = lb_add_local_generated(p, dst, true);
  6292. lbValue gp = lb_addr_get_ptr(p, gen);
  6293. lbValue real = lb_emit_conv(p, value, ft);
  6294. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  6295. return lb_addr_load(p, gen);
  6296. }
  6297. if (is_type_float(src) && is_type_quaternion(dst)) {
  6298. Type *ft = base_complex_elem_type(dst);
  6299. lbAddr gen = lb_add_local_generated(p, dst, true);
  6300. lbValue gp = lb_addr_get_ptr(p, gen);
  6301. lbValue real = lb_emit_conv(p, value, ft);
  6302. // @QuaternionLayout
  6303. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  6304. return lb_addr_load(p, gen);
  6305. }
  6306. if (is_type_complex(src) && is_type_quaternion(dst)) {
  6307. Type *ft = base_complex_elem_type(dst);
  6308. lbAddr gen = lb_add_local_generated(p, dst, true);
  6309. lbValue gp = lb_addr_get_ptr(p, gen);
  6310. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6311. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6312. // @QuaternionLayout
  6313. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  6314. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  6315. return lb_addr_load(p, gen);
  6316. }
  6317. // float <-> integer
  6318. if (is_type_float(src) && is_type_integer(dst)) {
  6319. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6320. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6321. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6322. lbValue res = {};
  6323. res = lb_emit_conv(p, value, platform_src_type);
  6324. res = lb_emit_conv(p, res, platform_dst_type);
  6325. if (is_type_different_to_arch_endianness(dst)) {
  6326. res = lb_emit_byte_swap(p, res, t);
  6327. }
  6328. return lb_emit_conv(p, res, t);
  6329. }
  6330. lbValue res = {};
  6331. res.type = t;
  6332. if (is_type_unsigned(dst)) {
  6333. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  6334. } else {
  6335. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  6336. }
  6337. return res;
  6338. }
  6339. if (is_type_integer(src) && is_type_float(dst)) {
  6340. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6341. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6342. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6343. lbValue res = {};
  6344. res = lb_emit_conv(p, value, platform_src_type);
  6345. res = lb_emit_conv(p, res, platform_dst_type);
  6346. if (is_type_different_to_arch_endianness(dst)) {
  6347. res = lb_emit_byte_swap(p, res, t);
  6348. }
  6349. return lb_emit_conv(p, res, t);
  6350. }
  6351. lbValue res = {};
  6352. res.type = t;
  6353. if (is_type_unsigned(src)) {
  6354. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  6355. } else {
  6356. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  6357. }
  6358. return res;
  6359. }
  6360. // Pointer <-> uintptr
  6361. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  6362. lbValue res = {};
  6363. res.type = t;
  6364. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6365. return res;
  6366. }
  6367. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  6368. lbValue res = {};
  6369. res.type = t;
  6370. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6371. return res;
  6372. }
  6373. #if 1
  6374. if (is_type_union(dst)) {
  6375. for_array(i, dst->Union.variants) {
  6376. Type *vt = dst->Union.variants[i];
  6377. if (are_types_identical(vt, src_type)) {
  6378. lbAddr parent = lb_add_local_generated(p, t, true);
  6379. lb_emit_store_union_variant(p, parent.addr, value, vt);
  6380. return lb_addr_load(p, parent);
  6381. }
  6382. }
  6383. }
  6384. #endif
  6385. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  6386. // subtype polymorphism casting
  6387. if (check_is_assignable_to_using_subtype(src_type, t)) {
  6388. Type *st = type_deref(src_type);
  6389. Type *pst = st;
  6390. st = type_deref(st);
  6391. bool st_is_ptr = is_type_pointer(src_type);
  6392. st = base_type(st);
  6393. Type *dt = t;
  6394. bool dt_is_ptr = type_deref(dt) != dt;
  6395. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  6396. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  6397. if (field_name.len > 0) {
  6398. // NOTE(bill): It can be casted
  6399. Selection sel = lookup_field(st, field_name, false, true);
  6400. if (sel.entity != nullptr) {
  6401. if (st_is_ptr) {
  6402. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  6403. Type *rt = res.type;
  6404. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  6405. res = lb_emit_load(p, res);
  6406. }
  6407. return res;
  6408. } else {
  6409. if (is_type_pointer(value.type)) {
  6410. Type *rt = value.type;
  6411. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  6412. value = lb_emit_load(p, value);
  6413. } else {
  6414. value = lb_emit_deep_field_gep(p, value, sel);
  6415. return lb_emit_load(p, value);
  6416. }
  6417. }
  6418. return lb_emit_deep_field_ev(p, value, sel);
  6419. }
  6420. } else {
  6421. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  6422. }
  6423. }
  6424. }
  6425. // Pointer <-> Pointer
  6426. if (is_type_pointer(src) && is_type_pointer(dst)) {
  6427. lbValue res = {};
  6428. res.type = t;
  6429. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6430. return res;
  6431. }
  6432. // proc <-> proc
  6433. if (is_type_proc(src) && is_type_proc(dst)) {
  6434. lbValue res = {};
  6435. res.type = t;
  6436. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6437. return res;
  6438. }
  6439. // pointer -> proc
  6440. if (is_type_pointer(src) && is_type_proc(dst)) {
  6441. lbValue res = {};
  6442. res.type = t;
  6443. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6444. return res;
  6445. }
  6446. // proc -> pointer
  6447. if (is_type_proc(src) && is_type_pointer(dst)) {
  6448. lbValue res = {};
  6449. res.type = t;
  6450. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6451. return res;
  6452. }
  6453. // []byte/[]u8 <-> string
  6454. if (is_type_u8_slice(src) && is_type_string(dst)) {
  6455. return lb_emit_transmute(p, value, t);
  6456. }
  6457. if (is_type_string(src) && is_type_u8_slice(dst)) {
  6458. return lb_emit_transmute(p, value, t);
  6459. }
  6460. if (is_type_array(dst)) {
  6461. Type *elem = dst->Array.elem;
  6462. lbValue e = lb_emit_conv(p, value, elem);
  6463. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  6464. lbAddr v = lb_add_local_generated(p, t, false);
  6465. isize index_count = cast(isize)dst->Array.count;
  6466. for (isize i = 0; i < index_count; i++) {
  6467. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  6468. lb_emit_store(p, elem, e);
  6469. }
  6470. return lb_addr_load(p, v);
  6471. }
  6472. if (is_type_any(dst)) {
  6473. if (is_type_untyped_nil(src)) {
  6474. return lb_const_nil(p->module, t);
  6475. }
  6476. if (is_type_untyped_undef(src)) {
  6477. return lb_const_undef(p->module, t);
  6478. }
  6479. lbAddr result = lb_add_local_generated(p, t, true);
  6480. Type *st = default_type(src_type);
  6481. lbValue data = lb_address_from_load_or_generate_local(p, value);
  6482. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  6483. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  6484. data = lb_emit_conv(p, data, t_rawptr);
  6485. lbValue id = lb_typeid(p->module, st);
  6486. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  6487. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  6488. lb_emit_store(p, any_data, data);
  6489. lb_emit_store(p, any_id, id);
  6490. return lb_addr_load(p, result);
  6491. }
  6492. i64 src_sz = type_size_of(src);
  6493. i64 dst_sz = type_size_of(dst);
  6494. if (src_sz == dst_sz) {
  6495. // bit_set <-> integer
  6496. if (is_type_integer(src) && is_type_bit_set(dst)) {
  6497. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  6498. res.type = dst;
  6499. return res;
  6500. }
  6501. if (is_type_bit_set(src) && is_type_integer(dst)) {
  6502. lbValue bs = value;
  6503. bs.type = bit_set_to_int(src);
  6504. return lb_emit_conv(p, bs, dst);
  6505. }
  6506. // typeid <-> integer
  6507. if (is_type_integer(src) && is_type_typeid(dst)) {
  6508. return lb_emit_transmute(p, value, dst);
  6509. }
  6510. if (is_type_typeid(src) && is_type_integer(dst)) {
  6511. return lb_emit_transmute(p, value, dst);
  6512. }
  6513. }
  6514. if (is_type_untyped(src)) {
  6515. if (is_type_string(src) && is_type_string(dst)) {
  6516. lbAddr result = lb_add_local_generated(p, t, false);
  6517. lb_addr_store(p, result, value);
  6518. return lb_addr_load(p, result);
  6519. }
  6520. }
  6521. gb_printf_err("%.*s\n", LIT(p->name));
  6522. gb_printf_err("lb_emit_conv: src -> dst\n");
  6523. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  6524. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  6525. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  6526. gb_printf_err("Not Identical %p != %p\n", src, dst);
  6527. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  6528. type_to_string(src_type), type_to_string(t),
  6529. LIT(p->name));
  6530. return {};
  6531. }
  6532. bool lb_is_type_aggregate(Type *t) {
  6533. t = base_type(t);
  6534. switch (t->kind) {
  6535. case Type_Basic:
  6536. switch (t->Basic.kind) {
  6537. case Basic_string:
  6538. case Basic_any:
  6539. return true;
  6540. case Basic_complex32:
  6541. case Basic_complex64:
  6542. case Basic_complex128:
  6543. case Basic_quaternion64:
  6544. case Basic_quaternion128:
  6545. case Basic_quaternion256:
  6546. return true;
  6547. }
  6548. break;
  6549. case Type_Pointer:
  6550. return false;
  6551. case Type_Array:
  6552. case Type_Slice:
  6553. case Type_Struct:
  6554. case Type_Union:
  6555. case Type_Tuple:
  6556. case Type_DynamicArray:
  6557. case Type_Map:
  6558. case Type_SimdVector:
  6559. return true;
  6560. case Type_Named:
  6561. return lb_is_type_aggregate(t->Named.base);
  6562. }
  6563. return false;
  6564. }
  6565. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  6566. Type *src_type = value.type;
  6567. if (are_types_identical(t, src_type)) {
  6568. return value;
  6569. }
  6570. lbValue res = {};
  6571. res.type = t;
  6572. Type *src = base_type(src_type);
  6573. Type *dst = base_type(t);
  6574. lbModule *m = p->module;
  6575. i64 sz = type_size_of(src);
  6576. i64 dz = type_size_of(dst);
  6577. if (sz != dz) {
  6578. LLVMTypeRef s = lb_type(m, src);
  6579. LLVMTypeRef d = lb_type(m, dst);
  6580. i64 llvm_sz = lb_sizeof(s);
  6581. i64 llvm_dz = lb_sizeof(d);
  6582. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  6583. }
  6584. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  6585. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  6586. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  6587. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6588. return res;
  6589. }
  6590. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  6591. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6592. return res;
  6593. }
  6594. if (is_type_uintptr(src) && is_type_proc(dst)) {
  6595. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6596. return res;
  6597. }
  6598. if (is_type_proc(src) && is_type_uintptr(dst)) {
  6599. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6600. return res;
  6601. }
  6602. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  6603. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6604. return res;
  6605. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  6606. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6607. return res;
  6608. }
  6609. if (is_type_pointer(src) && is_type_pointer(dst)) {
  6610. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  6611. return res;
  6612. }
  6613. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  6614. lbValue s = lb_address_from_load_or_generate_local(p, value);
  6615. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  6616. return lb_emit_load(p, d);
  6617. }
  6618. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  6619. // GB_PANIC("lb_emit_transmute");
  6620. return res;
  6621. }
  6622. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  6623. GB_ASSERT(addr.kind == lbAddr_Context);
  6624. GB_ASSERT(addr.ctx.sel.index.count == 0);
  6625. lbModule *m = p->module;
  6626. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6627. args[0] = addr.addr;
  6628. lb_emit_runtime_call(p, "__init_context", args);
  6629. }
  6630. lbContextData *lb_push_context_onto_stack_from_implicit_parameter(lbProcedure *p) {
  6631. Type *pt = base_type(p->type);
  6632. GB_ASSERT(pt->kind == Type_Proc);
  6633. GB_ASSERT(pt->Proc.calling_convention == ProcCC_Odin);
  6634. String name = str_lit("__.context_ptr");
  6635. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), t_context_ptr, false, false);
  6636. e->flags |= EntityFlag_NoAlias;
  6637. LLVMValueRef context_ptr = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  6638. LLVMSetValueName2(context_ptr, cast(char const *)name.text, name.len);
  6639. context_ptr = LLVMBuildPointerCast(p->builder, context_ptr, lb_type(p->module, e->type), "");
  6640. lbValue param = {context_ptr, e->type};
  6641. lb_add_entity(p->module, e, param);
  6642. lbAddr ctx_addr = {};
  6643. ctx_addr.kind = lbAddr_Context;
  6644. ctx_addr.addr = param;
  6645. lbContextData *cd = array_add_and_get(&p->context_stack);
  6646. cd->ctx = ctx_addr;
  6647. cd->scope_index = -1;
  6648. cd->uses = +1; // make sure it has been used already
  6649. return cd;
  6650. }
  6651. lbContextData *lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  6652. ctx.kind = lbAddr_Context;
  6653. lbContextData *cd = array_add_and_get(&p->context_stack);
  6654. cd->ctx = ctx;
  6655. cd->scope_index = p->scope_index;
  6656. return cd;
  6657. }
  6658. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  6659. if (p->context_stack.count > 0) {
  6660. return p->context_stack[p->context_stack.count-1].ctx;
  6661. }
  6662. Type *pt = base_type(p->type);
  6663. GB_ASSERT(pt->kind == Type_Proc);
  6664. GB_ASSERT(pt->Proc.calling_convention != ProcCC_Odin);
  6665. lbAddr c = lb_add_local_generated(p, t_context, true);
  6666. c.kind = lbAddr_Context;
  6667. lb_emit_init_context(p, c);
  6668. lb_push_context_onto_stack(p, c);
  6669. lb_add_debug_context_variable(p, c);
  6670. return c;
  6671. }
  6672. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  6673. if (LLVMIsALoadInst(value.value)) {
  6674. lbValue res = {};
  6675. res.value = LLVMGetOperand(value.value, 0);
  6676. res.type = alloc_type_pointer(value.type);
  6677. return res;
  6678. }
  6679. GB_ASSERT(is_type_typed(value.type));
  6680. lbAddr res = lb_add_local_generated(p, value.type, false);
  6681. lb_addr_store(p, res, value);
  6682. return res.addr;
  6683. }
  6684. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  6685. if (LLVMIsALoadInst(value.value)) {
  6686. lbValue res = {};
  6687. res.value = LLVMGetOperand(value.value, 0);
  6688. res.type = alloc_type_pointer(value.type);
  6689. return res;
  6690. }
  6691. GB_PANIC("lb_address_from_load");
  6692. return {};
  6693. }
  6694. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  6695. i64 type_alignment = type_align_of(new_type);
  6696. if (alignment < type_alignment) {
  6697. alignment = type_alignment;
  6698. }
  6699. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  6700. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  6701. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  6702. lb_addr_store(p, ptr, val);
  6703. // ptr.kind = lbAddr_Context;
  6704. return ptr.addr;
  6705. }
  6706. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  6707. GB_ASSERT(is_type_pointer(s.type));
  6708. Type *t = base_type(type_deref(s.type));
  6709. Type *result_type = nullptr;
  6710. if (is_type_relative_pointer(t)) {
  6711. s = lb_addr_get_ptr(p, lb_addr(s));
  6712. }
  6713. if (is_type_struct(t)) {
  6714. result_type = get_struct_field_type(t, index);
  6715. } else if (is_type_union(t)) {
  6716. GB_ASSERT(index == -1);
  6717. return lb_emit_union_tag_ptr(p, s);
  6718. } else if (is_type_tuple(t)) {
  6719. GB_ASSERT(t->Tuple.variables.count > 0);
  6720. result_type = t->Tuple.variables[index]->type;
  6721. } else if (is_type_complex(t)) {
  6722. Type *ft = base_complex_elem_type(t);
  6723. switch (index) {
  6724. case 0: result_type = ft; break;
  6725. case 1: result_type = ft; break;
  6726. }
  6727. } else if (is_type_quaternion(t)) {
  6728. Type *ft = base_complex_elem_type(t);
  6729. switch (index) {
  6730. case 0: result_type = ft; break;
  6731. case 1: result_type = ft; break;
  6732. case 2: result_type = ft; break;
  6733. case 3: result_type = ft; break;
  6734. }
  6735. } else if (is_type_slice(t)) {
  6736. switch (index) {
  6737. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6738. case 1: result_type = t_int; break;
  6739. }
  6740. } else if (is_type_string(t)) {
  6741. switch (index) {
  6742. case 0: result_type = t_u8_ptr; break;
  6743. case 1: result_type = t_int; break;
  6744. }
  6745. } else if (is_type_any(t)) {
  6746. switch (index) {
  6747. case 0: result_type = t_rawptr; break;
  6748. case 1: result_type = t_typeid; break;
  6749. }
  6750. } else if (is_type_dynamic_array(t)) {
  6751. switch (index) {
  6752. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6753. case 1: result_type = t_int; break;
  6754. case 2: result_type = t_int; break;
  6755. case 3: result_type = t_allocator; break;
  6756. }
  6757. } else if (is_type_map(t)) {
  6758. init_map_internal_types(t);
  6759. Type *itp = alloc_type_pointer(t->Map.internal_type);
  6760. s = lb_emit_transmute(p, s, itp);
  6761. Type *gst = t->Map.internal_type;
  6762. GB_ASSERT(gst->kind == Type_Struct);
  6763. switch (index) {
  6764. case 0: result_type = get_struct_field_type(gst, 0); break;
  6765. case 1: result_type = get_struct_field_type(gst, 1); break;
  6766. }
  6767. } else if (is_type_array(t)) {
  6768. return lb_emit_array_epi(p, s, index);
  6769. } else if (is_type_relative_slice(t)) {
  6770. switch (index) {
  6771. case 0: result_type = t->RelativeSlice.base_integer; break;
  6772. case 1: result_type = t->RelativeSlice.base_integer; break;
  6773. }
  6774. } else {
  6775. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  6776. }
  6777. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  6778. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6779. index += 1;
  6780. }
  6781. if (lb_is_const(s)) {
  6782. lbModule *m = p->module;
  6783. lbValue res = {};
  6784. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  6785. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6786. res.type = alloc_type_pointer(result_type);
  6787. return res;
  6788. } else {
  6789. lbValue res = {};
  6790. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  6791. res.type = alloc_type_pointer(result_type);
  6792. return res;
  6793. }
  6794. }
  6795. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  6796. if (LLVMIsALoadInst(s.value)) {
  6797. lbValue res = {};
  6798. res.value = LLVMGetOperand(s.value, 0);
  6799. res.type = alloc_type_pointer(s.type);
  6800. lbValue ptr = lb_emit_struct_ep(p, res, index);
  6801. return lb_emit_load(p, ptr);
  6802. }
  6803. Type *t = base_type(s.type);
  6804. Type *result_type = nullptr;
  6805. switch (t->kind) {
  6806. case Type_Basic:
  6807. switch (t->Basic.kind) {
  6808. case Basic_string:
  6809. switch (index) {
  6810. case 0: result_type = t_u8_ptr; break;
  6811. case 1: result_type = t_int; break;
  6812. }
  6813. break;
  6814. case Basic_any:
  6815. switch (index) {
  6816. case 0: result_type = t_rawptr; break;
  6817. case 1: result_type = t_typeid; break;
  6818. }
  6819. break;
  6820. case Basic_complex32:
  6821. case Basic_complex64:
  6822. case Basic_complex128:
  6823. {
  6824. Type *ft = base_complex_elem_type(t);
  6825. switch (index) {
  6826. case 0: result_type = ft; break;
  6827. case 1: result_type = ft; break;
  6828. }
  6829. break;
  6830. }
  6831. case Basic_quaternion64:
  6832. case Basic_quaternion128:
  6833. case Basic_quaternion256:
  6834. {
  6835. Type *ft = base_complex_elem_type(t);
  6836. switch (index) {
  6837. case 0: result_type = ft; break;
  6838. case 1: result_type = ft; break;
  6839. case 2: result_type = ft; break;
  6840. case 3: result_type = ft; break;
  6841. }
  6842. break;
  6843. }
  6844. }
  6845. break;
  6846. case Type_Struct:
  6847. result_type = get_struct_field_type(t, index);
  6848. break;
  6849. case Type_Union:
  6850. GB_ASSERT(index == -1);
  6851. // return lb_emit_union_tag_value(p, s);
  6852. GB_PANIC("lb_emit_union_tag_value");
  6853. case Type_Tuple:
  6854. GB_ASSERT(t->Tuple.variables.count > 0);
  6855. result_type = t->Tuple.variables[index]->type;
  6856. if (t->Tuple.variables.count == 1) {
  6857. return s;
  6858. }
  6859. break;
  6860. case Type_Slice:
  6861. switch (index) {
  6862. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6863. case 1: result_type = t_int; break;
  6864. }
  6865. break;
  6866. case Type_DynamicArray:
  6867. switch (index) {
  6868. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6869. case 1: result_type = t_int; break;
  6870. case 2: result_type = t_int; break;
  6871. case 3: result_type = t_allocator; break;
  6872. }
  6873. break;
  6874. case Type_Map:
  6875. {
  6876. init_map_internal_types(t);
  6877. Type *gst = t->Map.generated_struct_type;
  6878. switch (index) {
  6879. case 0: result_type = get_struct_field_type(gst, 0); break;
  6880. case 1: result_type = get_struct_field_type(gst, 1); break;
  6881. }
  6882. }
  6883. break;
  6884. case Type_Array:
  6885. result_type = t->Array.elem;
  6886. break;
  6887. default:
  6888. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  6889. break;
  6890. }
  6891. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  6892. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6893. index += 1;
  6894. }
  6895. lbValue res = {};
  6896. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  6897. res.type = result_type;
  6898. return res;
  6899. }
  6900. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  6901. GB_ASSERT(sel.index.count > 0);
  6902. Type *type = type_deref(e.type);
  6903. for_array(i, sel.index) {
  6904. i32 index = cast(i32)sel.index[i];
  6905. if (is_type_pointer(type)) {
  6906. type = type_deref(type);
  6907. e = lb_emit_load(p, e);
  6908. }
  6909. type = core_type(type);
  6910. if (is_type_quaternion(type)) {
  6911. e = lb_emit_struct_ep(p, e, index);
  6912. } else if (is_type_raw_union(type)) {
  6913. type = get_struct_field_type(type, index);
  6914. GB_ASSERT(is_type_pointer(e.type));
  6915. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  6916. } else if (is_type_struct(type)) {
  6917. type = get_struct_field_type(type, index);
  6918. e = lb_emit_struct_ep(p, e, index);
  6919. } else if (type->kind == Type_Union) {
  6920. GB_ASSERT(index == -1);
  6921. type = t_type_info_ptr;
  6922. e = lb_emit_struct_ep(p, e, index);
  6923. } else if (type->kind == Type_Tuple) {
  6924. type = type->Tuple.variables[index]->type;
  6925. e = lb_emit_struct_ep(p, e, index);
  6926. } else if (type->kind == Type_Basic) {
  6927. switch (type->Basic.kind) {
  6928. case Basic_any: {
  6929. if (index == 0) {
  6930. type = t_rawptr;
  6931. } else if (index == 1) {
  6932. type = t_type_info_ptr;
  6933. }
  6934. e = lb_emit_struct_ep(p, e, index);
  6935. break;
  6936. }
  6937. case Basic_string:
  6938. e = lb_emit_struct_ep(p, e, index);
  6939. break;
  6940. default:
  6941. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6942. break;
  6943. }
  6944. } else if (type->kind == Type_Slice) {
  6945. e = lb_emit_struct_ep(p, e, index);
  6946. } else if (type->kind == Type_DynamicArray) {
  6947. e = lb_emit_struct_ep(p, e, index);
  6948. } else if (type->kind == Type_Array) {
  6949. e = lb_emit_array_epi(p, e, index);
  6950. } else if (type->kind == Type_Map) {
  6951. e = lb_emit_struct_ep(p, e, index);
  6952. } else if (type->kind == Type_RelativePointer) {
  6953. e = lb_emit_struct_ep(p, e, index);
  6954. } else {
  6955. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6956. }
  6957. }
  6958. return e;
  6959. }
  6960. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  6961. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  6962. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  6963. return lb_emit_load(p, res);
  6964. }
  6965. void lb_build_defer_stmt(lbProcedure *p, lbDefer const &d) {
  6966. // NOTE(bill): The prev block may defer injection before it's terminator
  6967. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  6968. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  6969. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  6970. return;
  6971. }
  6972. isize prev_context_stack_count = p->context_stack.count;
  6973. GB_ASSERT(prev_context_stack_count <= p->context_stack.capacity);
  6974. defer (p->context_stack.count = prev_context_stack_count);
  6975. p->context_stack.count = d.context_stack_count;
  6976. lbBlock *b = lb_create_block(p, "defer");
  6977. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  6978. lb_emit_jump(p, b);
  6979. }
  6980. lb_start_block(p, b);
  6981. if (d.kind == lbDefer_Node) {
  6982. lb_build_stmt(p, d.stmt);
  6983. } else if (d.kind == lbDefer_Instr) {
  6984. // NOTE(bill): Need to make a new copy
  6985. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  6986. LLVMInsertIntoBuilder(p->builder, instr);
  6987. } else if (d.kind == lbDefer_Proc) {
  6988. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  6989. }
  6990. }
  6991. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  6992. isize count = p->defer_stmts.count;
  6993. isize i = count;
  6994. while (i --> 0) {
  6995. lbDefer const &d = p->defer_stmts[i];
  6996. if (kind == lbDeferExit_Default) {
  6997. if (p->scope_index == d.scope_index &&
  6998. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  6999. lb_build_defer_stmt(p, d);
  7000. array_pop(&p->defer_stmts);
  7001. continue;
  7002. } else {
  7003. break;
  7004. }
  7005. } else if (kind == lbDeferExit_Return) {
  7006. lb_build_defer_stmt(p, d);
  7007. } else if (kind == lbDeferExit_Branch) {
  7008. GB_ASSERT(block != nullptr);
  7009. isize lower_limit = block->scope_index;
  7010. if (lower_limit < d.scope_index) {
  7011. lb_build_defer_stmt(p, d);
  7012. }
  7013. }
  7014. }
  7015. }
  7016. void lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  7017. Type *pt = base_type(p->type);
  7018. GB_ASSERT(pt->kind == Type_Proc);
  7019. if (pt->Proc.calling_convention == ProcCC_Odin) {
  7020. GB_ASSERT(p->context_stack.count != 0);
  7021. }
  7022. lbDefer *d = array_add_and_get(&p->defer_stmts);
  7023. d->kind = lbDefer_Node;
  7024. d->scope_index = scope_index;
  7025. d->context_stack_count = p->context_stack.count;
  7026. d->block = p->curr_block;
  7027. d->stmt = stmt;
  7028. }
  7029. void lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  7030. Type *pt = base_type(p->type);
  7031. GB_ASSERT(pt->kind == Type_Proc);
  7032. if (pt->Proc.calling_convention == ProcCC_Odin) {
  7033. GB_ASSERT(p->context_stack.count != 0);
  7034. }
  7035. lbDefer *d = array_add_and_get(&p->defer_stmts);
  7036. d->kind = lbDefer_Proc;
  7037. d->scope_index = p->scope_index;
  7038. d->block = p->curr_block;
  7039. d->context_stack_count = p->context_stack.count;
  7040. d->proc.deferred = deferred;
  7041. d->proc.result_as_args = result_as_args;
  7042. }
  7043. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  7044. Array<lbValue> array = {};
  7045. Type *t = base_type(value.type);
  7046. if (t == nullptr) {
  7047. // Do nothing
  7048. } else if (is_type_tuple(t)) {
  7049. GB_ASSERT(t->kind == Type_Tuple);
  7050. auto *rt = &t->Tuple;
  7051. if (rt->variables.count > 0) {
  7052. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  7053. for_array(i, rt->variables) {
  7054. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  7055. array[i] = elem;
  7056. }
  7057. }
  7058. } else {
  7059. array = array_make<lbValue>(permanent_allocator(), 1);
  7060. array[0] = value;
  7061. }
  7062. return array;
  7063. }
  7064. lbValue lb_emit_call_internal(lbProcedure *p, lbValue value, lbValue return_ptr, Array<lbValue> const &processed_args, Type *abi_rt, lbAddr context_ptr, ProcInlining inlining) {
  7065. GB_ASSERT(p->module->ctx == LLVMGetTypeContext(LLVMTypeOf(value.value)));
  7066. unsigned arg_count = cast(unsigned)processed_args.count;
  7067. if (return_ptr.value != nullptr) {
  7068. arg_count += 1;
  7069. }
  7070. if (context_ptr.addr.value != nullptr) {
  7071. arg_count += 1;
  7072. }
  7073. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  7074. isize arg_index = 0;
  7075. if (return_ptr.value != nullptr) {
  7076. args[arg_index++] = return_ptr.value;
  7077. }
  7078. for_array(i, processed_args) {
  7079. lbValue arg = processed_args[i];
  7080. args[arg_index++] = arg.value;
  7081. }
  7082. if (context_ptr.addr.value != nullptr) {
  7083. LLVMValueRef cp = context_ptr.addr.value;
  7084. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  7085. args[arg_index++] = cp;
  7086. }
  7087. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  7088. GB_ASSERT(curr_block != p->decl_block->block);
  7089. {
  7090. LLVMTypeRef ftp = lb_type(p->module, value.type);
  7091. LLVMTypeRef ft = LLVMGetElementType(ftp);
  7092. LLVMValueRef fn = value.value;
  7093. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  7094. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  7095. }
  7096. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  7097. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  7098. {
  7099. unsigned param_count = LLVMCountParamTypes(fnp);
  7100. GB_ASSERT(arg_count >= param_count);
  7101. LLVMTypeRef *param_types = gb_alloc_array(temporary_allocator(), LLVMTypeRef, param_count);
  7102. LLVMGetParamTypes(fnp, param_types);
  7103. for (unsigned i = 0; i < param_count; i++) {
  7104. LLVMTypeRef param_type = param_types[i];
  7105. LLVMTypeRef arg_type = LLVMTypeOf(args[i]);
  7106. GB_ASSERT_MSG(
  7107. arg_type == param_type,
  7108. "Parameter types do not match: %s != %s, argument: %s",
  7109. LLVMPrintTypeToString(arg_type),
  7110. LLVMPrintTypeToString(param_type),
  7111. LLVMPrintValueToString(args[i])
  7112. );
  7113. }
  7114. }
  7115. LLVMValueRef ret = LLVMBuildCall2(p->builder, fnp, fn, args, arg_count, "");
  7116. switch (inlining) {
  7117. case ProcInlining_none:
  7118. break;
  7119. case ProcInlining_inline:
  7120. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  7121. break;
  7122. case ProcInlining_no_inline:
  7123. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "noinline"));
  7124. break;
  7125. }
  7126. lbValue res = {};
  7127. res.value = ret;
  7128. res.type = abi_rt;
  7129. return res;
  7130. }
  7131. }
  7132. lbValue lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  7133. AstPackage *pkg = m->info->runtime_package;
  7134. Entity *e = scope_lookup_current(pkg->scope, name);
  7135. return lb_find_procedure_value_from_entity(m, e);
  7136. }
  7137. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  7138. String name = make_string_c(c_name);
  7139. lbValue proc = lb_lookup_runtime_procedure(p->module, name);
  7140. return lb_emit_call(p, proc, args);
  7141. }
  7142. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_copy_elision_hint) {
  7143. lbModule *m = p->module;
  7144. Type *pt = base_type(value.type);
  7145. GB_ASSERT(pt->kind == Type_Proc);
  7146. Type *results = pt->Proc.results;
  7147. if (p->entity != nullptr) {
  7148. if (p->entity->flags & EntityFlag_Disabled) {
  7149. return {};
  7150. }
  7151. }
  7152. lbAddr context_ptr = {};
  7153. if (pt->Proc.calling_convention == ProcCC_Odin) {
  7154. context_ptr = lb_find_or_generate_context_ptr(p);
  7155. }
  7156. defer (if (pt->Proc.diverging) {
  7157. LLVMBuildUnreachable(p->builder);
  7158. });
  7159. bool is_c_vararg = pt->Proc.c_vararg;
  7160. isize param_count = pt->Proc.param_count;
  7161. if (is_c_vararg) {
  7162. GB_ASSERT(param_count-1 <= args.count);
  7163. param_count -= 1;
  7164. } else {
  7165. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  7166. }
  7167. lbValue result = {};
  7168. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  7169. {
  7170. lbFunctionType *ft = lb_get_function_type(m, p, pt);
  7171. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  7172. unsigned param_index = 0;
  7173. for (isize i = 0; i < param_count; i++) {
  7174. Entity *e = pt->Proc.params->Tuple.variables[i];
  7175. if (e->kind != Entity_Variable) {
  7176. continue;
  7177. }
  7178. GB_ASSERT(e->flags & EntityFlag_Param);
  7179. Type *original_type = e->type;
  7180. lbArgType *arg = &ft->args[param_index];
  7181. if (arg->kind == lbArg_Ignore) {
  7182. continue;
  7183. }
  7184. lbValue x = lb_emit_conv(p, args[i], original_type);
  7185. LLVMTypeRef xt = lb_type(p->module, x.type);
  7186. if (arg->kind == lbArg_Direct) {
  7187. LLVMTypeRef abi_type = arg->cast_type;
  7188. if (!abi_type) {
  7189. abi_type = arg->type;
  7190. }
  7191. if (xt == abi_type) {
  7192. array_add(&processed_args, x);
  7193. } else {
  7194. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  7195. array_add(&processed_args, x);
  7196. }
  7197. } else if (arg->kind == lbArg_Indirect) {
  7198. lbValue ptr = {};
  7199. if (arg->is_byval) {
  7200. ptr = lb_copy_value_to_ptr(p, x, original_type, arg->byval_alignment);
  7201. } else if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  7202. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  7203. // i.e. `T const &` in C++
  7204. ptr = lb_address_from_load_or_generate_local(p, x);
  7205. } else {
  7206. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  7207. }
  7208. array_add(&processed_args, ptr);
  7209. }
  7210. param_index += 1;
  7211. }
  7212. if (is_c_vararg) {
  7213. for (isize i = processed_args.count; i < args.count; i++) {
  7214. array_add(&processed_args, args[i]);
  7215. }
  7216. }
  7217. if (inlining == ProcInlining_none) {
  7218. inlining = p->inlining;
  7219. }
  7220. Type *rt = reduce_tuple_to_single_type(results);
  7221. if (return_by_pointer) {
  7222. lbValue return_ptr = {};
  7223. if (use_copy_elision_hint && p->copy_elision_hint.ptr.value != nullptr) {
  7224. if (are_types_identical(type_deref(p->copy_elision_hint.ptr.type), rt)) {
  7225. return_ptr = lb_consume_copy_elision_hint(p);
  7226. }
  7227. }
  7228. if (return_ptr.value == nullptr) {
  7229. lbAddr r = lb_add_local_generated(p, rt, true);
  7230. return_ptr = r.addr;
  7231. }
  7232. GB_ASSERT(is_type_pointer(return_ptr.type));
  7233. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  7234. result = lb_emit_load(p, return_ptr);
  7235. } else if (rt != nullptr) {
  7236. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  7237. if (ft->ret.cast_type) {
  7238. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  7239. }
  7240. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  7241. result.type = rt;
  7242. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  7243. result.type = t_llvm_bool;
  7244. }
  7245. if (!is_type_tuple(rt)) {
  7246. result = lb_emit_conv(p, result, rt);
  7247. }
  7248. } else {
  7249. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  7250. }
  7251. }
  7252. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  7253. if (found != nullptr) {
  7254. Entity *e = *found;
  7255. if (e != nullptr && entity_has_deferred_procedure(e)) {
  7256. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  7257. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  7258. lbValue deferred = lb_find_procedure_value_from_entity(p->module, deferred_entity);
  7259. auto in_args = args;
  7260. Array<lbValue> result_as_args = {};
  7261. switch (kind) {
  7262. case DeferredProcedure_none:
  7263. break;
  7264. case DeferredProcedure_in:
  7265. result_as_args = in_args;
  7266. break;
  7267. case DeferredProcedure_out:
  7268. result_as_args = lb_value_to_array(p, result);
  7269. break;
  7270. case DeferredProcedure_in_out:
  7271. {
  7272. auto out_args = lb_value_to_array(p, result);
  7273. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  7274. array_copy(&result_as_args, in_args, 0);
  7275. array_copy(&result_as_args, out_args, in_args.count);
  7276. }
  7277. break;
  7278. }
  7279. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  7280. }
  7281. }
  7282. return result;
  7283. }
  7284. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  7285. Type *t = s.type;
  7286. GB_ASSERT(is_type_pointer(t));
  7287. Type *st = base_type(type_deref(t));
  7288. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  7289. GB_ASSERT_MSG(is_type_integer(core_type(index.type)), "%s", type_to_string(index.type));
  7290. LLVMValueRef indices[2] = {};
  7291. indices[0] = llvm_zero(p->module);
  7292. indices[1] = lb_emit_conv(p, index, t_int).value;
  7293. Type *ptr = base_array_type(st);
  7294. lbValue res = {};
  7295. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  7296. res.type = alloc_type_pointer(ptr);
  7297. return res;
  7298. }
  7299. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  7300. Type *t = s.type;
  7301. GB_ASSERT(is_type_pointer(t));
  7302. Type *st = base_type(type_deref(t));
  7303. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  7304. GB_ASSERT(0 <= index);
  7305. Type *ptr = base_array_type(st);
  7306. LLVMValueRef indices[2] = {
  7307. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  7308. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  7309. };
  7310. lbValue res = {};
  7311. if (lb_is_const(s)) {
  7312. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  7313. } else {
  7314. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  7315. }
  7316. res.type = alloc_type_pointer(ptr);
  7317. return res;
  7318. }
  7319. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  7320. LLVMValueRef indices[1] = {index.value};
  7321. lbValue res = {};
  7322. res.type = ptr.type;
  7323. if (lb_is_const(ptr) && lb_is_const(index)) {
  7324. res.value = LLVMConstGEP(ptr.value, indices, 1);
  7325. } else {
  7326. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  7327. }
  7328. return res;
  7329. }
  7330. LLVMValueRef llvm_const_slice(lbModule *m, lbValue data, lbValue len) {
  7331. GB_ASSERT(is_type_pointer(data.type));
  7332. GB_ASSERT(are_types_identical(len.type, t_int));
  7333. LLVMValueRef vals[2] = {
  7334. data.value,
  7335. len.value,
  7336. };
  7337. return LLVMConstStructInContext(m->ctx, vals, gb_count_of(vals), false);
  7338. }
  7339. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  7340. Type *t = lb_addr_type(slice);
  7341. GB_ASSERT(is_type_slice(t));
  7342. lbValue ptr = lb_addr_get_ptr(p, slice);
  7343. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  7344. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  7345. }
  7346. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  7347. Type *t = lb_addr_type(string);
  7348. GB_ASSERT(is_type_string(t));
  7349. lbValue ptr = lb_addr_get_ptr(p, string);
  7350. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  7351. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  7352. }
  7353. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  7354. Type *t = base_type(string.type);
  7355. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  7356. return lb_emit_struct_ev(p, string, 0);
  7357. }
  7358. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  7359. Type *t = base_type(string.type);
  7360. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  7361. return lb_emit_struct_ev(p, string, 1);
  7362. }
  7363. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  7364. GB_ASSERT(is_type_cstring(value.type));
  7365. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7366. args[0] = lb_emit_conv(p, value, t_cstring);
  7367. return lb_emit_runtime_call(p, "cstring_len", args);
  7368. }
  7369. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  7370. Type *t = type_deref(array_ptr.type);
  7371. GB_ASSERT(is_type_array(t));
  7372. return lb_emit_struct_ep(p, array_ptr, 0);
  7373. }
  7374. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  7375. GB_ASSERT(is_type_slice(slice.type));
  7376. return lb_emit_struct_ev(p, slice, 0);
  7377. }
  7378. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  7379. GB_ASSERT(is_type_slice(slice.type));
  7380. return lb_emit_struct_ev(p, slice, 1);
  7381. }
  7382. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  7383. GB_ASSERT(is_type_dynamic_array(da.type));
  7384. return lb_emit_struct_ev(p, da, 0);
  7385. }
  7386. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  7387. GB_ASSERT(is_type_dynamic_array(da.type));
  7388. return lb_emit_struct_ev(p, da, 1);
  7389. }
  7390. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  7391. GB_ASSERT(is_type_dynamic_array(da.type));
  7392. return lb_emit_struct_ev(p, da, 2);
  7393. }
  7394. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  7395. GB_ASSERT(is_type_dynamic_array(da.type));
  7396. return lb_emit_struct_ev(p, da, 3);
  7397. }
  7398. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  7399. Type *t = base_type(value.type);
  7400. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  7401. init_map_internal_types(t);
  7402. Type *gst = t->Map.generated_struct_type;
  7403. i32 index = 1;
  7404. lbValue entries = lb_emit_struct_ev(p, value, index);
  7405. return entries;
  7406. }
  7407. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  7408. Type *t = base_type(type_deref(value.type));
  7409. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  7410. init_map_internal_types(t);
  7411. Type *gst = t->Map.generated_struct_type;
  7412. i32 index = 1;
  7413. lbValue entries = lb_emit_struct_ep(p, value, index);
  7414. return entries;
  7415. }
  7416. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  7417. lbValue entries = lb_map_entries(p, value);
  7418. return lb_dynamic_array_len(p, entries);
  7419. }
  7420. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  7421. lbValue entries = lb_map_entries(p, value);
  7422. return lb_dynamic_array_cap(p, entries);
  7423. }
  7424. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  7425. Type *t = base_type(value.type);
  7426. bool is_ptr = false;
  7427. if (is_type_pointer(t)) {
  7428. is_ptr = true;
  7429. t = base_type(type_deref(t));
  7430. }
  7431. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7432. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  7433. }
  7434. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  7435. t->Struct.soa_kind == StructSoa_Dynamic);
  7436. isize n = 0;
  7437. Type *elem = base_type(t->Struct.soa_elem);
  7438. if (elem->kind == Type_Struct) {
  7439. n = elem->Struct.fields.count;
  7440. } else if (elem->kind == Type_Array) {
  7441. n = elem->Array.count;
  7442. } else {
  7443. GB_PANIC("Unreachable");
  7444. }
  7445. if (is_ptr) {
  7446. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  7447. return lb_emit_load(p, v);
  7448. }
  7449. return lb_emit_struct_ev(p, value, cast(i32)n);
  7450. }
  7451. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  7452. Type *t = base_type(value.type);
  7453. bool is_ptr = false;
  7454. if (is_type_pointer(t)) {
  7455. is_ptr = true;
  7456. t = base_type(type_deref(t));
  7457. }
  7458. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7459. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  7460. }
  7461. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  7462. isize n = 0;
  7463. Type *elem = base_type(t->Struct.soa_elem);
  7464. if (elem->kind == Type_Struct) {
  7465. n = elem->Struct.fields.count+1;
  7466. } else if (elem->kind == Type_Array) {
  7467. n = elem->Array.count+1;
  7468. } else {
  7469. GB_PANIC("Unreachable");
  7470. }
  7471. if (is_ptr) {
  7472. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  7473. return lb_emit_load(p, v);
  7474. }
  7475. return lb_emit_struct_ev(p, value, cast(i32)n);
  7476. }
  7477. lbValue lb_soa_zip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  7478. GB_ASSERT(ce->args.count > 0);
  7479. auto slices = slice_make<lbValue>(temporary_allocator(), ce->args.count);
  7480. for_array(i, slices) {
  7481. Ast *arg = ce->args[i];
  7482. if (arg->kind == Ast_FieldValue) {
  7483. arg = arg->FieldValue.value;
  7484. }
  7485. slices[i] = lb_build_expr(p, arg);
  7486. }
  7487. lbValue len = lb_slice_len(p, slices[0]);
  7488. for (isize i = 1; i < slices.count; i++) {
  7489. lbValue other_len = lb_slice_len(p, slices[i]);
  7490. len = lb_emit_min(p, t_int, len, other_len);
  7491. }
  7492. GB_ASSERT(is_type_soa_struct(tv.type));
  7493. lbAddr res = lb_add_local_generated(p, tv.type, true);
  7494. for_array(i, slices) {
  7495. lbValue src = lb_slice_elem(p, slices[i]);
  7496. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  7497. lb_emit_store(p, dst, src);
  7498. }
  7499. lbValue len_dst = lb_emit_struct_ep(p, res.addr, cast(i32)slices.count);
  7500. lb_emit_store(p, len_dst, len);
  7501. return lb_addr_load(p, res);
  7502. }
  7503. lbValue lb_soa_unzip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  7504. GB_ASSERT(ce->args.count == 1);
  7505. lbValue arg = lb_build_expr(p, ce->args[0]);
  7506. Type *t = base_type(arg.type);
  7507. GB_ASSERT(is_type_soa_struct(t) && t->Struct.soa_kind == StructSoa_Slice);
  7508. lbValue len = lb_soa_struct_len(p, arg);
  7509. lbAddr res = lb_add_local_generated(p, tv.type, true);
  7510. if (is_type_tuple(tv.type)) {
  7511. lbValue rp = lb_addr_get_ptr(p, res);
  7512. for (i32 i = 0; i < cast(i32)(t->Struct.fields.count-1); i++) {
  7513. lbValue ptr = lb_emit_struct_ev(p, arg, i);
  7514. lbAddr dst = lb_addr(lb_emit_struct_ep(p, rp, i));
  7515. lb_fill_slice(p, dst, ptr, len);
  7516. }
  7517. } else {
  7518. GB_ASSERT(is_type_slice(tv.type));
  7519. lbValue ptr = lb_emit_struct_ev(p, arg, 0);
  7520. lb_fill_slice(p, res, ptr, len);
  7521. }
  7522. return lb_addr_load(p, res);
  7523. }
  7524. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  7525. ast_node(ce, CallExpr, expr);
  7526. switch (id) {
  7527. case BuiltinProc_DIRECTIVE: {
  7528. ast_node(bd, BasicDirective, ce->proc);
  7529. String name = bd->name.string;
  7530. GB_ASSERT(name == "location");
  7531. String procedure = p->entity->token.string;
  7532. TokenPos pos = ast_token(ce->proc).pos;
  7533. if (ce->args.count > 0) {
  7534. Ast *ident = unselector_expr(ce->args[0]);
  7535. GB_ASSERT(ident->kind == Ast_Ident);
  7536. Entity *e = entity_of_node(ident);
  7537. GB_ASSERT(e != nullptr);
  7538. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  7539. procedure = e->parent_proc_decl->entity->token.string;
  7540. } else {
  7541. procedure = str_lit("");
  7542. }
  7543. pos = e->token.pos;
  7544. }
  7545. return lb_emit_source_code_location(p, procedure, pos);
  7546. }
  7547. case BuiltinProc_type_info_of: {
  7548. Ast *arg = ce->args[0];
  7549. TypeAndValue tav = type_and_value_of_expr(arg);
  7550. if (tav.mode == Addressing_Type) {
  7551. Type *t = default_type(type_of_expr(arg));
  7552. return lb_type_info(p->module, t);
  7553. }
  7554. GB_ASSERT(is_type_typeid(tav.type));
  7555. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7556. args[0] = lb_build_expr(p, arg);
  7557. return lb_emit_runtime_call(p, "__type_info_of", args);
  7558. }
  7559. case BuiltinProc_typeid_of: {
  7560. Ast *arg = ce->args[0];
  7561. TypeAndValue tav = type_and_value_of_expr(arg);
  7562. GB_ASSERT(tav.mode == Addressing_Type);
  7563. Type *t = default_type(type_of_expr(arg));
  7564. return lb_typeid(p->module, t);
  7565. }
  7566. case BuiltinProc_len: {
  7567. lbValue v = lb_build_expr(p, ce->args[0]);
  7568. Type *t = base_type(v.type);
  7569. if (is_type_pointer(t)) {
  7570. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  7571. v = lb_emit_load(p, v);
  7572. t = type_deref(t);
  7573. }
  7574. if (is_type_cstring(t)) {
  7575. return lb_cstring_len(p, v);
  7576. } else if (is_type_string(t)) {
  7577. return lb_string_len(p, v);
  7578. } else if (is_type_array(t)) {
  7579. GB_PANIC("Array lengths are constant");
  7580. } else if (is_type_slice(t)) {
  7581. return lb_slice_len(p, v);
  7582. } else if (is_type_dynamic_array(t)) {
  7583. return lb_dynamic_array_len(p, v);
  7584. } else if (is_type_map(t)) {
  7585. return lb_map_len(p, v);
  7586. } else if (is_type_soa_struct(t)) {
  7587. return lb_soa_struct_len(p, v);
  7588. }
  7589. GB_PANIC("Unreachable");
  7590. break;
  7591. }
  7592. case BuiltinProc_cap: {
  7593. lbValue v = lb_build_expr(p, ce->args[0]);
  7594. Type *t = base_type(v.type);
  7595. if (is_type_pointer(t)) {
  7596. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  7597. v = lb_emit_load(p, v);
  7598. t = type_deref(t);
  7599. }
  7600. if (is_type_string(t)) {
  7601. GB_PANIC("Unreachable");
  7602. } else if (is_type_array(t)) {
  7603. GB_PANIC("Array lengths are constant");
  7604. } else if (is_type_slice(t)) {
  7605. return lb_slice_len(p, v);
  7606. } else if (is_type_dynamic_array(t)) {
  7607. return lb_dynamic_array_cap(p, v);
  7608. } else if (is_type_map(t)) {
  7609. return lb_map_cap(p, v);
  7610. } else if (is_type_soa_struct(t)) {
  7611. return lb_soa_struct_cap(p, v);
  7612. }
  7613. GB_PANIC("Unreachable");
  7614. break;
  7615. }
  7616. case BuiltinProc_swizzle: {
  7617. isize index_count = ce->args.count-1;
  7618. if (is_type_simd_vector(tv.type)) {
  7619. lbValue vec = lb_build_expr(p, ce->args[0]);
  7620. if (index_count == 0) {
  7621. return vec;
  7622. }
  7623. unsigned mask_len = cast(unsigned)index_count;
  7624. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  7625. for (isize i = 1; i < ce->args.count; i++) {
  7626. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  7627. GB_ASSERT(is_type_integer(tv.type));
  7628. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  7629. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  7630. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  7631. }
  7632. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  7633. LLVMValueRef v1 = vec.value;
  7634. LLVMValueRef v2 = vec.value;
  7635. lbValue res = {};
  7636. res.type = tv.type;
  7637. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  7638. return res;
  7639. }
  7640. lbAddr addr = lb_build_addr(p, ce->args[0]);
  7641. if (index_count == 0) {
  7642. return lb_addr_load(p, addr);
  7643. }
  7644. lbValue src = lb_addr_get_ptr(p, addr);
  7645. // TODO(bill): Should this be zeroed or not?
  7646. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  7647. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  7648. for (i32 i = 1; i < ce->args.count; i++) {
  7649. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  7650. GB_ASSERT(is_type_integer(tv.type));
  7651. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  7652. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  7653. i32 dst_index = i-1;
  7654. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  7655. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  7656. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  7657. }
  7658. return lb_addr_load(p, dst);
  7659. }
  7660. case BuiltinProc_complex: {
  7661. lbValue real = lb_build_expr(p, ce->args[0]);
  7662. lbValue imag = lb_build_expr(p, ce->args[1]);
  7663. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  7664. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  7665. Type *ft = base_complex_elem_type(tv.type);
  7666. real = lb_emit_conv(p, real, ft);
  7667. imag = lb_emit_conv(p, imag, ft);
  7668. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  7669. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  7670. return lb_emit_load(p, dst);
  7671. }
  7672. case BuiltinProc_quaternion: {
  7673. lbValue real = lb_build_expr(p, ce->args[0]);
  7674. lbValue imag = lb_build_expr(p, ce->args[1]);
  7675. lbValue jmag = lb_build_expr(p, ce->args[2]);
  7676. lbValue kmag = lb_build_expr(p, ce->args[3]);
  7677. // @QuaternionLayout
  7678. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  7679. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  7680. Type *ft = base_complex_elem_type(tv.type);
  7681. real = lb_emit_conv(p, real, ft);
  7682. imag = lb_emit_conv(p, imag, ft);
  7683. jmag = lb_emit_conv(p, jmag, ft);
  7684. kmag = lb_emit_conv(p, kmag, ft);
  7685. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  7686. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  7687. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  7688. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  7689. return lb_emit_load(p, dst);
  7690. }
  7691. case BuiltinProc_real: {
  7692. lbValue val = lb_build_expr(p, ce->args[0]);
  7693. if (is_type_complex(val.type)) {
  7694. lbValue real = lb_emit_struct_ev(p, val, 0);
  7695. return lb_emit_conv(p, real, tv.type);
  7696. } else if (is_type_quaternion(val.type)) {
  7697. // @QuaternionLayout
  7698. lbValue real = lb_emit_struct_ev(p, val, 3);
  7699. return lb_emit_conv(p, real, tv.type);
  7700. }
  7701. GB_PANIC("invalid type for real");
  7702. return {};
  7703. }
  7704. case BuiltinProc_imag: {
  7705. lbValue val = lb_build_expr(p, ce->args[0]);
  7706. if (is_type_complex(val.type)) {
  7707. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7708. return lb_emit_conv(p, imag, tv.type);
  7709. } else if (is_type_quaternion(val.type)) {
  7710. // @QuaternionLayout
  7711. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7712. return lb_emit_conv(p, imag, tv.type);
  7713. }
  7714. GB_PANIC("invalid type for imag");
  7715. return {};
  7716. }
  7717. case BuiltinProc_jmag: {
  7718. lbValue val = lb_build_expr(p, ce->args[0]);
  7719. if (is_type_quaternion(val.type)) {
  7720. // @QuaternionLayout
  7721. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7722. return lb_emit_conv(p, imag, tv.type);
  7723. }
  7724. GB_PANIC("invalid type for jmag");
  7725. return {};
  7726. }
  7727. case BuiltinProc_kmag: {
  7728. lbValue val = lb_build_expr(p, ce->args[0]);
  7729. if (is_type_quaternion(val.type)) {
  7730. // @QuaternionLayout
  7731. lbValue imag = lb_emit_struct_ev(p, val, 2);
  7732. return lb_emit_conv(p, imag, tv.type);
  7733. }
  7734. GB_PANIC("invalid type for kmag");
  7735. return {};
  7736. }
  7737. case BuiltinProc_conj: {
  7738. lbValue val = lb_build_expr(p, ce->args[0]);
  7739. lbValue res = {};
  7740. Type *t = val.type;
  7741. if (is_type_complex(t)) {
  7742. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7743. lbValue real = lb_emit_struct_ev(p, val, 0);
  7744. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7745. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7746. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  7747. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  7748. } else if (is_type_quaternion(t)) {
  7749. // @QuaternionLayout
  7750. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7751. lbValue real = lb_emit_struct_ev(p, val, 3);
  7752. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7753. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  7754. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  7755. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7756. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  7757. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  7758. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  7759. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  7760. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  7761. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  7762. }
  7763. return lb_emit_load(p, res);
  7764. }
  7765. case BuiltinProc_expand_to_tuple: {
  7766. lbValue val = lb_build_expr(p, ce->args[0]);
  7767. Type *t = base_type(val.type);
  7768. if (!is_type_tuple(tv.type)) {
  7769. if (t->kind == Type_Struct) {
  7770. GB_ASSERT(t->Struct.fields.count == 1);
  7771. return lb_emit_struct_ev(p, val, 0);
  7772. } else if (t->kind == Type_Array) {
  7773. GB_ASSERT(t->Array.count == 1);
  7774. return lb_emit_array_epi(p, val, 0);
  7775. } else {
  7776. GB_PANIC("Unknown type of expand_to_tuple");
  7777. }
  7778. }
  7779. GB_ASSERT(is_type_tuple(tv.type));
  7780. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  7781. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7782. if (t->kind == Type_Struct) {
  7783. for_array(src_index, t->Struct.fields) {
  7784. Entity *field = t->Struct.fields[src_index];
  7785. i32 field_index = field->Variable.field_index;
  7786. lbValue f = lb_emit_struct_ev(p, val, field_index);
  7787. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  7788. lb_emit_store(p, ep, f);
  7789. }
  7790. } else if (t->kind == Type_Array) {
  7791. // TODO(bill): Clean-up this code
  7792. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  7793. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  7794. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  7795. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  7796. lb_emit_store(p, ep, f);
  7797. }
  7798. } else {
  7799. GB_PANIC("Unknown type of expand_to_tuple");
  7800. }
  7801. return lb_emit_load(p, tuple);
  7802. }
  7803. case BuiltinProc_min: {
  7804. Type *t = type_of_expr(expr);
  7805. if (ce->args.count == 2) {
  7806. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  7807. } else {
  7808. lbValue x = lb_build_expr(p, ce->args[0]);
  7809. for (isize i = 1; i < ce->args.count; i++) {
  7810. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  7811. }
  7812. return x;
  7813. }
  7814. }
  7815. case BuiltinProc_max: {
  7816. Type *t = type_of_expr(expr);
  7817. if (ce->args.count == 2) {
  7818. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  7819. } else {
  7820. lbValue x = lb_build_expr(p, ce->args[0]);
  7821. for (isize i = 1; i < ce->args.count; i++) {
  7822. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  7823. }
  7824. return x;
  7825. }
  7826. }
  7827. case BuiltinProc_abs: {
  7828. lbValue x = lb_build_expr(p, ce->args[0]);
  7829. Type *t = x.type;
  7830. if (is_type_unsigned(t)) {
  7831. return x;
  7832. }
  7833. if (is_type_quaternion(t)) {
  7834. i64 sz = 8*type_size_of(t);
  7835. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7836. args[0] = x;
  7837. switch (sz) {
  7838. case 64: return lb_emit_runtime_call(p, "abs_quaternion64", args);
  7839. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  7840. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  7841. }
  7842. GB_PANIC("Unknown complex type");
  7843. } else if (is_type_complex(t)) {
  7844. i64 sz = 8*type_size_of(t);
  7845. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7846. args[0] = x;
  7847. switch (sz) {
  7848. case 32: return lb_emit_runtime_call(p, "abs_complex32", args);
  7849. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  7850. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  7851. }
  7852. GB_PANIC("Unknown complex type");
  7853. } else if (is_type_float(t)) {
  7854. i64 sz = 8*type_size_of(t);
  7855. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7856. args[0] = x;
  7857. switch (sz) {
  7858. case 16: return lb_emit_runtime_call(p, "abs_f16", args);
  7859. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  7860. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  7861. }
  7862. GB_PANIC("Unknown float type");
  7863. }
  7864. lbValue zero = lb_const_nil(p->module, t);
  7865. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  7866. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  7867. return lb_emit_select(p, cond, neg, x);
  7868. }
  7869. case BuiltinProc_clamp:
  7870. return lb_emit_clamp(p, type_of_expr(expr),
  7871. lb_build_expr(p, ce->args[0]),
  7872. lb_build_expr(p, ce->args[1]),
  7873. lb_build_expr(p, ce->args[2]));
  7874. case BuiltinProc_soa_zip:
  7875. return lb_soa_zip(p, ce, tv);
  7876. case BuiltinProc_soa_unzip:
  7877. return lb_soa_unzip(p, ce, tv);
  7878. // "Intrinsics"
  7879. case BuiltinProc_alloca:
  7880. {
  7881. lbValue sz = lb_build_expr(p, ce->args[0]);
  7882. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  7883. lbValue res = {};
  7884. res.type = t_u8_ptr;
  7885. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  7886. LLVMSetAlignment(res.value, cast(unsigned)al);
  7887. return res;
  7888. }
  7889. case BuiltinProc_cpu_relax:
  7890. if (build_context.metrics.arch == TargetArch_386 ||
  7891. build_context.metrics.arch == TargetArch_amd64) {
  7892. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  7893. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  7894. cast(char *)"pause", 5,
  7895. cast(char *)"", 0,
  7896. /*HasSideEffects*/true, /*IsAlignStack*/false,
  7897. LLVMInlineAsmDialectATT
  7898. );
  7899. GB_ASSERT(the_asm != nullptr);
  7900. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  7901. } else if (build_context.metrics.arch == TargetArch_arm64) {
  7902. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  7903. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  7904. cast(char *)"yield", 5,
  7905. cast(char *)"", 0,
  7906. /*HasSideEffects*/true, /*IsAlignStack*/false,
  7907. LLVMInlineAsmDialectATT
  7908. );
  7909. GB_ASSERT(the_asm != nullptr);
  7910. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  7911. }
  7912. return {};
  7913. case BuiltinProc_debug_trap:
  7914. case BuiltinProc_trap:
  7915. {
  7916. char const *name = nullptr;
  7917. switch (id) {
  7918. case BuiltinProc_debug_trap: name = "llvm.debugtrap"; break;
  7919. case BuiltinProc_trap: name = "llvm.trap"; break;
  7920. }
  7921. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  7922. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  7923. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, nullptr, 0);
  7924. LLVMBuildCall(p->builder, ip, nullptr, 0, "");
  7925. if (id == BuiltinProc_trap) {
  7926. LLVMBuildUnreachable(p->builder);
  7927. }
  7928. return {};
  7929. }
  7930. case BuiltinProc_read_cycle_counter:
  7931. {
  7932. char const *name = "llvm.readcyclecounter";
  7933. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  7934. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  7935. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, nullptr, 0);
  7936. lbValue res = {};
  7937. res.value = LLVMBuildCall(p->builder, ip, nullptr, 0, "");
  7938. res.type = tv.type;
  7939. return res;
  7940. }
  7941. case BuiltinProc_count_trailing_zeros:
  7942. return lb_emit_count_trailing_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  7943. case BuiltinProc_count_leading_zeros:
  7944. return lb_emit_count_leading_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  7945. case BuiltinProc_count_ones:
  7946. return lb_emit_count_ones(p, lb_build_expr(p, ce->args[0]), tv.type);
  7947. case BuiltinProc_count_zeros:
  7948. return lb_emit_count_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  7949. case BuiltinProc_reverse_bits:
  7950. return lb_emit_reverse_bits(p, lb_build_expr(p, ce->args[0]), tv.type);
  7951. case BuiltinProc_byte_swap:
  7952. {
  7953. lbValue x = lb_build_expr(p, ce->args[0]);
  7954. x = lb_emit_conv(p, x, tv.type);
  7955. return lb_emit_byte_swap(p, x, tv.type);
  7956. }
  7957. case BuiltinProc_overflow_add:
  7958. case BuiltinProc_overflow_sub:
  7959. case BuiltinProc_overflow_mul:
  7960. {
  7961. Type *main_type = tv.type;
  7962. Type *type = main_type;
  7963. if (is_type_tuple(main_type)) {
  7964. type = main_type->Tuple.variables[0]->type;
  7965. }
  7966. lbValue x = lb_build_expr(p, ce->args[0]);
  7967. lbValue y = lb_build_expr(p, ce->args[1]);
  7968. x = lb_emit_conv(p, x, type);
  7969. y = lb_emit_conv(p, y, type);
  7970. char const *name = nullptr;
  7971. if (is_type_unsigned(type)) {
  7972. switch (id) {
  7973. case BuiltinProc_overflow_add: name = "llvm.uadd.with.overflow"; break;
  7974. case BuiltinProc_overflow_sub: name = "llvm.usub.with.overflow"; break;
  7975. case BuiltinProc_overflow_mul: name = "llvm.umul.with.overflow"; break;
  7976. }
  7977. } else {
  7978. switch (id) {
  7979. case BuiltinProc_overflow_add: name = "llvm.sadd.with.overflow"; break;
  7980. case BuiltinProc_overflow_sub: name = "llvm.ssub.with.overflow"; break;
  7981. case BuiltinProc_overflow_mul: name = "llvm.smul.with.overflow"; break;
  7982. }
  7983. }
  7984. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  7985. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  7986. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  7987. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  7988. LLVMValueRef args[2] = {};
  7989. args[0] = x.value;
  7990. args[1] = y.value;
  7991. lbValue res = {};
  7992. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  7993. if (is_type_tuple(main_type)) {
  7994. Type *res_type = nullptr;
  7995. gbAllocator a = permanent_allocator();
  7996. res_type = alloc_type_tuple();
  7997. array_init(&res_type->Tuple.variables, a, 2);
  7998. res_type->Tuple.variables[0] = alloc_entity_field(nullptr, blank_token, type, false, 0);
  7999. res_type->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  8000. res.type = res_type;
  8001. } else {
  8002. res.value = LLVMBuildExtractValue(p->builder, res.value, 0, "");
  8003. res.type = type;
  8004. }
  8005. return res;
  8006. }
  8007. case BuiltinProc_sqrt:
  8008. {
  8009. Type *type = tv.type;
  8010. lbValue x = lb_build_expr(p, ce->args[0]);
  8011. x = lb_emit_conv(p, x, type);
  8012. char const *name = "llvm.sqrt";
  8013. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8014. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8015. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8016. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8017. LLVMValueRef args[1] = {};
  8018. args[0] = x.value;
  8019. lbValue res = {};
  8020. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8021. res.type = type;
  8022. return res;
  8023. }
  8024. case BuiltinProc_mem_copy:
  8025. case BuiltinProc_mem_copy_non_overlapping:
  8026. {
  8027. lbValue dst = lb_build_expr(p, ce->args[0]);
  8028. lbValue src = lb_build_expr(p, ce->args[1]);
  8029. lbValue len = lb_build_expr(p, ce->args[2]);
  8030. dst = lb_emit_conv(p, dst, t_rawptr);
  8031. src = lb_emit_conv(p, src, t_rawptr);
  8032. len = lb_emit_conv(p, len, t_int);
  8033. bool is_inlinable = false;
  8034. if (ce->args[2]->tav.mode == Addressing_Constant) {
  8035. ExactValue ev = exact_value_to_integer(ce->args[2]->tav.value);
  8036. i64 const_len = exact_value_to_i64(ev);
  8037. // TODO(bill): Determine when it is better to do the `*.inline` versions
  8038. if (const_len <= 4*build_context.word_size) {
  8039. is_inlinable = true;
  8040. }
  8041. }
  8042. char const *name = nullptr;
  8043. switch (id) {
  8044. case BuiltinProc_mem_copy:
  8045. if (is_inlinable) {
  8046. name = "llvm.memmove.inline";
  8047. } else {
  8048. name = "llvm.memmove";
  8049. }
  8050. break;
  8051. case BuiltinProc_mem_copy_non_overlapping:
  8052. if (is_inlinable) {
  8053. name = "llvm.memcpy.line";
  8054. } else {
  8055. name = "llvm.memcpy";
  8056. }
  8057. break;
  8058. }
  8059. LLVMTypeRef types[3] = {
  8060. lb_type(p->module, t_rawptr),
  8061. lb_type(p->module, t_rawptr),
  8062. lb_type(p->module, t_int)
  8063. };
  8064. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8065. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s.%s.%s", name, LLVMPrintTypeToString(types[0]), LLVMPrintTypeToString(types[1]), LLVMPrintTypeToString(types[2]));
  8066. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8067. LLVMValueRef args[4] = {};
  8068. args[0] = dst.value;
  8069. args[1] = src.value;
  8070. args[2] = len.value;
  8071. args[3] = LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, false); // is_volatile parameter
  8072. LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8073. return {};
  8074. }
  8075. case BuiltinProc_mem_zero:
  8076. {
  8077. lbValue ptr = lb_build_expr(p, ce->args[0]);
  8078. lbValue len = lb_build_expr(p, ce->args[1]);
  8079. ptr = lb_emit_conv(p, ptr, t_rawptr);
  8080. len = lb_emit_conv(p, len, t_int);
  8081. unsigned alignment = 1;
  8082. lb_mem_zero_ptr_internal(p, ptr.value, len.value, alignment);
  8083. return {};
  8084. }
  8085. case BuiltinProc_ptr_offset:
  8086. {
  8087. lbValue ptr = lb_build_expr(p, ce->args[0]);
  8088. lbValue len = lb_build_expr(p, ce->args[1]);
  8089. len = lb_emit_conv(p, len, t_int);
  8090. LLVMValueRef indices[1] = {
  8091. len.value,
  8092. };
  8093. lbValue res = {};
  8094. res.type = tv.type;
  8095. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, gb_count_of(indices), "");
  8096. return res;
  8097. }
  8098. case BuiltinProc_ptr_sub:
  8099. {
  8100. lbValue ptr0 = lb_build_expr(p, ce->args[0]);
  8101. lbValue ptr1 = lb_build_expr(p, ce->args[1]);
  8102. LLVMTypeRef type_int = lb_type(p->module, t_int);
  8103. LLVMValueRef diff = LLVMBuildPtrDiff(p->builder, ptr0.value, ptr1.value, "");
  8104. diff = LLVMBuildIntCast2(p->builder, diff, type_int, /*signed*/true, "");
  8105. lbValue res = {};
  8106. res.type = t_int;
  8107. res.value = diff;
  8108. return res;
  8109. }
  8110. case BuiltinProc_atomic_fence:
  8111. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  8112. return {};
  8113. case BuiltinProc_atomic_fence_acq:
  8114. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  8115. return {};
  8116. case BuiltinProc_atomic_fence_rel:
  8117. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  8118. return {};
  8119. case BuiltinProc_atomic_fence_acqrel:
  8120. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  8121. return {};
  8122. case BuiltinProc_volatile_store:
  8123. case BuiltinProc_atomic_store:
  8124. case BuiltinProc_atomic_store_rel:
  8125. case BuiltinProc_atomic_store_relaxed:
  8126. case BuiltinProc_atomic_store_unordered: {
  8127. lbValue dst = lb_build_expr(p, ce->args[0]);
  8128. lbValue val = lb_build_expr(p, ce->args[1]);
  8129. val = lb_emit_conv(p, val, type_deref(dst.type));
  8130. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  8131. switch (id) {
  8132. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  8133. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  8134. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  8135. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  8136. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  8137. }
  8138. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  8139. return {};
  8140. }
  8141. case BuiltinProc_volatile_load:
  8142. case BuiltinProc_atomic_load:
  8143. case BuiltinProc_atomic_load_acq:
  8144. case BuiltinProc_atomic_load_relaxed:
  8145. case BuiltinProc_atomic_load_unordered: {
  8146. lbValue dst = lb_build_expr(p, ce->args[0]);
  8147. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  8148. switch (id) {
  8149. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  8150. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  8151. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  8152. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  8153. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  8154. }
  8155. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  8156. lbValue res = {};
  8157. res.value = instr;
  8158. res.type = type_deref(dst.type);
  8159. return res;
  8160. }
  8161. case BuiltinProc_atomic_add:
  8162. case BuiltinProc_atomic_add_acq:
  8163. case BuiltinProc_atomic_add_rel:
  8164. case BuiltinProc_atomic_add_acqrel:
  8165. case BuiltinProc_atomic_add_relaxed:
  8166. case BuiltinProc_atomic_sub:
  8167. case BuiltinProc_atomic_sub_acq:
  8168. case BuiltinProc_atomic_sub_rel:
  8169. case BuiltinProc_atomic_sub_acqrel:
  8170. case BuiltinProc_atomic_sub_relaxed:
  8171. case BuiltinProc_atomic_and:
  8172. case BuiltinProc_atomic_and_acq:
  8173. case BuiltinProc_atomic_and_rel:
  8174. case BuiltinProc_atomic_and_acqrel:
  8175. case BuiltinProc_atomic_and_relaxed:
  8176. case BuiltinProc_atomic_nand:
  8177. case BuiltinProc_atomic_nand_acq:
  8178. case BuiltinProc_atomic_nand_rel:
  8179. case BuiltinProc_atomic_nand_acqrel:
  8180. case BuiltinProc_atomic_nand_relaxed:
  8181. case BuiltinProc_atomic_or:
  8182. case BuiltinProc_atomic_or_acq:
  8183. case BuiltinProc_atomic_or_rel:
  8184. case BuiltinProc_atomic_or_acqrel:
  8185. case BuiltinProc_atomic_or_relaxed:
  8186. case BuiltinProc_atomic_xor:
  8187. case BuiltinProc_atomic_xor_acq:
  8188. case BuiltinProc_atomic_xor_rel:
  8189. case BuiltinProc_atomic_xor_acqrel:
  8190. case BuiltinProc_atomic_xor_relaxed:
  8191. case BuiltinProc_atomic_xchg:
  8192. case BuiltinProc_atomic_xchg_acq:
  8193. case BuiltinProc_atomic_xchg_rel:
  8194. case BuiltinProc_atomic_xchg_acqrel:
  8195. case BuiltinProc_atomic_xchg_relaxed: {
  8196. lbValue dst = lb_build_expr(p, ce->args[0]);
  8197. lbValue val = lb_build_expr(p, ce->args[1]);
  8198. val = lb_emit_conv(p, val, type_deref(dst.type));
  8199. LLVMAtomicRMWBinOp op = {};
  8200. LLVMAtomicOrdering ordering = {};
  8201. switch (id) {
  8202. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8203. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  8204. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  8205. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8206. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  8207. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8208. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  8209. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  8210. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8211. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  8212. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8213. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  8214. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  8215. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8216. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  8217. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8218. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  8219. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  8220. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8221. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  8222. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8223. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  8224. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  8225. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8226. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  8227. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8228. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  8229. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  8230. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8231. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  8232. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8233. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  8234. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  8235. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8236. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  8237. }
  8238. lbValue res = {};
  8239. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  8240. res.type = tv.type;
  8241. return res;
  8242. }
  8243. case BuiltinProc_atomic_cxchg:
  8244. case BuiltinProc_atomic_cxchg_acq:
  8245. case BuiltinProc_atomic_cxchg_rel:
  8246. case BuiltinProc_atomic_cxchg_acqrel:
  8247. case BuiltinProc_atomic_cxchg_relaxed:
  8248. case BuiltinProc_atomic_cxchg_failrelaxed:
  8249. case BuiltinProc_atomic_cxchg_failacq:
  8250. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  8251. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  8252. case BuiltinProc_atomic_cxchgweak:
  8253. case BuiltinProc_atomic_cxchgweak_acq:
  8254. case BuiltinProc_atomic_cxchgweak_rel:
  8255. case BuiltinProc_atomic_cxchgweak_acqrel:
  8256. case BuiltinProc_atomic_cxchgweak_relaxed:
  8257. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  8258. case BuiltinProc_atomic_cxchgweak_failacq:
  8259. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  8260. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  8261. Type *type = expr->tav.type;
  8262. lbValue address = lb_build_expr(p, ce->args[0]);
  8263. Type *elem = type_deref(address.type);
  8264. lbValue old_value = lb_build_expr(p, ce->args[1]);
  8265. lbValue new_value = lb_build_expr(p, ce->args[2]);
  8266. old_value = lb_emit_conv(p, old_value, elem);
  8267. new_value = lb_emit_conv(p, new_value, elem);
  8268. LLVMAtomicOrdering success_ordering = {};
  8269. LLVMAtomicOrdering failure_ordering = {};
  8270. LLVMBool weak = false;
  8271. switch (id) {
  8272. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8273. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8274. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8275. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8276. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  8277. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  8278. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  8279. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  8280. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  8281. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8282. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  8283. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  8284. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  8285. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  8286. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  8287. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  8288. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  8289. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  8290. }
  8291. // TODO(bill): Figure out how to make it weak
  8292. LLVMBool single_threaded = weak;
  8293. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  8294. p->builder, address.value,
  8295. old_value.value, new_value.value,
  8296. success_ordering,
  8297. failure_ordering,
  8298. single_threaded
  8299. );
  8300. if (tv.type->kind == Type_Tuple) {
  8301. Type *fix_typed = alloc_type_tuple();
  8302. array_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  8303. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  8304. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  8305. lbValue res = {};
  8306. res.value = value;
  8307. res.type = fix_typed;
  8308. return res;
  8309. } else {
  8310. lbValue res = {};
  8311. res.value = LLVMBuildExtractValue(p->builder, value, 0, "");
  8312. res.type = tv.type;
  8313. return res;
  8314. }
  8315. }
  8316. case BuiltinProc_type_equal_proc:
  8317. return lb_get_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  8318. case BuiltinProc_type_hasher_proc:
  8319. return lb_get_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  8320. case BuiltinProc_fixed_point_mul:
  8321. case BuiltinProc_fixed_point_div:
  8322. case BuiltinProc_fixed_point_mul_sat:
  8323. case BuiltinProc_fixed_point_div_sat:
  8324. {
  8325. bool do_bswap = is_type_different_to_arch_endianness(tv.type);
  8326. Type *platform_type = integer_endian_type_to_platform_type(tv.type);
  8327. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), platform_type);
  8328. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), platform_type);
  8329. lbValue scale = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), platform_type);
  8330. char const *name = nullptr;
  8331. if (is_type_unsigned(tv.type)) {
  8332. switch (id) {
  8333. case BuiltinProc_fixed_point_mul: name = "llvm.umul.fix"; break;
  8334. case BuiltinProc_fixed_point_div: name = "llvm.udiv.fix"; break;
  8335. case BuiltinProc_fixed_point_mul_sat: name = "llvm.umul.fix.sat"; break;
  8336. case BuiltinProc_fixed_point_div_sat: name = "llvm.udiv.fix.sat"; break;
  8337. }
  8338. } else {
  8339. switch (id) {
  8340. case BuiltinProc_fixed_point_mul: name = "llvm.smul.fix"; break;
  8341. case BuiltinProc_fixed_point_div: name = "llvm.sdiv.fix"; break;
  8342. case BuiltinProc_fixed_point_mul_sat: name = "llvm.smul.fix.sat"; break;
  8343. case BuiltinProc_fixed_point_div_sat: name = "llvm.sdiv.fix.sat"; break;
  8344. }
  8345. }
  8346. GB_ASSERT(name != nullptr);
  8347. LLVMTypeRef types[1] = {lb_type(p->module, platform_type)};
  8348. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8349. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8350. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8351. lbValue res = {};
  8352. LLVMValueRef args[3] = {};
  8353. args[0] = x.value;
  8354. args[1] = y.value;
  8355. args[2] = scale.value;
  8356. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8357. res.type = platform_type;
  8358. return lb_emit_conv(p, res, tv.type);
  8359. }
  8360. case BuiltinProc_expect:
  8361. {
  8362. Type *t = default_type(tv.type);
  8363. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t);
  8364. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t);
  8365. char const *name = "llvm.expect";
  8366. LLVMTypeRef types[1] = {lb_type(p->module, t)};
  8367. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8368. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8369. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8370. lbValue res = {};
  8371. LLVMValueRef args[2] = {};
  8372. args[0] = x.value;
  8373. args[1] = y.value;
  8374. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8375. res.type = t;
  8376. return lb_emit_conv(p, res, t);
  8377. }
  8378. }
  8379. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  8380. return {};
  8381. }
  8382. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  8383. switch (param_value.kind) {
  8384. case ParameterValue_Constant:
  8385. if (is_type_constant_type(parameter_type)) {
  8386. auto res = lb_const_value(p->module, parameter_type, param_value.value);
  8387. return res;
  8388. } else {
  8389. ExactValue ev = param_value.value;
  8390. lbValue arg = {};
  8391. Type *type = type_of_expr(param_value.original_ast_expr);
  8392. if (type != nullptr) {
  8393. arg = lb_const_value(p->module, type, ev);
  8394. } else {
  8395. arg = lb_const_value(p->module, parameter_type, param_value.value);
  8396. }
  8397. return lb_emit_conv(p, arg, parameter_type);
  8398. }
  8399. case ParameterValue_Nil:
  8400. return lb_const_nil(p->module, parameter_type);
  8401. case ParameterValue_Location:
  8402. {
  8403. String proc_name = {};
  8404. if (p->entity != nullptr) {
  8405. proc_name = p->entity->token.string;
  8406. }
  8407. return lb_emit_source_code_location(p, proc_name, pos);
  8408. }
  8409. case ParameterValue_Value:
  8410. return lb_build_expr(p, param_value.ast_value);
  8411. }
  8412. return lb_const_nil(p->module, parameter_type);
  8413. }
  8414. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  8415. lbModule *m = p->module;
  8416. TypeAndValue tv = type_and_value_of_expr(expr);
  8417. ast_node(ce, CallExpr, expr);
  8418. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  8419. AddressingMode proc_mode = proc_tv.mode;
  8420. if (proc_mode == Addressing_Type) {
  8421. GB_ASSERT(ce->args.count == 1);
  8422. lbValue x = lb_build_expr(p, ce->args[0]);
  8423. lbValue y = lb_emit_conv(p, x, tv.type);
  8424. return y;
  8425. }
  8426. Ast *pexpr = unparen_expr(ce->proc);
  8427. if (proc_mode == Addressing_Builtin) {
  8428. Entity *e = entity_of_node(pexpr);
  8429. BuiltinProcId id = BuiltinProc_Invalid;
  8430. if (e != nullptr) {
  8431. id = cast(BuiltinProcId)e->Builtin.id;
  8432. } else {
  8433. id = BuiltinProc_DIRECTIVE;
  8434. }
  8435. return lb_build_builtin_proc(p, expr, tv, id);
  8436. }
  8437. // NOTE(bill): Regular call
  8438. lbValue value = {};
  8439. Ast *proc_expr = unparen_expr(ce->proc);
  8440. if (proc_expr->tav.mode == Addressing_Constant) {
  8441. ExactValue v = proc_expr->tav.value;
  8442. switch (v.kind) {
  8443. case ExactValue_Integer:
  8444. {
  8445. u64 u = big_int_to_u64(&v.value_integer);
  8446. lbValue x = {};
  8447. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  8448. x.type = t_uintptr;
  8449. x = lb_emit_conv(p, x, t_rawptr);
  8450. value = lb_emit_conv(p, x, proc_expr->tav.type);
  8451. break;
  8452. }
  8453. case ExactValue_Pointer:
  8454. {
  8455. u64 u = cast(u64)v.value_pointer;
  8456. lbValue x = {};
  8457. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  8458. x.type = t_uintptr;
  8459. x = lb_emit_conv(p, x, t_rawptr);
  8460. value = lb_emit_conv(p, x, proc_expr->tav.type);
  8461. break;
  8462. }
  8463. }
  8464. }
  8465. Entity *proc_entity = entity_of_node(proc_expr);
  8466. if (proc_entity != nullptr) {
  8467. if (proc_entity->flags & EntityFlag_Disabled) {
  8468. return {};
  8469. }
  8470. }
  8471. if (value.value == nullptr) {
  8472. value = lb_build_expr(p, proc_expr);
  8473. }
  8474. GB_ASSERT(value.value != nullptr);
  8475. Type *proc_type_ = base_type(value.type);
  8476. GB_ASSERT(proc_type_->kind == Type_Proc);
  8477. TypeProc *pt = &proc_type_->Proc;
  8478. if (is_call_expr_field_value(ce)) {
  8479. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  8480. for_array(arg_index, ce->args) {
  8481. Ast *arg = ce->args[arg_index];
  8482. ast_node(fv, FieldValue, arg);
  8483. GB_ASSERT(fv->field->kind == Ast_Ident);
  8484. String name = fv->field->Ident.token.string;
  8485. isize index = lookup_procedure_parameter(pt, name);
  8486. GB_ASSERT(index >= 0);
  8487. TypeAndValue tav = type_and_value_of_expr(fv->value);
  8488. if (tav.mode == Addressing_Type) {
  8489. args[index] = lb_const_nil(m, tav.type);
  8490. } else {
  8491. args[index] = lb_build_expr(p, fv->value);
  8492. }
  8493. }
  8494. TypeTuple *params = &pt->params->Tuple;
  8495. for (isize i = 0; i < args.count; i++) {
  8496. Entity *e = params->variables[i];
  8497. if (e->kind == Entity_TypeName) {
  8498. args[i] = lb_const_nil(m, e->type);
  8499. } else if (e->kind == Entity_Constant) {
  8500. continue;
  8501. } else {
  8502. GB_ASSERT(e->kind == Entity_Variable);
  8503. if (args[i].value == nullptr) {
  8504. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  8505. } else {
  8506. args[i] = lb_emit_conv(p, args[i], e->type);
  8507. }
  8508. }
  8509. }
  8510. for (isize i = 0; i < args.count; i++) {
  8511. Entity *e = params->variables[i];
  8512. if (args[i].type == nullptr) {
  8513. continue;
  8514. } else if (is_type_untyped_nil(args[i].type)) {
  8515. args[i] = lb_const_nil(m, e->type);
  8516. } else if (is_type_untyped_undef(args[i].type)) {
  8517. args[i] = lb_const_undef(m, e->type);
  8518. }
  8519. }
  8520. return lb_emit_call(p, value, args, ce->inlining, p->copy_elision_hint.ast == expr);
  8521. }
  8522. isize arg_index = 0;
  8523. isize arg_count = 0;
  8524. for_array(i, ce->args) {
  8525. Ast *arg = ce->args[i];
  8526. TypeAndValue tav = type_and_value_of_expr(arg);
  8527. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  8528. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  8529. Type *at = tav.type;
  8530. if (at->kind == Type_Tuple) {
  8531. arg_count += at->Tuple.variables.count;
  8532. } else {
  8533. arg_count++;
  8534. }
  8535. }
  8536. isize param_count = 0;
  8537. if (pt->params) {
  8538. GB_ASSERT(pt->params->kind == Type_Tuple);
  8539. param_count = pt->params->Tuple.variables.count;
  8540. }
  8541. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  8542. isize variadic_index = pt->variadic_index;
  8543. bool variadic = pt->variadic && variadic_index >= 0;
  8544. bool vari_expand = ce->ellipsis.pos.line != 0;
  8545. bool is_c_vararg = pt->c_vararg;
  8546. String proc_name = {};
  8547. if (p->entity != nullptr) {
  8548. proc_name = p->entity->token.string;
  8549. }
  8550. TokenPos pos = ast_token(ce->proc).pos;
  8551. TypeTuple *param_tuple = nullptr;
  8552. if (pt->params) {
  8553. GB_ASSERT(pt->params->kind == Type_Tuple);
  8554. param_tuple = &pt->params->Tuple;
  8555. }
  8556. for_array(i, ce->args) {
  8557. Ast *arg = ce->args[i];
  8558. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  8559. if (arg_tv.mode == Addressing_Type) {
  8560. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  8561. } else {
  8562. lbValue a = lb_build_expr(p, arg);
  8563. Type *at = a.type;
  8564. if (at->kind == Type_Tuple) {
  8565. for_array(i, at->Tuple.variables) {
  8566. Entity *e = at->Tuple.variables[i];
  8567. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  8568. args[arg_index++] = v;
  8569. }
  8570. } else {
  8571. args[arg_index++] = a;
  8572. }
  8573. }
  8574. }
  8575. if (param_count > 0) {
  8576. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  8577. GB_ASSERT(param_count < 1000000);
  8578. if (arg_count < param_count) {
  8579. isize end = cast(isize)param_count;
  8580. if (variadic) {
  8581. end = variadic_index;
  8582. }
  8583. while (arg_index < end) {
  8584. Entity *e = param_tuple->variables[arg_index];
  8585. GB_ASSERT(e->kind == Entity_Variable);
  8586. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  8587. }
  8588. }
  8589. if (is_c_vararg) {
  8590. GB_ASSERT(variadic);
  8591. GB_ASSERT(!vari_expand);
  8592. isize i = 0;
  8593. for (; i < variadic_index; i++) {
  8594. Entity *e = param_tuple->variables[i];
  8595. if (e->kind == Entity_Variable) {
  8596. args[i] = lb_emit_conv(p, args[i], e->type);
  8597. }
  8598. }
  8599. Type *variadic_type = param_tuple->variables[i]->type;
  8600. GB_ASSERT(is_type_slice(variadic_type));
  8601. variadic_type = base_type(variadic_type)->Slice.elem;
  8602. if (!is_type_any(variadic_type)) {
  8603. for (; i < arg_count; i++) {
  8604. args[i] = lb_emit_conv(p, args[i], variadic_type);
  8605. }
  8606. } else {
  8607. for (; i < arg_count; i++) {
  8608. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  8609. }
  8610. }
  8611. } else if (variadic) {
  8612. isize i = 0;
  8613. for (; i < variadic_index; i++) {
  8614. Entity *e = param_tuple->variables[i];
  8615. if (e->kind == Entity_Variable) {
  8616. args[i] = lb_emit_conv(p, args[i], e->type);
  8617. }
  8618. }
  8619. if (!vari_expand) {
  8620. Type *variadic_type = param_tuple->variables[i]->type;
  8621. GB_ASSERT(is_type_slice(variadic_type));
  8622. variadic_type = base_type(variadic_type)->Slice.elem;
  8623. for (; i < arg_count; i++) {
  8624. args[i] = lb_emit_conv(p, args[i], variadic_type);
  8625. }
  8626. }
  8627. } else {
  8628. for (isize i = 0; i < param_count; i++) {
  8629. Entity *e = param_tuple->variables[i];
  8630. if (e->kind == Entity_Variable) {
  8631. if (args[i].value == nullptr) {
  8632. continue;
  8633. }
  8634. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  8635. args[i] = lb_emit_conv(p, args[i], e->type);
  8636. }
  8637. }
  8638. }
  8639. if (variadic && !vari_expand && !is_c_vararg) {
  8640. // variadic call argument generation
  8641. Type *slice_type = param_tuple->variables[variadic_index]->type;
  8642. Type *elem_type = base_type(slice_type)->Slice.elem;
  8643. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  8644. isize slice_len = arg_count+1 - (variadic_index+1);
  8645. if (slice_len > 0) {
  8646. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  8647. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  8648. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  8649. lb_emit_store(p, addr, args[i]);
  8650. }
  8651. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  8652. lbValue len = lb_const_int(m, t_int, slice_len);
  8653. lb_fill_slice(p, slice, base_elem, len);
  8654. }
  8655. arg_count = param_count;
  8656. args[variadic_index] = lb_addr_load(p, slice);
  8657. }
  8658. }
  8659. if (variadic && variadic_index+1 < param_count) {
  8660. for (isize i = variadic_index+1; i < param_count; i++) {
  8661. Entity *e = param_tuple->variables[i];
  8662. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  8663. }
  8664. }
  8665. isize final_count = param_count;
  8666. if (is_c_vararg) {
  8667. final_count = arg_count;
  8668. }
  8669. if (param_tuple != nullptr) {
  8670. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  8671. Entity *e = param_tuple->variables[i];
  8672. if (args[i].type == nullptr) {
  8673. continue;
  8674. } else if (is_type_untyped_nil(args[i].type)) {
  8675. args[i] = lb_const_nil(m, e->type);
  8676. } else if (is_type_untyped_undef(args[i].type)) {
  8677. args[i] = lb_const_undef(m, e->type);
  8678. }
  8679. }
  8680. }
  8681. auto call_args = array_slice(args, 0, final_count);
  8682. return lb_emit_call(p, value, call_args, ce->inlining, p->copy_elision_hint.ast == expr);
  8683. }
  8684. bool lb_is_const(lbValue value) {
  8685. LLVMValueRef v = value.value;
  8686. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  8687. // TODO(bill): Is this correct behaviour?
  8688. return true;
  8689. }
  8690. if (LLVMIsConstant(v)) {
  8691. return true;
  8692. }
  8693. return false;
  8694. }
  8695. bool lb_is_const_or_global(lbValue value) {
  8696. if (lb_is_const(value)) {
  8697. return true;
  8698. }
  8699. if (LLVMGetValueKind(value.value) == LLVMGlobalVariableValueKind) {
  8700. LLVMTypeRef t = LLVMGetElementType(LLVMTypeOf(value.value));
  8701. if (!lb_is_type_kind(t, LLVMPointerTypeKind)) {
  8702. return false;
  8703. }
  8704. LLVMTypeRef elem = LLVMGetElementType(t);
  8705. return lb_is_type_kind(elem, LLVMFunctionTypeKind);
  8706. }
  8707. return false;
  8708. }
  8709. bool lb_is_const_nil(lbValue value) {
  8710. LLVMValueRef v = value.value;
  8711. if (LLVMIsConstant(v)) {
  8712. if (LLVMIsAConstantAggregateZero(v)) {
  8713. return true;
  8714. } else if (LLVMIsAConstantPointerNull(v)) {
  8715. return true;
  8716. }
  8717. }
  8718. return false;
  8719. }
  8720. String lb_get_const_string(lbModule *m, lbValue value) {
  8721. GB_ASSERT(lb_is_const(value));
  8722. GB_ASSERT(LLVMIsConstant(value.value));
  8723. Type *t = base_type(value.type);
  8724. GB_ASSERT(are_types_identical(t, t_string));
  8725. unsigned ptr_indices[1] = {0};
  8726. unsigned len_indices[1] = {1};
  8727. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  8728. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  8729. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  8730. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  8731. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  8732. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  8733. size_t length = 0;
  8734. char const *text = LLVMGetAsString(underlying_ptr, &length);
  8735. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  8736. return make_string(cast(u8 const *)text, real_length);
  8737. }
  8738. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  8739. GB_ASSERT(is_type_pointer(addr.type));
  8740. Type *type = type_deref(addr.type);
  8741. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  8742. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  8743. }
  8744. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *end_type) {
  8745. GB_ASSERT(type_size_of(value.type) == type_size_of(end_type));
  8746. if (type_size_of(value.type) < 2) {
  8747. return value;
  8748. }
  8749. Type *original_type = value.type;
  8750. if (is_type_float(original_type)) {
  8751. i64 sz = type_size_of(original_type);
  8752. Type *integer_type = nullptr;
  8753. switch (sz) {
  8754. case 2: integer_type = t_u16; break;
  8755. case 4: integer_type = t_u32; break;
  8756. case 8: integer_type = t_u64; break;
  8757. }
  8758. GB_ASSERT(integer_type != nullptr);
  8759. value = lb_emit_transmute(p, value, integer_type);
  8760. }
  8761. char const *name = "llvm.bswap";
  8762. LLVMTypeRef types[1] = {lb_type(p->module, value.type)};
  8763. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8764. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8765. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8766. LLVMValueRef args[1] = {};
  8767. args[0] = value.value;
  8768. lbValue res = {};
  8769. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8770. res.type = value.type;
  8771. if (is_type_float(original_type)) {
  8772. res = lb_emit_transmute(p, res, original_type);
  8773. }
  8774. res.type = end_type;
  8775. return res;
  8776. }
  8777. lbValue lb_emit_count_ones(lbProcedure *p, lbValue x, Type *type) {
  8778. x = lb_emit_conv(p, x, type);
  8779. char const *name = "llvm.ctpop";
  8780. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8781. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8782. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8783. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8784. LLVMValueRef args[1] = {};
  8785. args[0] = x.value;
  8786. lbValue res = {};
  8787. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8788. res.type = type;
  8789. return res;
  8790. }
  8791. lbValue lb_emit_count_zeros(lbProcedure *p, lbValue x, Type *type) {
  8792. i64 sz = 8*type_size_of(type);
  8793. lbValue size = lb_const_int(p->module, type, cast(u64)sz);
  8794. lbValue count = lb_emit_count_ones(p, x, type);
  8795. return lb_emit_arith(p, Token_Sub, size, count, type);
  8796. }
  8797. lbValue lb_emit_count_trailing_zeros(lbProcedure *p, lbValue x, Type *type) {
  8798. x = lb_emit_conv(p, x, type);
  8799. char const *name = "llvm.cttz";
  8800. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8801. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8802. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8803. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8804. LLVMValueRef args[2] = {};
  8805. args[0] = x.value;
  8806. args[1] = LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx));
  8807. lbValue res = {};
  8808. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8809. res.type = type;
  8810. return res;
  8811. }
  8812. lbValue lb_emit_count_leading_zeros(lbProcedure *p, lbValue x, Type *type) {
  8813. x = lb_emit_conv(p, x, type);
  8814. char const *name = "llvm.ctlz";
  8815. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8816. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8817. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8818. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8819. LLVMValueRef args[2] = {};
  8820. args[0] = x.value;
  8821. args[1] = LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx));
  8822. lbValue res = {};
  8823. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8824. res.type = type;
  8825. return res;
  8826. }
  8827. lbValue lb_emit_reverse_bits(lbProcedure *p, lbValue x, Type *type) {
  8828. x = lb_emit_conv(p, x, type);
  8829. char const *name = "llvm.bitreverse";
  8830. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8831. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8832. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8833. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8834. LLVMValueRef args[1] = {};
  8835. args[0] = x.value;
  8836. lbValue res = {};
  8837. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8838. res.type = type;
  8839. return res;
  8840. }
  8841. lbValue lb_emit_bit_set_card(lbProcedure *p, lbValue x) {
  8842. GB_ASSERT(is_type_bit_set(x.type));
  8843. Type *underlying = bit_set_to_int(x.type);
  8844. lbValue card = lb_emit_count_ones(p, x, underlying);
  8845. return lb_emit_conv(p, card, t_int);
  8846. }
  8847. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  8848. lbLoopData data = {};
  8849. lbValue max = lb_const_int(p->module, t_int, count);
  8850. data.idx_addr = lb_add_local_generated(p, index_type, true);
  8851. data.body = lb_create_block(p, "loop.body");
  8852. data.done = lb_create_block(p, "loop.done");
  8853. data.loop = lb_create_block(p, "loop.loop");
  8854. lb_emit_jump(p, data.loop);
  8855. lb_start_block(p, data.loop);
  8856. data.idx = lb_addr_load(p, data.idx_addr);
  8857. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  8858. lb_emit_if(p, cond, data.body, data.done);
  8859. lb_start_block(p, data.body);
  8860. return data;
  8861. }
  8862. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  8863. if (data.idx_addr.addr.value != nullptr) {
  8864. lb_emit_increment(p, data.idx_addr.addr);
  8865. lb_emit_jump(p, data.loop);
  8866. lb_start_block(p, data.done);
  8867. }
  8868. }
  8869. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  8870. lbValue res = {};
  8871. res.type = t_llvm_bool;
  8872. Type *t = x.type;
  8873. if (is_type_pointer(t)) {
  8874. if (op_kind == Token_CmpEq) {
  8875. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  8876. } else if (op_kind == Token_NotEq) {
  8877. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  8878. }
  8879. return res;
  8880. } else if (is_type_cstring(t)) {
  8881. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  8882. if (op_kind == Token_CmpEq) {
  8883. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  8884. } else if (op_kind == Token_NotEq) {
  8885. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  8886. }
  8887. return res;
  8888. } else if (is_type_proc(t)) {
  8889. if (op_kind == Token_CmpEq) {
  8890. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  8891. } else if (op_kind == Token_NotEq) {
  8892. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  8893. }
  8894. return res;
  8895. } else if (is_type_any(t)) {
  8896. // TODO(bill): is this correct behaviour for nil comparison for any?
  8897. lbValue data = lb_emit_struct_ev(p, x, 0);
  8898. lbValue ti = lb_emit_struct_ev(p, x, 1);
  8899. if (op_kind == Token_CmpEq) {
  8900. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  8901. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  8902. res.value = LLVMBuildOr(p->builder, a, b, "");
  8903. return res;
  8904. } else if (op_kind == Token_NotEq) {
  8905. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  8906. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  8907. res.value = LLVMBuildAnd(p->builder, a, b, "");
  8908. return res;
  8909. }
  8910. } else if (is_type_slice(t)) {
  8911. lbValue len = lb_emit_struct_ev(p, x, 1);
  8912. if (op_kind == Token_CmpEq) {
  8913. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  8914. return res;
  8915. } else if (op_kind == Token_NotEq) {
  8916. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  8917. return res;
  8918. }
  8919. } else if (is_type_dynamic_array(t)) {
  8920. lbValue cap = lb_emit_struct_ev(p, x, 2);
  8921. if (op_kind == Token_CmpEq) {
  8922. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  8923. return res;
  8924. } else if (op_kind == Token_NotEq) {
  8925. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  8926. return res;
  8927. }
  8928. } else if (is_type_map(t)) {
  8929. lbValue cap = lb_map_cap(p, x);
  8930. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  8931. } else if (is_type_union(t)) {
  8932. if (type_size_of(t) == 0) {
  8933. if (op_kind == Token_CmpEq) {
  8934. return lb_const_bool(p->module, t_llvm_bool, true);
  8935. } else if (op_kind == Token_NotEq) {
  8936. return lb_const_bool(p->module, t_llvm_bool, false);
  8937. }
  8938. } else if (is_type_union_maybe_pointer(t)) {
  8939. lbValue tag = lb_emit_transmute(p, x, t_rawptr);
  8940. return lb_emit_comp_against_nil(p, op_kind, tag);
  8941. } else {
  8942. lbValue tag = lb_emit_union_tag_value(p, x);
  8943. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  8944. }
  8945. } else if (is_type_typeid(t)) {
  8946. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  8947. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  8948. } else if (is_type_soa_struct(t)) {
  8949. Type *bt = base_type(t);
  8950. if (bt->Struct.soa_kind == StructSoa_Slice) {
  8951. lbValue len = lb_soa_struct_len(p, x);
  8952. if (op_kind == Token_CmpEq) {
  8953. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  8954. return res;
  8955. } else if (op_kind == Token_NotEq) {
  8956. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  8957. return res;
  8958. }
  8959. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  8960. lbValue cap = lb_soa_struct_cap(p, x);
  8961. if (op_kind == Token_CmpEq) {
  8962. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  8963. return res;
  8964. } else if (op_kind == Token_NotEq) {
  8965. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  8966. return res;
  8967. }
  8968. }
  8969. } else if (is_type_struct(t) && type_has_nil(t)) {
  8970. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8971. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  8972. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  8973. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  8974. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  8975. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  8976. return res;
  8977. }
  8978. return {};
  8979. }
  8980. lbValue lb_get_equal_proc_for_type(lbModule *m, Type *type) {
  8981. Type *original_type = type;
  8982. type = base_type(type);
  8983. GB_ASSERT(is_type_comparable(type));
  8984. Type *pt = alloc_type_pointer(type);
  8985. LLVMTypeRef ptr_type = lb_type(m, pt);
  8986. auto key = hash_type(type);
  8987. lbProcedure **found = map_get(&m->equal_procs, key);
  8988. lbProcedure *compare_proc = nullptr;
  8989. if (found) {
  8990. compare_proc = *found;
  8991. GB_ASSERT(compare_proc != nullptr);
  8992. return {compare_proc->value, compare_proc->type};
  8993. }
  8994. static u32 proc_index = 0;
  8995. char buf[16] = {};
  8996. isize n = gb_snprintf(buf, 16, "__$equal%u", ++proc_index);
  8997. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  8998. String proc_name = make_string_c(str);
  8999. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  9000. map_set(&m->equal_procs, key, p);
  9001. lb_begin_procedure_body(p);
  9002. LLVMValueRef x = LLVMGetParam(p->value, 0);
  9003. LLVMValueRef y = LLVMGetParam(p->value, 1);
  9004. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  9005. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  9006. lbValue lhs = {x, pt};
  9007. lbValue rhs = {y, pt};
  9008. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  9009. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  9010. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  9011. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  9012. lb_start_block(p, block_same_ptr);
  9013. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  9014. lb_start_block(p, block_diff_ptr);
  9015. if (type->kind == Type_Struct) {
  9016. type_set_offsets(type);
  9017. lbBlock *block_false = lb_create_block(p, "bfalse");
  9018. lbValue res = lb_const_bool(m, t_bool, true);
  9019. for_array(i, type->Struct.fields) {
  9020. lbBlock *next_block = lb_create_block(p, "btrue");
  9021. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  9022. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  9023. lbValue left = lb_emit_load(p, pleft);
  9024. lbValue right = lb_emit_load(p, pright);
  9025. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  9026. lb_emit_if(p, ok, next_block, block_false);
  9027. lb_emit_jump(p, next_block);
  9028. lb_start_block(p, next_block);
  9029. }
  9030. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  9031. lb_start_block(p, block_false);
  9032. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  9033. } else if (type->kind == Type_Union) {
  9034. if (is_type_union_maybe_pointer(type)) {
  9035. Type *v = type->Union.variants[0];
  9036. Type *pv = alloc_type_pointer(v);
  9037. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, pv));
  9038. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, pv));
  9039. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  9040. ok = lb_emit_conv(p, ok, t_bool);
  9041. LLVMBuildRet(p->builder, ok.value);
  9042. } else {
  9043. lbBlock *block_false = lb_create_block(p, "bfalse");
  9044. lbBlock *block_switch = lb_create_block(p, "bswitch");
  9045. lbValue left_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, lhs));
  9046. lbValue right_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, rhs));
  9047. lbValue tag_eq = lb_emit_comp(p, Token_CmpEq, left_tag, right_tag);
  9048. lb_emit_if(p, tag_eq, block_switch, block_false);
  9049. lb_start_block(p, block_switch);
  9050. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, left_tag.value, block_false->block, cast(unsigned)type->Union.variants.count);
  9051. for_array(i, type->Union.variants) {
  9052. lbBlock *case_block = lb_create_block(p, "bcase");
  9053. lb_start_block(p, case_block);
  9054. Type *v = type->Union.variants[i];
  9055. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  9056. Type *vp = alloc_type_pointer(v);
  9057. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, vp));
  9058. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, vp));
  9059. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  9060. ok = lb_emit_conv(p, ok, t_bool);
  9061. LLVMBuildRet(p->builder, ok.value);
  9062. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  9063. }
  9064. lb_start_block(p, block_false);
  9065. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  9066. }
  9067. } else {
  9068. lbValue left = lb_emit_load(p, lhs);
  9069. lbValue right = lb_emit_load(p, rhs);
  9070. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  9071. ok = lb_emit_conv(p, ok, t_bool);
  9072. LLVMBuildRet(p->builder, ok.value);
  9073. }
  9074. lb_end_procedure_body(p);
  9075. compare_proc = p;
  9076. return {compare_proc->value, compare_proc->type};
  9077. }
  9078. lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  9079. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  9080. i64 sz = type_size_of(type);
  9081. if (1 <= sz && sz <= 16) {
  9082. char name[20] = {};
  9083. gb_snprintf(name, 20, "default_hasher%d", cast(i32)sz);
  9084. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9085. args[0] = data;
  9086. args[1] = seed;
  9087. return lb_emit_runtime_call(p, name, args);
  9088. }
  9089. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9090. args[0] = data;
  9091. args[1] = seed;
  9092. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  9093. return lb_emit_runtime_call(p, "default_hasher_n", args);
  9094. }
  9095. lbValue lb_get_hasher_proc_for_type(lbModule *m, Type *type) {
  9096. Type *original_type = type;
  9097. type = core_type(type);
  9098. GB_ASSERT(is_type_valid_for_keys(type));
  9099. Type *pt = alloc_type_pointer(type);
  9100. LLVMTypeRef ptr_type = lb_type(m, pt);
  9101. auto key = hash_type(type);
  9102. lbProcedure **found = map_get(&m->hasher_procs, key);
  9103. if (found) {
  9104. GB_ASSERT(*found != nullptr);
  9105. return {(*found)->value, (*found)->type};
  9106. }
  9107. static u32 proc_index = 0;
  9108. char buf[16] = {};
  9109. isize n = gb_snprintf(buf, 16, "__$hasher%u", ++proc_index);
  9110. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  9111. String proc_name = make_string_c(str);
  9112. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  9113. map_set(&m->hasher_procs, key, p);
  9114. lb_begin_procedure_body(p);
  9115. defer (lb_end_procedure_body(p));
  9116. LLVMValueRef x = LLVMGetParam(p->value, 0);
  9117. LLVMValueRef y = LLVMGetParam(p->value, 1);
  9118. lbValue data = {x, t_rawptr};
  9119. lbValue seed = {y, t_uintptr};
  9120. LLVMAttributeRef nonnull_attr = lb_create_enum_attribute(m->ctx, "nonnull");
  9121. LLVMAddAttributeAtIndex(p->value, 1+0, nonnull_attr);
  9122. if (is_type_simple_compare(type)) {
  9123. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  9124. LLVMBuildRet(p->builder, res.value);
  9125. return {p->value, p->type};
  9126. }
  9127. if (type->kind == Type_Struct) {
  9128. type_set_offsets(type);
  9129. data = lb_emit_conv(p, data, t_u8_ptr);
  9130. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9131. for_array(i, type->Struct.fields) {
  9132. i64 offset = type->Struct.offsets[i];
  9133. Entity *field = type->Struct.fields[i];
  9134. lbValue field_hasher = lb_get_hasher_proc_for_type(m, field->type);
  9135. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  9136. args[0] = ptr;
  9137. args[1] = seed;
  9138. seed = lb_emit_call(p, field_hasher, args);
  9139. }
  9140. LLVMBuildRet(p->builder, seed.value);
  9141. } else if (type->kind == Type_Union) {
  9142. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9143. if (is_type_union_maybe_pointer(type)) {
  9144. Type *v = type->Union.variants[0];
  9145. lbValue variant_hasher = lb_get_hasher_proc_for_type(m, v);
  9146. args[0] = data;
  9147. args[1] = seed;
  9148. lbValue res = lb_emit_call(p, variant_hasher, args);
  9149. LLVMBuildRet(p->builder, res.value);
  9150. }
  9151. lbBlock *end_block = lb_create_block(p, "bend");
  9152. data = lb_emit_conv(p, data, pt);
  9153. lbValue tag_ptr = lb_emit_union_tag_ptr(p, data);
  9154. lbValue tag = lb_emit_load(p, tag_ptr);
  9155. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, tag.value, end_block->block, cast(unsigned)type->Union.variants.count);
  9156. for_array(i, type->Union.variants) {
  9157. lbBlock *case_block = lb_create_block(p, "bcase");
  9158. lb_start_block(p, case_block);
  9159. Type *v = type->Union.variants[i];
  9160. Type *vp = alloc_type_pointer(v);
  9161. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  9162. lbValue variant_hasher = lb_get_hasher_proc_for_type(m, v);
  9163. args[0] = data;
  9164. args[1] = seed;
  9165. lbValue res = lb_emit_call(p, variant_hasher, args);
  9166. LLVMBuildRet(p->builder, res.value);
  9167. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  9168. }
  9169. lb_start_block(p, end_block);
  9170. LLVMBuildRet(p->builder, seed.value);
  9171. } else if (type->kind == Type_Array) {
  9172. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  9173. lb_addr_store(p, pres, seed);
  9174. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9175. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->Array.elem);
  9176. auto loop_data = lb_loop_start(p, type->Array.count, t_i32);
  9177. data = lb_emit_conv(p, data, pt);
  9178. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  9179. args[0] = ptr;
  9180. args[1] = lb_addr_load(p, pres);
  9181. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  9182. lb_addr_store(p, pres, new_seed);
  9183. lb_loop_end(p, loop_data);
  9184. lbValue res = lb_addr_load(p, pres);
  9185. LLVMBuildRet(p->builder, res.value);
  9186. } else if (type->kind == Type_EnumeratedArray) {
  9187. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  9188. lb_addr_store(p, res, seed);
  9189. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9190. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  9191. auto loop_data = lb_loop_start(p, type->EnumeratedArray.count, t_i32);
  9192. data = lb_emit_conv(p, data, pt);
  9193. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  9194. args[0] = ptr;
  9195. args[1] = lb_addr_load(p, res);
  9196. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  9197. lb_addr_store(p, res, new_seed);
  9198. lb_loop_end(p, loop_data);
  9199. lbValue vres = lb_addr_load(p, res);
  9200. LLVMBuildRet(p->builder, vres.value);
  9201. } else if (is_type_cstring(type)) {
  9202. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9203. args[0] = data;
  9204. args[1] = seed;
  9205. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  9206. LLVMBuildRet(p->builder, res.value);
  9207. } else if (is_type_string(type)) {
  9208. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9209. args[0] = data;
  9210. args[1] = seed;
  9211. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  9212. LLVMBuildRet(p->builder, res.value);
  9213. } else {
  9214. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  9215. }
  9216. return {p->value, p->type};
  9217. }
  9218. lbValue lb_compare_records(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right, Type *type) {
  9219. GB_ASSERT((is_type_struct(type) || is_type_union(type)) && is_type_comparable(type));
  9220. lbValue left_ptr = lb_address_from_load_or_generate_local(p, left);
  9221. lbValue right_ptr = lb_address_from_load_or_generate_local(p, right);
  9222. lbValue res = {};
  9223. if (is_type_simple_compare(type)) {
  9224. // TODO(bill): Test to see if this is actually faster!!!!
  9225. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9226. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  9227. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  9228. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  9229. res = lb_emit_runtime_call(p, "memory_equal", args);
  9230. } else {
  9231. lbValue value = lb_get_equal_proc_for_type(p->module, type);
  9232. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9233. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  9234. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  9235. res = lb_emit_call(p, value, args);
  9236. }
  9237. if (op_kind == Token_NotEq) {
  9238. res = lb_emit_unary_arith(p, Token_Not, res, res.type);
  9239. }
  9240. return res;
  9241. }
  9242. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  9243. Type *a = core_type(left.type);
  9244. Type *b = core_type(right.type);
  9245. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  9246. lbValue nil_check = {};
  9247. if (is_type_untyped_nil(left.type)) {
  9248. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  9249. } else if (is_type_untyped_nil(right.type)) {
  9250. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  9251. }
  9252. if (nil_check.value != nullptr) {
  9253. return nil_check;
  9254. }
  9255. if (are_types_identical(a, b)) {
  9256. // NOTE(bill): No need for a conversion
  9257. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  9258. left = lb_emit_conv(p, left, right.type);
  9259. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  9260. right = lb_emit_conv(p, right, left.type);
  9261. } else {
  9262. Type *lt = left.type;
  9263. Type *rt = right.type;
  9264. lt = left.type;
  9265. rt = right.type;
  9266. i64 ls = type_size_of(lt);
  9267. i64 rs = type_size_of(rt);
  9268. // NOTE(bill): Quick heuristic, larger types are usually the target type
  9269. if (ls < rs) {
  9270. left = lb_emit_conv(p, left, rt);
  9271. } else if (ls > rs) {
  9272. right = lb_emit_conv(p, right, lt);
  9273. } else {
  9274. if (is_type_union(rt)) {
  9275. left = lb_emit_conv(p, left, rt);
  9276. } else {
  9277. right = lb_emit_conv(p, right, lt);
  9278. }
  9279. }
  9280. }
  9281. if (is_type_array(a) || is_type_enumerated_array(a)) {
  9282. Type *tl = base_type(a);
  9283. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  9284. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  9285. TokenKind cmp_op = Token_And;
  9286. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  9287. if (op_kind == Token_NotEq) {
  9288. res = lb_const_bool(p->module, t_llvm_bool, false);
  9289. cmp_op = Token_Or;
  9290. } else if (op_kind == Token_CmpEq) {
  9291. res = lb_const_bool(p->module, t_llvm_bool, true);
  9292. cmp_op = Token_And;
  9293. }
  9294. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  9295. i32 count = 0;
  9296. switch (tl->kind) {
  9297. case Type_Array: count = cast(i32)tl->Array.count; break;
  9298. case Type_EnumeratedArray: count = cast(i32)tl->EnumeratedArray.count; break;
  9299. }
  9300. if (inline_array_arith) {
  9301. // inline
  9302. lbAddr val = lb_add_local_generated(p, t_bool, false);
  9303. lb_addr_store(p, val, res);
  9304. for (i32 i = 0; i < count; i++) {
  9305. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  9306. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  9307. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  9308. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  9309. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  9310. }
  9311. return lb_addr_load(p, val);
  9312. } else {
  9313. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  9314. // TODO(bill): Test to see if this is actually faster!!!!
  9315. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9316. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  9317. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  9318. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  9319. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  9320. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  9321. return lb_emit_conv(p, res, t_bool);
  9322. } else {
  9323. lbAddr val = lb_add_local_generated(p, t_bool, false);
  9324. lb_addr_store(p, val, res);
  9325. auto loop_data = lb_loop_start(p, count, t_i32);
  9326. {
  9327. lbValue i = loop_data.idx;
  9328. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  9329. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  9330. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  9331. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  9332. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  9333. }
  9334. lb_loop_end(p, loop_data);
  9335. return lb_addr_load(p, val);
  9336. }
  9337. }
  9338. }
  9339. if ((is_type_struct(a) || is_type_union(a)) && is_type_comparable(a)) {
  9340. return lb_compare_records(p, op_kind, left, right, a);
  9341. }
  9342. if ((is_type_struct(b) || is_type_union(b)) && is_type_comparable(b)) {
  9343. return lb_compare_records(p, op_kind, left, right, b);
  9344. }
  9345. if (is_type_string(a)) {
  9346. if (is_type_cstring(a)) {
  9347. left = lb_emit_conv(p, left, t_string);
  9348. right = lb_emit_conv(p, right, t_string);
  9349. }
  9350. char const *runtime_procedure = nullptr;
  9351. switch (op_kind) {
  9352. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  9353. case Token_NotEq: runtime_procedure = "string_ne"; break;
  9354. case Token_Lt: runtime_procedure = "string_lt"; break;
  9355. case Token_Gt: runtime_procedure = "string_gt"; break;
  9356. case Token_LtEq: runtime_procedure = "string_le"; break;
  9357. case Token_GtEq: runtime_procedure = "string_gt"; break;
  9358. }
  9359. GB_ASSERT(runtime_procedure != nullptr);
  9360. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9361. args[0] = left;
  9362. args[1] = right;
  9363. return lb_emit_runtime_call(p, runtime_procedure, args);
  9364. }
  9365. if (is_type_complex(a)) {
  9366. char const *runtime_procedure = "";
  9367. i64 sz = 8*type_size_of(a);
  9368. switch (sz) {
  9369. case 64:
  9370. switch (op_kind) {
  9371. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  9372. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  9373. }
  9374. break;
  9375. case 128:
  9376. switch (op_kind) {
  9377. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  9378. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  9379. }
  9380. break;
  9381. }
  9382. GB_ASSERT(runtime_procedure != nullptr);
  9383. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9384. args[0] = left;
  9385. args[1] = right;
  9386. return lb_emit_runtime_call(p, runtime_procedure, args);
  9387. }
  9388. if (is_type_quaternion(a)) {
  9389. char const *runtime_procedure = "";
  9390. i64 sz = 8*type_size_of(a);
  9391. switch (sz) {
  9392. case 128:
  9393. switch (op_kind) {
  9394. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  9395. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  9396. }
  9397. break;
  9398. case 256:
  9399. switch (op_kind) {
  9400. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  9401. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  9402. }
  9403. break;
  9404. }
  9405. GB_ASSERT(runtime_procedure != nullptr);
  9406. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9407. args[0] = left;
  9408. args[1] = right;
  9409. return lb_emit_runtime_call(p, runtime_procedure, args);
  9410. }
  9411. if (is_type_bit_set(a)) {
  9412. switch (op_kind) {
  9413. case Token_Lt:
  9414. case Token_LtEq:
  9415. case Token_Gt:
  9416. case Token_GtEq:
  9417. {
  9418. Type *it = bit_set_to_int(a);
  9419. lbValue lhs = lb_emit_transmute(p, left, it);
  9420. lbValue rhs = lb_emit_transmute(p, right, it);
  9421. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  9422. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  9423. // (lhs & rhs) == lhs
  9424. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  9425. res.type = t_llvm_bool;
  9426. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  9427. // (lhs & rhs) == rhs
  9428. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  9429. res.type = t_llvm_bool;
  9430. }
  9431. // NOTE(bill): Strict subsets
  9432. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  9433. // res &~ (lhs == rhs)
  9434. lbValue eq = {};
  9435. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  9436. eq.type = t_llvm_bool;
  9437. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  9438. }
  9439. return res;
  9440. }
  9441. case Token_CmpEq:
  9442. case Token_NotEq:
  9443. {
  9444. LLVMIntPredicate pred = {};
  9445. switch (op_kind) {
  9446. case Token_CmpEq: pred = LLVMIntEQ; break;
  9447. case Token_NotEq: pred = LLVMIntNE; break;
  9448. }
  9449. lbValue res = {};
  9450. res.type = t_llvm_bool;
  9451. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  9452. return res;
  9453. }
  9454. }
  9455. }
  9456. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  9457. Type *t = left.type;
  9458. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  9459. Type *platform_type = integer_endian_type_to_platform_type(t);
  9460. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  9461. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  9462. left = x;
  9463. right = y;
  9464. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  9465. Type *platform_type = integer_endian_type_to_platform_type(t);
  9466. lbValue x = lb_emit_conv(p, left, platform_type);
  9467. lbValue y = lb_emit_conv(p, right, platform_type);
  9468. left = x;
  9469. right = y;
  9470. }
  9471. }
  9472. a = core_type(left.type);
  9473. b = core_type(right.type);
  9474. lbValue res = {};
  9475. res.type = t_llvm_bool;
  9476. if (is_type_integer(a) ||
  9477. is_type_boolean(a) ||
  9478. is_type_pointer(a) ||
  9479. is_type_proc(a) ||
  9480. is_type_enum(a)) {
  9481. LLVMIntPredicate pred = {};
  9482. if (is_type_unsigned(left.type)) {
  9483. switch (op_kind) {
  9484. case Token_Gt: pred = LLVMIntUGT; break;
  9485. case Token_GtEq: pred = LLVMIntUGE; break;
  9486. case Token_Lt: pred = LLVMIntULT; break;
  9487. case Token_LtEq: pred = LLVMIntULE; break;
  9488. }
  9489. } else {
  9490. switch (op_kind) {
  9491. case Token_Gt: pred = LLVMIntSGT; break;
  9492. case Token_GtEq: pred = LLVMIntSGE; break;
  9493. case Token_Lt: pred = LLVMIntSLT; break;
  9494. case Token_LtEq: pred = LLVMIntSLE; break;
  9495. }
  9496. }
  9497. switch (op_kind) {
  9498. case Token_CmpEq: pred = LLVMIntEQ; break;
  9499. case Token_NotEq: pred = LLVMIntNE; break;
  9500. }
  9501. LLVMValueRef lhs = left.value;
  9502. LLVMValueRef rhs = right.value;
  9503. if (LLVMTypeOf(lhs) != LLVMTypeOf(rhs)) {
  9504. if (lb_is_type_kind(LLVMTypeOf(lhs), LLVMPointerTypeKind)) {
  9505. rhs = LLVMBuildPointerCast(p->builder, rhs, LLVMTypeOf(lhs), "");
  9506. }
  9507. }
  9508. res.value = LLVMBuildICmp(p->builder, pred, lhs, rhs, "");
  9509. } else if (is_type_float(a)) {
  9510. LLVMRealPredicate pred = {};
  9511. switch (op_kind) {
  9512. case Token_CmpEq: pred = LLVMRealOEQ; break;
  9513. case Token_Gt: pred = LLVMRealOGT; break;
  9514. case Token_GtEq: pred = LLVMRealOGE; break;
  9515. case Token_Lt: pred = LLVMRealOLT; break;
  9516. case Token_LtEq: pred = LLVMRealOLE; break;
  9517. case Token_NotEq: pred = LLVMRealONE; break;
  9518. }
  9519. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  9520. } else if (is_type_typeid(a)) {
  9521. LLVMIntPredicate pred = {};
  9522. switch (op_kind) {
  9523. case Token_Gt: pred = LLVMIntUGT; break;
  9524. case Token_GtEq: pred = LLVMIntUGE; break;
  9525. case Token_Lt: pred = LLVMIntULT; break;
  9526. case Token_LtEq: pred = LLVMIntULE; break;
  9527. case Token_CmpEq: pred = LLVMIntEQ; break;
  9528. case Token_NotEq: pred = LLVMIntNE; break;
  9529. }
  9530. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  9531. } else {
  9532. GB_PANIC("Unhandled comparison kind %s (%s) %.*s %s (%s)", type_to_string(left.type), type_to_string(base_type(left.type)), LIT(token_strings[op_kind]), type_to_string(right.type), type_to_string(base_type(right.type)));
  9533. }
  9534. return res;
  9535. }
  9536. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  9537. lbProcedure **found = map_get(&m->gen->anonymous_proc_lits, hash_pointer(expr));
  9538. if (found) {
  9539. return lb_find_procedure_value_from_entity(m, (*found)->entity);
  9540. }
  9541. ast_node(pl, ProcLit, expr);
  9542. // NOTE(bill): Generate a new name
  9543. // parent$count
  9544. isize name_len = prefix_name.len + 1 + 8 + 1;
  9545. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  9546. i32 name_id = cast(i32)m->gen->anonymous_proc_lits.entries.count;
  9547. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  9548. String name = make_string((u8 *)name_text, name_len-1);
  9549. Type *type = type_of_expr(expr);
  9550. Token token = {};
  9551. token.pos = ast_token(expr).pos;
  9552. token.kind = Token_Ident;
  9553. token.string = name;
  9554. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  9555. e->file = expr->file;
  9556. e->decl_info = pl->decl;
  9557. e->code_gen_module = m;
  9558. lbProcedure *p = lb_create_procedure(m, e);
  9559. lbValue value = {};
  9560. value.value = p->value;
  9561. value.type = p->type;
  9562. array_add(&m->procedures_to_generate, p);
  9563. if (parent != nullptr) {
  9564. array_add(&parent->children, p);
  9565. } else {
  9566. string_map_set(&m->members, name, value);
  9567. }
  9568. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  9569. map_set(&m->gen->anonymous_proc_lits, hash_pointer(expr), p);
  9570. return value;
  9571. }
  9572. lbValue lb_emit_union_cast_only_ok_check(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  9573. GB_ASSERT(is_type_tuple(type));
  9574. lbModule *m = p->module;
  9575. Type *src_type = value.type;
  9576. bool is_ptr = is_type_pointer(src_type);
  9577. // IMPORTANT NOTE(bill): This assumes that the value is completely ignored
  9578. // so when it does an assignment, it complete ignores the value.
  9579. // Just make it two booleans and ignore the first one
  9580. //
  9581. // _, ok := x.(T);
  9582. //
  9583. Type *ok_type = type->Tuple.variables[1]->type;
  9584. Type *gen_tuple_types[2] = {};
  9585. gen_tuple_types[0] = ok_type;
  9586. gen_tuple_types[1] = ok_type;
  9587. Type *gen_tuple = alloc_type_tuple_from_field_types(gen_tuple_types, gb_count_of(gen_tuple_types), false, true);
  9588. lbAddr v = lb_add_local_generated(p, gen_tuple, false);
  9589. if (is_ptr) {
  9590. value = lb_emit_load(p, value);
  9591. }
  9592. Type *src = base_type(type_deref(src_type));
  9593. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  9594. Type *dst = type->Tuple.variables[0]->type;
  9595. lbValue cond = {};
  9596. if (is_type_union_maybe_pointer(src)) {
  9597. lbValue data = lb_emit_transmute(p, value, dst);
  9598. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  9599. } else {
  9600. lbValue tag = lb_emit_union_tag_value(p, value);
  9601. lbValue dst_tag = lb_const_union_tag(m, src, dst);
  9602. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  9603. }
  9604. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  9605. lb_emit_store(p, gep1, cond);
  9606. return lb_addr_load(p, v);
  9607. }
  9608. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  9609. lbModule *m = p->module;
  9610. Type *src_type = value.type;
  9611. bool is_ptr = is_type_pointer(src_type);
  9612. bool is_tuple = true;
  9613. Type *tuple = type;
  9614. if (type->kind != Type_Tuple) {
  9615. is_tuple = false;
  9616. tuple = make_optional_ok_type(type);
  9617. }
  9618. lbAddr v = lb_add_local_generated(p, tuple, true);
  9619. if (is_ptr) {
  9620. value = lb_emit_load(p, value);
  9621. }
  9622. Type *src = base_type(type_deref(src_type));
  9623. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  9624. Type *dst = tuple->Tuple.variables[0]->type;
  9625. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  9626. lbValue tag = {};
  9627. lbValue dst_tag = {};
  9628. lbValue cond = {};
  9629. lbValue data = {};
  9630. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  9631. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  9632. if (is_type_union_maybe_pointer(src)) {
  9633. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  9634. } else {
  9635. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  9636. dst_tag = lb_const_union_tag(m, src, dst);
  9637. }
  9638. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  9639. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  9640. if (data.value != nullptr) {
  9641. GB_ASSERT(is_type_union_maybe_pointer(src));
  9642. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  9643. } else {
  9644. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  9645. }
  9646. lb_emit_if(p, cond, ok_block, end_block);
  9647. lb_start_block(p, ok_block);
  9648. if (data.value == nullptr) {
  9649. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  9650. }
  9651. lb_emit_store(p, gep0, data);
  9652. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  9653. lb_emit_jump(p, end_block);
  9654. lb_start_block(p, end_block);
  9655. if (!is_tuple) {
  9656. {
  9657. // NOTE(bill): Panic on invalid conversion
  9658. Type *dst_type = tuple->Tuple.variables[0]->type;
  9659. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  9660. auto args = array_make<lbValue>(permanent_allocator(), 7);
  9661. args[0] = ok;
  9662. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  9663. args[2] = lb_const_int(m, t_i32, pos.line);
  9664. args[3] = lb_const_int(m, t_i32, pos.column);
  9665. args[4] = lb_typeid(m, src_type);
  9666. args[5] = lb_typeid(m, dst_type);
  9667. args[6] = lb_emit_conv(p, value_, t_rawptr);
  9668. lb_emit_runtime_call(p, "type_assertion_check2", args);
  9669. }
  9670. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  9671. }
  9672. return lb_addr_load(p, v);
  9673. }
  9674. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  9675. lbModule *m = p->module;
  9676. Type *src_type = value.type;
  9677. if (is_type_pointer(src_type)) {
  9678. value = lb_emit_load(p, value);
  9679. }
  9680. bool is_tuple = true;
  9681. Type *tuple = type;
  9682. if (type->kind != Type_Tuple) {
  9683. is_tuple = false;
  9684. tuple = make_optional_ok_type(type);
  9685. }
  9686. Type *dst_type = tuple->Tuple.variables[0]->type;
  9687. lbAddr v = lb_add_local_generated(p, tuple, true);
  9688. lbValue dst_typeid = lb_typeid(m, dst_type);
  9689. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  9690. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  9691. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  9692. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  9693. lb_emit_if(p, cond, ok_block, end_block);
  9694. lb_start_block(p, ok_block);
  9695. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  9696. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  9697. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  9698. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  9699. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  9700. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  9701. lb_emit_jump(p, end_block);
  9702. lb_start_block(p, end_block);
  9703. if (!is_tuple) {
  9704. // NOTE(bill): Panic on invalid conversion
  9705. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  9706. auto args = array_make<lbValue>(permanent_allocator(), 7);
  9707. args[0] = ok;
  9708. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  9709. args[2] = lb_const_int(m, t_i32, pos.line);
  9710. args[3] = lb_const_int(m, t_i32, pos.column);
  9711. args[4] = any_typeid;
  9712. args[5] = dst_typeid;
  9713. args[6] = lb_emit_struct_ev(p, value, 0);;
  9714. lb_emit_runtime_call(p, "type_assertion_check2", args);
  9715. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  9716. }
  9717. return v;
  9718. }
  9719. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  9720. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  9721. }
  9722. lbValue lb_find_ident(lbProcedure *p, lbModule *m, Entity *e, Ast *expr) {
  9723. auto *found = map_get(&m->values, hash_entity(e));
  9724. if (found) {
  9725. auto v = *found;
  9726. // NOTE(bill): This is because pointers are already pointers in LLVM
  9727. if (is_type_proc(v.type)) {
  9728. return v;
  9729. }
  9730. return lb_emit_load(p, v);
  9731. } else if (e != nullptr && e->kind == Entity_Variable) {
  9732. return lb_addr_load(p, lb_build_addr(p, expr));
  9733. }
  9734. if (e->kind == Entity_Procedure) {
  9735. return lb_find_procedure_value_from_entity(m, e);
  9736. }
  9737. if (USE_SEPARTE_MODULES) {
  9738. lbModule *other_module = lb_pkg_module(m->gen, e->pkg);
  9739. if (other_module != m) {
  9740. String name = lb_get_entity_name(other_module, e);
  9741. lbValue g = {};
  9742. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  9743. g.type = alloc_type_pointer(e->type);
  9744. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  9745. lb_add_entity(m, e, g);
  9746. lb_add_member(m, name, g);
  9747. return lb_emit_load(p, g);
  9748. }
  9749. }
  9750. String pkg = {};
  9751. if (e->pkg) {
  9752. pkg = e->pkg->name;
  9753. }
  9754. gb_printf_err("Error in: %s\n", token_pos_to_string(ast_token(expr).pos));
  9755. GB_PANIC("nullptr value for expression from identifier: %.*s.%.*s (%p) : %s @ %p", LIT(pkg), LIT(e->token.string), e, type_to_string(e->type), expr);
  9756. return {};
  9757. }
  9758. bool lb_is_expr_constant_zero(Ast *expr) {
  9759. GB_ASSERT(expr != nullptr);
  9760. auto v = exact_value_to_integer(expr->tav.value);
  9761. if (v.kind == ExactValue_Integer) {
  9762. return big_int_cmp_zero(&v.value_integer) == 0;
  9763. }
  9764. return false;
  9765. }
  9766. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  9767. lbModule *m = p->module;
  9768. u16 prev_state_flags = p->state_flags;
  9769. defer (p->state_flags = prev_state_flags);
  9770. if (expr->state_flags != 0) {
  9771. u16 in = expr->state_flags;
  9772. u16 out = p->state_flags;
  9773. if (in & StateFlag_bounds_check) {
  9774. out |= StateFlag_bounds_check;
  9775. out &= ~StateFlag_no_bounds_check;
  9776. } else if (in & StateFlag_no_bounds_check) {
  9777. out |= StateFlag_no_bounds_check;
  9778. out &= ~StateFlag_bounds_check;
  9779. }
  9780. p->state_flags = out;
  9781. }
  9782. expr = unparen_expr(expr);
  9783. TokenPos expr_pos = ast_token(expr).pos;
  9784. TypeAndValue tv = type_and_value_of_expr(expr);
  9785. GB_ASSERT_MSG(tv.mode != Addressing_Invalid, "invalid expression '%s' (tv.mode = %d, tv.type = %s) @ %s\n Current Proc: %.*s : %s", expr_to_string(expr), tv.mode, type_to_string(tv.type), token_pos_to_string(expr_pos), LIT(p->name), type_to_string(p->type));
  9786. if (tv.value.kind != ExactValue_Invalid) {
  9787. // NOTE(bill): The commented out code below is just for debug purposes only
  9788. // GB_ASSERT_MSG(!is_type_untyped(tv.type), "%s @ %s\n%s", type_to_string(tv.type), token_pos_to_string(expr_pos), expr_to_string(expr));
  9789. // if (is_type_untyped(tv.type)) {
  9790. // gb_printf_err("%s %s\n", token_pos_to_string(expr_pos), expr_to_string(expr));
  9791. // }
  9792. // NOTE(bill): Short on constant values
  9793. return lb_const_value(p->module, tv.type, tv.value);
  9794. }
  9795. #if 0
  9796. LLVMMetadataRef prev_debug_location = nullptr;
  9797. if (p->debug_info != nullptr) {
  9798. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  9799. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, expr));
  9800. }
  9801. defer (if (prev_debug_location != nullptr) {
  9802. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  9803. });
  9804. #endif
  9805. switch (expr->kind) {
  9806. case_ast_node(bl, BasicLit, expr);
  9807. TokenPos pos = bl->token.pos;
  9808. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(token_strings[bl->token.kind]));
  9809. case_end;
  9810. case_ast_node(bd, BasicDirective, expr);
  9811. TokenPos pos = bd->token.pos;
  9812. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(bd->name.string));
  9813. case_end;
  9814. case_ast_node(i, Implicit, expr);
  9815. return lb_addr_load(p, lb_build_addr(p, expr));
  9816. case_end;
  9817. case_ast_node(u, Undef, expr)
  9818. lbValue res = {};
  9819. if (is_type_untyped(tv.type)) {
  9820. res.value = nullptr;
  9821. res.type = t_untyped_undef;
  9822. } else {
  9823. res.value = LLVMGetUndef(lb_type(m, tv.type));
  9824. res.type = tv.type;
  9825. }
  9826. return res;
  9827. case_end;
  9828. case_ast_node(i, Ident, expr);
  9829. Entity *e = entity_from_expr(expr);
  9830. e = strip_entity_wrapping(e);
  9831. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  9832. if (e->kind == Entity_Builtin) {
  9833. Token token = ast_token(expr);
  9834. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  9835. "\t at %s", LIT(builtin_procs[e->Builtin.id].name),
  9836. token_pos_to_string(token.pos));
  9837. return {};
  9838. } else if (e->kind == Entity_Nil) {
  9839. lbValue res = {};
  9840. res.value = nullptr;
  9841. res.type = e->type;
  9842. return res;
  9843. }
  9844. GB_ASSERT(e->kind != Entity_ProcGroup);
  9845. return lb_find_ident(p, m, e, expr);
  9846. case_end;
  9847. case_ast_node(de, DerefExpr, expr);
  9848. return lb_addr_load(p, lb_build_addr(p, expr));
  9849. case_end;
  9850. case_ast_node(se, SelectorExpr, expr);
  9851. TypeAndValue tav = type_and_value_of_expr(expr);
  9852. GB_ASSERT(tav.mode != Addressing_Invalid);
  9853. return lb_addr_load(p, lb_build_addr(p, expr));
  9854. case_end;
  9855. case_ast_node(ise, ImplicitSelectorExpr, expr);
  9856. TypeAndValue tav = type_and_value_of_expr(expr);
  9857. GB_ASSERT(tav.mode == Addressing_Constant);
  9858. return lb_const_value(p->module, tv.type, tv.value);
  9859. case_end;
  9860. case_ast_node(se, SelectorCallExpr, expr);
  9861. GB_ASSERT(se->modified_call);
  9862. TypeAndValue tav = type_and_value_of_expr(expr);
  9863. GB_ASSERT(tav.mode != Addressing_Invalid);
  9864. return lb_build_expr(p, se->call);
  9865. case_end;
  9866. case_ast_node(te, TernaryIfExpr, expr);
  9867. LLVMValueRef incoming_values[2] = {};
  9868. LLVMBasicBlockRef incoming_blocks[2] = {};
  9869. GB_ASSERT(te->y != nullptr);
  9870. lbBlock *then = lb_create_block(p, "if.then");
  9871. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  9872. lbBlock *else_ = lb_create_block(p, "if.else");
  9873. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  9874. lb_start_block(p, then);
  9875. Type *type = default_type(type_of_expr(expr));
  9876. lb_open_scope(p, nullptr);
  9877. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  9878. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9879. lb_emit_jump(p, done);
  9880. lb_start_block(p, else_);
  9881. lb_open_scope(p, nullptr);
  9882. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  9883. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9884. lb_emit_jump(p, done);
  9885. lb_start_block(p, done);
  9886. lbValue res = {};
  9887. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  9888. res.type = type;
  9889. GB_ASSERT(p->curr_block->preds.count >= 2);
  9890. incoming_blocks[0] = p->curr_block->preds[0]->block;
  9891. incoming_blocks[1] = p->curr_block->preds[1]->block;
  9892. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  9893. return res;
  9894. case_end;
  9895. case_ast_node(te, TernaryWhenExpr, expr);
  9896. TypeAndValue tav = type_and_value_of_expr(te->cond);
  9897. GB_ASSERT(tav.mode == Addressing_Constant);
  9898. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  9899. if (tav.value.value_bool) {
  9900. return lb_build_expr(p, te->x);
  9901. } else {
  9902. return lb_build_expr(p, te->y);
  9903. }
  9904. case_end;
  9905. case_ast_node(ta, TypeAssertion, expr);
  9906. TokenPos pos = ast_token(expr).pos;
  9907. Type *type = tv.type;
  9908. lbValue e = lb_build_expr(p, ta->expr);
  9909. Type *t = type_deref(e.type);
  9910. if (is_type_union(t)) {
  9911. if (ta->ignores[0]) {
  9912. // NOTE(bill): This is not needed for optimization levels other than 0
  9913. return lb_emit_union_cast_only_ok_check(p, e, type, pos);
  9914. }
  9915. return lb_emit_union_cast(p, e, type, pos);
  9916. } else if (is_type_any(t)) {
  9917. return lb_emit_any_cast(p, e, type, pos);
  9918. } else {
  9919. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  9920. }
  9921. case_end;
  9922. case_ast_node(tc, TypeCast, expr);
  9923. lbValue e = lb_build_expr(p, tc->expr);
  9924. switch (tc->token.kind) {
  9925. case Token_cast:
  9926. return lb_emit_conv(p, e, tv.type);
  9927. case Token_transmute:
  9928. return lb_emit_transmute(p, e, tv.type);
  9929. }
  9930. GB_PANIC("Invalid AST TypeCast");
  9931. case_end;
  9932. case_ast_node(ac, AutoCast, expr);
  9933. lbValue value = lb_build_expr(p, ac->expr);
  9934. return lb_emit_conv(p, value, tv.type);
  9935. case_end;
  9936. case_ast_node(ue, UnaryExpr, expr);
  9937. switch (ue->op.kind) {
  9938. case Token_And: {
  9939. Ast *ue_expr = unparen_expr(ue->expr);
  9940. if (ue_expr->kind == Ast_CompoundLit) {
  9941. lbValue v = lb_build_expr(p, ue->expr);
  9942. Type *type = v.type;
  9943. lbAddr addr = {};
  9944. if (p->is_startup) {
  9945. addr = lb_add_global_generated(p->module, type, v);
  9946. } else {
  9947. addr = lb_add_local_generated(p, type, false);
  9948. }
  9949. lb_addr_store(p, addr, v);
  9950. return addr.addr;
  9951. } else if (ue_expr->kind == Ast_TypeAssertion) {
  9952. GB_ASSERT(is_type_pointer(tv.type));
  9953. ast_node(ta, TypeAssertion, ue_expr);
  9954. TokenPos pos = ast_token(expr).pos;
  9955. Type *type = type_of_expr(ue_expr);
  9956. GB_ASSERT(!is_type_tuple(type));
  9957. lbValue e = lb_build_expr(p, ta->expr);
  9958. Type *t = type_deref(e.type);
  9959. if (is_type_union(t)) {
  9960. lbValue v = e;
  9961. if (!is_type_pointer(v.type)) {
  9962. v = lb_address_from_load_or_generate_local(p, v);
  9963. }
  9964. Type *src_type = type_deref(v.type);
  9965. Type *dst_type = type;
  9966. lbValue src_tag = {};
  9967. lbValue dst_tag = {};
  9968. if (is_type_union_maybe_pointer(src_type)) {
  9969. src_tag = lb_emit_comp_against_nil(p, Token_NotEq, v);
  9970. dst_tag = lb_const_bool(p->module, t_bool, true);
  9971. } else {
  9972. src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  9973. dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  9974. }
  9975. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  9976. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9977. args[0] = ok;
  9978. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  9979. args[2] = lb_const_int(p->module, t_i32, pos.line);
  9980. args[3] = lb_const_int(p->module, t_i32, pos.column);
  9981. args[4] = lb_typeid(p->module, src_type);
  9982. args[5] = lb_typeid(p->module, dst_type);
  9983. lb_emit_runtime_call(p, "type_assertion_check", args);
  9984. lbValue data_ptr = v;
  9985. return lb_emit_conv(p, data_ptr, tv.type);
  9986. } else if (is_type_any(t)) {
  9987. lbValue v = e;
  9988. if (is_type_pointer(v.type)) {
  9989. v = lb_emit_load(p, v);
  9990. }
  9991. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  9992. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  9993. lbValue id = lb_typeid(p->module, type);
  9994. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  9995. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9996. args[0] = ok;
  9997. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  9998. args[2] = lb_const_int(p->module, t_i32, pos.line);
  9999. args[3] = lb_const_int(p->module, t_i32, pos.column);
  10000. args[4] = any_id;
  10001. args[5] = id;
  10002. lb_emit_runtime_call(p, "type_assertion_check", args);
  10003. return lb_emit_conv(p, data_ptr, tv.type);
  10004. } else {
  10005. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  10006. }
  10007. }
  10008. return lb_build_addr_ptr(p, ue->expr);
  10009. }
  10010. default:
  10011. {
  10012. lbValue v = lb_build_expr(p, ue->expr);
  10013. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  10014. }
  10015. }
  10016. case_end;
  10017. case_ast_node(be, BinaryExpr, expr);
  10018. return lb_build_binary_expr(p, expr);
  10019. case_end;
  10020. case_ast_node(pl, ProcLit, expr);
  10021. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  10022. case_end;
  10023. case_ast_node(cl, CompoundLit, expr);
  10024. return lb_addr_load(p, lb_build_addr(p, expr));
  10025. case_end;
  10026. case_ast_node(ce, CallExpr, expr);
  10027. lbValue res = lb_build_call_expr(p, expr);
  10028. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  10029. GB_ASSERT(is_type_tuple(res.type));
  10030. GB_ASSERT(res.type->Tuple.variables.count == 2);
  10031. return lb_emit_struct_ev(p, res, 0);
  10032. }
  10033. return res;
  10034. case_end;
  10035. case_ast_node(se, SliceExpr, expr);
  10036. if (is_type_slice(type_of_expr(se->expr))) {
  10037. // NOTE(bill): Quick optimization
  10038. if (se->high == nullptr &&
  10039. (se->low == nullptr || lb_is_expr_constant_zero(se->low))) {
  10040. return lb_build_expr(p, se->expr);
  10041. }
  10042. }
  10043. return lb_addr_load(p, lb_build_addr(p, expr));
  10044. case_end;
  10045. case_ast_node(ie, IndexExpr, expr);
  10046. return lb_addr_load(p, lb_build_addr(p, expr));
  10047. case_end;
  10048. case_ast_node(ia, InlineAsmExpr, expr);
  10049. Type *t = type_of_expr(expr);
  10050. GB_ASSERT(is_type_asm_proc(t));
  10051. String asm_string = {};
  10052. String constraints_string = {};
  10053. TypeAndValue tav;
  10054. tav = type_and_value_of_expr(ia->asm_string);
  10055. GB_ASSERT(is_type_string(tav.type));
  10056. GB_ASSERT(tav.value.kind == ExactValue_String);
  10057. asm_string = tav.value.value_string;
  10058. tav = type_and_value_of_expr(ia->constraints_string);
  10059. GB_ASSERT(is_type_string(tav.type));
  10060. GB_ASSERT(tav.value.kind == ExactValue_String);
  10061. constraints_string = tav.value.value_string;
  10062. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  10063. switch (ia->dialect) {
  10064. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  10065. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  10066. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  10067. default: GB_PANIC("Unhandled inline asm dialect"); break;
  10068. }
  10069. LLVMTypeRef func_type = LLVMGetElementType(lb_type(p->module, t));
  10070. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  10071. cast(char *)asm_string.text, cast(size_t)asm_string.len,
  10072. cast(char *)constraints_string.text, cast(size_t)constraints_string.len,
  10073. ia->has_side_effects, ia->is_align_stack, dialect
  10074. );
  10075. GB_ASSERT(the_asm != nullptr);
  10076. return {the_asm, t};
  10077. case_end;
  10078. }
  10079. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  10080. return {};
  10081. }
  10082. lbAddr lb_get_soa_variable_addr(lbProcedure *p, Entity *e) {
  10083. lbAddr *found = map_get(&p->module->soa_values, hash_entity(e));
  10084. GB_ASSERT(found != nullptr);
  10085. return *found;
  10086. }
  10087. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  10088. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  10089. String name = e->token.string;
  10090. Entity *parent = e->using_parent;
  10091. Selection sel = lookup_field(parent->type, name, false);
  10092. GB_ASSERT(sel.entity != nullptr);
  10093. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  10094. lbValue v = {};
  10095. if (pv == nullptr && parent->flags & EntityFlag_SoaPtrField) {
  10096. // NOTE(bill): using SOA value (probably from for-in statement)
  10097. lbAddr parent_addr = lb_get_soa_variable_addr(p, parent);
  10098. v = lb_addr_get_ptr(p, parent_addr);
  10099. } else if (pv != nullptr) {
  10100. v = *pv;
  10101. } else {
  10102. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  10103. v = lb_build_addr_ptr(p, e->using_expr);
  10104. }
  10105. GB_ASSERT(v.value != nullptr);
  10106. GB_ASSERT_MSG(parent->type == type_deref(v.type), "%s %s", type_to_string(parent->type), type_to_string(v.type));
  10107. lbValue ptr = lb_emit_deep_field_gep(p, v, sel);
  10108. if (parent->scope) {
  10109. if ((parent->scope->flags & (ScopeFlag_File|ScopeFlag_Pkg)) == 0) {
  10110. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  10111. }
  10112. } else {
  10113. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  10114. }
  10115. return ptr;
  10116. }
  10117. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  10118. GB_ASSERT(e != nullptr);
  10119. if (e->kind == Entity_Constant) {
  10120. Type *t = default_type(type_of_expr(expr));
  10121. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  10122. lbAddr g = lb_add_global_generated(p->module, t, v);
  10123. return g;
  10124. }
  10125. lbValue v = {};
  10126. lbValue *found = map_get(&p->module->values, hash_entity(e));
  10127. if (found) {
  10128. v = *found;
  10129. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  10130. // NOTE(bill): Calculate the using variable every time
  10131. v = lb_get_using_variable(p, e);
  10132. } else if (e->flags & EntityFlag_SoaPtrField) {
  10133. return lb_get_soa_variable_addr(p, e);
  10134. }
  10135. if (v.value == nullptr) {
  10136. return lb_addr(lb_find_value_from_entity(p->module, e));
  10137. // error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  10138. // LIT(p->name),
  10139. // LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  10140. // GB_PANIC("Unknown value");
  10141. }
  10142. return lb_addr(v);
  10143. }
  10144. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  10145. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  10146. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  10147. map_type = base_type(map_type);
  10148. GB_ASSERT(map_type->kind == Type_Map);
  10149. Type *key_type = map_type->Map.key;
  10150. Type *val_type = map_type->Map.value;
  10151. // NOTE(bill): Removes unnecessary allocation if split gep
  10152. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  10153. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  10154. lb_emit_store(p, gep0, m);
  10155. i64 entry_size = type_size_of (map_type->Map.entry_type);
  10156. i64 entry_align = type_align_of (map_type->Map.entry_type);
  10157. i64 key_offset = type_offset_of(map_type->Map.entry_type, 2);
  10158. i64 key_size = type_size_of (map_type->Map.key);
  10159. i64 value_offset = type_offset_of(map_type->Map.entry_type, 3);
  10160. i64 value_size = type_size_of (map_type->Map.value);
  10161. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_get_equal_proc_for_type(p->module, key_type));
  10162. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  10163. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  10164. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, key_offset));
  10165. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, key_size));
  10166. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 6), lb_const_int(p->module, t_uintptr, value_offset));
  10167. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 7), lb_const_int(p->module, t_int, value_size));
  10168. return lb_addr_load(p, h);
  10169. }
  10170. lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  10171. if (true) {
  10172. return {};
  10173. }
  10174. lbValue hashed_key = {};
  10175. if (lb_is_const(key)) {
  10176. u64 hash = 0xcbf29ce484222325;
  10177. if (is_type_cstring(key_type)) {
  10178. size_t length = 0;
  10179. char const *text = LLVMGetAsString(key.value, &length);
  10180. hash = fnv64a(text, cast(isize)length);
  10181. } else if (is_type_string(key_type)) {
  10182. unsigned data_indices[] = {0};
  10183. unsigned len_indices[] = {1};
  10184. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  10185. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  10186. isize length = LLVMConstIntGetSExtValue(len);
  10187. char const *text = nullptr;
  10188. if (false && length != 0) {
  10189. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  10190. return {};
  10191. }
  10192. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  10193. size_t ulength = 0;
  10194. text = LLVMGetAsString(data, &ulength);
  10195. gb_printf_err("%td %td %s\n", length, ulength, text);
  10196. length = gb_min(length, cast(isize)ulength);
  10197. }
  10198. hash = fnv64a(text, cast(isize)length);
  10199. } else {
  10200. return {};
  10201. }
  10202. // TODO(bill): other const hash types
  10203. if (build_context.word_size == 4) {
  10204. hash &= 0xffffffffull;
  10205. }
  10206. hashed_key = lb_const_int(m, t_uintptr, hash);
  10207. }
  10208. return hashed_key;
  10209. }
  10210. lbValue lb_gen_map_hash(lbProcedure *p, lbValue key, Type *key_type) {
  10211. Type *hash_type = t_u64;
  10212. lbAddr v = lb_add_local_generated(p, t_map_hash, true);
  10213. lbValue vp = lb_addr_get_ptr(p, v);
  10214. Type *t = base_type(key.type);
  10215. key = lb_emit_conv(p, key, key_type);
  10216. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  10217. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  10218. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  10219. if (hashed_key.value == nullptr) {
  10220. lbValue hasher = lb_get_hasher_proc_for_type(p->module, key_type);
  10221. auto args = array_make<lbValue>(permanent_allocator(), 2);
  10222. args[0] = key_ptr;
  10223. args[1] = lb_const_int(p->module, t_uintptr, 0);
  10224. hashed_key = lb_emit_call(p, hasher, args);
  10225. }
  10226. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_key);
  10227. lb_emit_store(p, lb_emit_struct_ep(p, vp, 1), key_ptr);
  10228. return lb_addr_load(p, v);
  10229. }
  10230. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  10231. lbValue map_key, lbValue map_value, Ast *node) {
  10232. map_type = base_type(map_type);
  10233. GB_ASSERT(map_type->kind == Type_Map);
  10234. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  10235. lbValue key = lb_gen_map_hash(p, map_key, map_type->Map.key);
  10236. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  10237. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  10238. lb_addr_store(p, value_addr, v);
  10239. auto args = array_make<lbValue>(permanent_allocator(), 4);
  10240. args[0] = h;
  10241. args[1] = key;
  10242. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  10243. args[3] = lb_emit_source_code_location(p, node);
  10244. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  10245. }
  10246. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  10247. expr = unparen_expr(expr);
  10248. switch (expr->kind) {
  10249. case_ast_node(i, Implicit, expr);
  10250. lbAddr v = {};
  10251. switch (i->kind) {
  10252. case Token_context:
  10253. v = lb_find_or_generate_context_ptr(p);
  10254. break;
  10255. }
  10256. GB_ASSERT(v.addr.value != nullptr);
  10257. return v;
  10258. case_end;
  10259. case_ast_node(i, Ident, expr);
  10260. if (is_blank_ident(expr)) {
  10261. lbAddr val = {};
  10262. return val;
  10263. }
  10264. String name = i->token.string;
  10265. Entity *e = entity_of_node(expr);
  10266. return lb_build_addr_from_entity(p, e, expr);
  10267. case_end;
  10268. case_ast_node(se, SelectorExpr, expr);
  10269. Ast *sel = unparen_expr(se->selector);
  10270. if (sel->kind == Ast_Ident) {
  10271. String selector = sel->Ident.token.string;
  10272. TypeAndValue tav = type_and_value_of_expr(se->expr);
  10273. if (tav.mode == Addressing_Invalid) {
  10274. // NOTE(bill): Imports
  10275. Entity *imp = entity_of_node(se->expr);
  10276. if (imp != nullptr) {
  10277. GB_ASSERT(imp->kind == Entity_ImportName);
  10278. }
  10279. return lb_build_addr(p, unparen_expr(se->selector));
  10280. }
  10281. Type *type = base_type(tav.type);
  10282. if (tav.mode == Addressing_Type) { // Addressing_Type
  10283. Selection sel = lookup_field(type, selector, true);
  10284. Entity *e = sel.entity;
  10285. GB_ASSERT_MSG(e->kind == Entity_Variable, "Entity_%.*s", LIT(entity_strings[e->kind]));
  10286. GB_ASSERT(e->flags & EntityFlag_TypeField);
  10287. String name = e->token.string;
  10288. /*if (name == "names") {
  10289. lbValue ti_ptr = lb_type_info(m, type);
  10290. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  10291. lbValue names_ptr = nullptr;
  10292. if (is_type_enum(type)) {
  10293. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  10294. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  10295. } else if (type->kind == Type_Struct) {
  10296. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  10297. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  10298. }
  10299. return ir_addr(names_ptr);
  10300. } else */{
  10301. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  10302. }
  10303. GB_PANIC("Unreachable");
  10304. }
  10305. Selection sel = lookup_field(type, selector, false);
  10306. GB_ASSERT(sel.entity != nullptr);
  10307. {
  10308. lbAddr addr = lb_build_addr(p, se->expr);
  10309. if (addr.kind == lbAddr_Map) {
  10310. lbValue v = lb_addr_load(p, addr);
  10311. lbValue a = lb_address_from_load_or_generate_local(p, v);
  10312. a = lb_emit_deep_field_gep(p, a, sel);
  10313. return lb_addr(a);
  10314. } else if (addr.kind == lbAddr_Context) {
  10315. GB_ASSERT(sel.index.count > 0);
  10316. if (addr.ctx.sel.index.count >= 0) {
  10317. sel = selection_combine(addr.ctx.sel, sel);
  10318. }
  10319. addr.ctx.sel = sel;
  10320. addr.kind = lbAddr_Context;
  10321. return addr;
  10322. } else if (addr.kind == lbAddr_SoaVariable) {
  10323. lbValue index = addr.soa.index;
  10324. i32 first_index = sel.index[0];
  10325. Selection sub_sel = sel;
  10326. sub_sel.index.data += 1;
  10327. sub_sel.index.count -= 1;
  10328. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  10329. Type *t = base_type(type_deref(addr.addr.type));
  10330. GB_ASSERT(is_type_soa_struct(t));
  10331. // TODO(bill): Bounds check
  10332. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  10333. lbValue len = lb_soa_struct_len(p, addr.addr);
  10334. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  10335. }
  10336. lbValue item = {};
  10337. if (t->Struct.soa_kind == StructSoa_Fixed) {
  10338. item = lb_emit_array_ep(p, arr, index);
  10339. } else {
  10340. item = lb_emit_ptr_offset(p, lb_emit_load(p, arr), index);
  10341. }
  10342. if (sub_sel.index.count > 0) {
  10343. item = lb_emit_deep_field_gep(p, item, sub_sel);
  10344. }
  10345. return lb_addr(item);
  10346. }
  10347. lbValue a = lb_addr_get_ptr(p, addr);
  10348. a = lb_emit_deep_field_gep(p, a, sel);
  10349. return lb_addr(a);
  10350. }
  10351. } else {
  10352. GB_PANIC("Unsupported selector expression");
  10353. }
  10354. case_end;
  10355. case_ast_node(se, SelectorCallExpr, expr);
  10356. GB_ASSERT(se->modified_call);
  10357. TypeAndValue tav = type_and_value_of_expr(expr);
  10358. GB_ASSERT(tav.mode != Addressing_Invalid);
  10359. return lb_build_addr(p, se->call);
  10360. case_end;
  10361. case_ast_node(ta, TypeAssertion, expr);
  10362. TokenPos pos = ast_token(expr).pos;
  10363. lbValue e = lb_build_expr(p, ta->expr);
  10364. Type *t = type_deref(e.type);
  10365. if (is_type_union(t)) {
  10366. Type *type = type_of_expr(expr);
  10367. lbAddr v = lb_add_local_generated(p, type, false);
  10368. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  10369. return v;
  10370. } else if (is_type_any(t)) {
  10371. Type *type = type_of_expr(expr);
  10372. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  10373. } else {
  10374. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  10375. }
  10376. case_end;
  10377. case_ast_node(ue, UnaryExpr, expr);
  10378. switch (ue->op.kind) {
  10379. case Token_And: {
  10380. return lb_build_addr(p, ue->expr);
  10381. }
  10382. default:
  10383. GB_PANIC("Invalid unary expression for lb_build_addr");
  10384. }
  10385. case_end;
  10386. case_ast_node(be, BinaryExpr, expr);
  10387. lbValue v = lb_build_expr(p, expr);
  10388. Type *t = v.type;
  10389. if (is_type_pointer(t)) {
  10390. return lb_addr(v);
  10391. }
  10392. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  10393. case_end;
  10394. case_ast_node(ie, IndexExpr, expr);
  10395. Type *t = base_type(type_of_expr(ie->expr));
  10396. bool deref = is_type_pointer(t);
  10397. t = base_type(type_deref(t));
  10398. if (is_type_soa_struct(t)) {
  10399. // SOA STRUCTURES!!!!
  10400. lbValue val = lb_build_addr_ptr(p, ie->expr);
  10401. if (deref) {
  10402. val = lb_emit_load(p, val);
  10403. }
  10404. lbValue index = lb_build_expr(p, ie->index);
  10405. return lb_addr_soa_variable(val, index, ie->index);
  10406. }
  10407. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  10408. // SOA Structures for slices/dynamic arrays
  10409. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  10410. lbValue field = lb_build_expr(p, ie->expr);
  10411. lbValue index = lb_build_expr(p, ie->index);
  10412. if (!build_context.no_bounds_check) {
  10413. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  10414. // GB_ASSERT(LLVMIsALoadInst(field.value));
  10415. // lbValue a = {};
  10416. // a.value = LLVMGetOperand(field.value, 0);
  10417. // a.type = alloc_type_pointer(field.type);
  10418. // irInstr *b = &a->Instr;
  10419. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  10420. // lbValue base_struct = b->StructElementPtr.address;
  10421. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  10422. // lbValue len = ir_soa_struct_len(p, base_struct);
  10423. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10424. }
  10425. lbValue val = lb_emit_ptr_offset(p, field, index);
  10426. return lb_addr(val);
  10427. }
  10428. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  10429. if (is_type_map(t)) {
  10430. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  10431. if (deref) {
  10432. map_val = lb_emit_load(p, map_val);
  10433. }
  10434. lbValue key = lb_build_expr(p, ie->index);
  10435. key = lb_emit_conv(p, key, t->Map.key);
  10436. Type *result_type = type_of_expr(expr);
  10437. return lb_addr_map(map_val, key, t, result_type);
  10438. }
  10439. switch (t->kind) {
  10440. case Type_Array: {
  10441. lbValue array = {};
  10442. array = lb_build_addr_ptr(p, ie->expr);
  10443. if (deref) {
  10444. array = lb_emit_load(p, array);
  10445. }
  10446. lbValue index = lb_build_expr(p, ie->index);
  10447. index = lb_emit_conv(p, index, t_int);
  10448. lbValue elem = lb_emit_array_ep(p, array, index);
  10449. auto index_tv = type_and_value_of_expr(ie->index);
  10450. if (index_tv.mode != Addressing_Constant) {
  10451. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  10452. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10453. }
  10454. return lb_addr(elem);
  10455. }
  10456. case Type_EnumeratedArray: {
  10457. lbValue array = {};
  10458. array = lb_build_addr_ptr(p, ie->expr);
  10459. if (deref) {
  10460. array = lb_emit_load(p, array);
  10461. }
  10462. Type *index_type = t->EnumeratedArray.index;
  10463. auto index_tv = type_and_value_of_expr(ie->index);
  10464. lbValue index = {};
  10465. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  10466. if (index_tv.mode == Addressing_Constant) {
  10467. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  10468. index = lb_const_value(p->module, index_type, idx);
  10469. } else {
  10470. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10471. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  10472. }
  10473. } else {
  10474. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10475. }
  10476. lbValue elem = lb_emit_array_ep(p, array, index);
  10477. if (index_tv.mode != Addressing_Constant) {
  10478. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  10479. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10480. }
  10481. return lb_addr(elem);
  10482. }
  10483. case Type_Slice: {
  10484. lbValue slice = {};
  10485. slice = lb_build_expr(p, ie->expr);
  10486. if (deref) {
  10487. slice = lb_emit_load(p, slice);
  10488. }
  10489. lbValue elem = lb_slice_elem(p, slice);
  10490. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10491. lbValue len = lb_slice_len(p, slice);
  10492. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10493. lbValue v = lb_emit_ptr_offset(p, elem, index);
  10494. return lb_addr(v);
  10495. }
  10496. case Type_RelativeSlice: {
  10497. lbAddr slice_addr = {};
  10498. if (deref) {
  10499. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  10500. } else {
  10501. slice_addr = lb_build_addr(p, ie->expr);
  10502. }
  10503. lbValue slice = lb_addr_load(p, slice_addr);
  10504. lbValue elem = lb_slice_elem(p, slice);
  10505. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10506. lbValue len = lb_slice_len(p, slice);
  10507. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10508. lbValue v = lb_emit_ptr_offset(p, elem, index);
  10509. return lb_addr(v);
  10510. }
  10511. case Type_DynamicArray: {
  10512. lbValue dynamic_array = {};
  10513. dynamic_array = lb_build_expr(p, ie->expr);
  10514. if (deref) {
  10515. dynamic_array = lb_emit_load(p, dynamic_array);
  10516. }
  10517. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  10518. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  10519. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10520. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10521. lbValue v = lb_emit_ptr_offset(p, elem, index);
  10522. return lb_addr(v);
  10523. }
  10524. case Type_Basic: { // Basic_string
  10525. lbValue str;
  10526. lbValue elem;
  10527. lbValue len;
  10528. lbValue index;
  10529. str = lb_build_expr(p, ie->expr);
  10530. if (deref) {
  10531. str = lb_emit_load(p, str);
  10532. }
  10533. elem = lb_string_elem(p, str);
  10534. len = lb_string_len(p, str);
  10535. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10536. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10537. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  10538. }
  10539. }
  10540. case_end;
  10541. case_ast_node(se, SliceExpr, expr);
  10542. lbValue low = lb_const_int(p->module, t_int, 0);
  10543. lbValue high = {};
  10544. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  10545. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  10546. bool no_indices = se->low == nullptr && se->high == nullptr;
  10547. lbAddr addr = lb_build_addr(p, se->expr);
  10548. lbValue base = lb_addr_load(p, addr);
  10549. Type *type = base_type(base.type);
  10550. if (is_type_pointer(type)) {
  10551. type = base_type(type_deref(type));
  10552. addr = lb_addr(base);
  10553. base = lb_addr_load(p, addr);
  10554. }
  10555. switch (type->kind) {
  10556. case Type_Slice: {
  10557. Type *slice_type = type;
  10558. lbValue len = lb_slice_len(p, base);
  10559. if (high.value == nullptr) high = len;
  10560. if (!no_indices) {
  10561. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10562. }
  10563. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  10564. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10565. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  10566. lb_fill_slice(p, slice, elem, new_len);
  10567. return slice;
  10568. }
  10569. case Type_RelativeSlice:
  10570. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  10571. break;
  10572. case Type_DynamicArray: {
  10573. Type *elem_type = type->DynamicArray.elem;
  10574. Type *slice_type = alloc_type_slice(elem_type);
  10575. lbValue len = lb_dynamic_array_len(p, base);
  10576. if (high.value == nullptr) high = len;
  10577. if (!no_indices) {
  10578. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10579. }
  10580. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  10581. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10582. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  10583. lb_fill_slice(p, slice, elem, new_len);
  10584. return slice;
  10585. }
  10586. case Type_Array: {
  10587. Type *slice_type = alloc_type_slice(type->Array.elem);
  10588. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  10589. if (high.value == nullptr) high = len;
  10590. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  10591. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  10592. if (!low_const || !high_const) {
  10593. if (!no_indices) {
  10594. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10595. }
  10596. }
  10597. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  10598. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10599. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  10600. lb_fill_slice(p, slice, elem, new_len);
  10601. return slice;
  10602. }
  10603. case Type_Basic: {
  10604. GB_ASSERT(type == t_string);
  10605. lbValue len = lb_string_len(p, base);
  10606. if (high.value == nullptr) high = len;
  10607. if (!no_indices) {
  10608. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10609. }
  10610. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  10611. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10612. lbAddr str = lb_add_local_generated(p, t_string, false);
  10613. lb_fill_string(p, str, elem, new_len);
  10614. return str;
  10615. }
  10616. case Type_Struct:
  10617. if (is_type_soa_struct(type)) {
  10618. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  10619. if (high.value == nullptr) high = len;
  10620. if (!no_indices) {
  10621. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10622. }
  10623. #if 1
  10624. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  10625. if (type->Struct.soa_kind == StructSoa_Fixed) {
  10626. i32 field_count = cast(i32)type->Struct.fields.count;
  10627. for (i32 i = 0; i < field_count; i++) {
  10628. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  10629. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  10630. field_src = lb_emit_array_ep(p, field_src, low);
  10631. lb_emit_store(p, field_dst, field_src);
  10632. }
  10633. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  10634. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10635. lb_emit_store(p, len_dst, new_len);
  10636. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  10637. if (no_indices) {
  10638. lb_addr_store(p, dst, base);
  10639. } else {
  10640. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  10641. for (i32 i = 0; i < field_count; i++) {
  10642. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  10643. lbValue field_src = lb_emit_struct_ev(p, base, i);
  10644. field_src = lb_emit_ptr_offset(p, field_src, low);
  10645. lb_emit_store(p, field_dst, field_src);
  10646. }
  10647. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  10648. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10649. lb_emit_store(p, len_dst, new_len);
  10650. }
  10651. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  10652. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  10653. for (i32 i = 0; i < field_count; i++) {
  10654. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  10655. lbValue field_src = lb_emit_struct_ev(p, base, i);
  10656. field_src = lb_emit_ptr_offset(p, field_src, low);
  10657. lb_emit_store(p, field_dst, field_src);
  10658. }
  10659. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  10660. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10661. lb_emit_store(p, len_dst, new_len);
  10662. }
  10663. return dst;
  10664. #endif
  10665. }
  10666. break;
  10667. }
  10668. GB_PANIC("Unknown slicable type");
  10669. case_end;
  10670. case_ast_node(de, DerefExpr, expr);
  10671. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  10672. lbAddr addr = lb_build_addr(p, de->expr);
  10673. addr.relative.deref = true;
  10674. return addr;\
  10675. }
  10676. lbValue addr = lb_build_expr(p, de->expr);
  10677. return lb_addr(addr);
  10678. case_end;
  10679. case_ast_node(ce, CallExpr, expr);
  10680. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  10681. lbValue e = lb_build_expr(p, expr);
  10682. #if 1
  10683. return lb_addr(lb_address_from_load_or_generate_local(p, e));
  10684. #else
  10685. lbAddr v = lb_add_local_generated(p, e.type, false);
  10686. lb_addr_store(p, v, e);
  10687. return v;
  10688. #endif
  10689. case_end;
  10690. case_ast_node(cl, CompoundLit, expr);
  10691. Type *type = type_of_expr(expr);
  10692. Type *bt = base_type(type);
  10693. lbAddr v = lb_add_local_generated(p, type, true);
  10694. Type *et = nullptr;
  10695. switch (bt->kind) {
  10696. case Type_Array: et = bt->Array.elem; break;
  10697. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  10698. case Type_Slice: et = bt->Slice.elem; break;
  10699. case Type_BitSet: et = bt->BitSet.elem; break;
  10700. case Type_SimdVector: et = bt->SimdVector.elem; break;
  10701. }
  10702. String proc_name = {};
  10703. if (p->entity) {
  10704. proc_name = p->entity->token.string;
  10705. }
  10706. TokenPos pos = ast_token(expr).pos;
  10707. switch (bt->kind) {
  10708. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  10709. case Type_Struct: {
  10710. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  10711. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  10712. bool is_raw_union = is_type_raw_union(bt);
  10713. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  10714. TypeStruct *st = &bt->Struct;
  10715. if (cl->elems.count > 0) {
  10716. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10717. for_array(field_index, cl->elems) {
  10718. Ast *elem = cl->elems[field_index];
  10719. lbValue field_expr = {};
  10720. Entity *field = nullptr;
  10721. isize index = field_index;
  10722. if (elem->kind == Ast_FieldValue) {
  10723. ast_node(fv, FieldValue, elem);
  10724. String name = fv->field->Ident.token.string;
  10725. Selection sel = lookup_field(bt, name, false);
  10726. index = sel.index[0];
  10727. elem = fv->value;
  10728. TypeAndValue tav = type_and_value_of_expr(elem);
  10729. } else {
  10730. TypeAndValue tav = type_and_value_of_expr(elem);
  10731. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  10732. index = sel.index[0];
  10733. }
  10734. field = st->fields[index];
  10735. Type *ft = field->type;
  10736. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  10737. continue;
  10738. }
  10739. field_expr = lb_build_expr(p, elem);
  10740. Type *fet = field_expr.type;
  10741. GB_ASSERT(fet->kind != Type_Tuple);
  10742. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  10743. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  10744. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  10745. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  10746. lb_emit_store_union_variant(p, gep, field_expr, fet);
  10747. } else {
  10748. lbValue fv = lb_emit_conv(p, field_expr, ft);
  10749. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  10750. lb_emit_store(p, gep, fv);
  10751. }
  10752. }
  10753. }
  10754. break;
  10755. }
  10756. case Type_Map: {
  10757. if (cl->elems.count == 0) {
  10758. break;
  10759. }
  10760. {
  10761. auto args = array_make<lbValue>(permanent_allocator(), 3);
  10762. args[0] = lb_gen_map_header(p, v.addr, type);
  10763. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  10764. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  10765. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  10766. }
  10767. for_array(field_index, cl->elems) {
  10768. Ast *elem = cl->elems[field_index];
  10769. ast_node(fv, FieldValue, elem);
  10770. lbValue key = lb_build_expr(p, fv->field);
  10771. lbValue value = lb_build_expr(p, fv->value);
  10772. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  10773. }
  10774. break;
  10775. }
  10776. case Type_Array: {
  10777. if (cl->elems.count > 0) {
  10778. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10779. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  10780. // NOTE(bill): Separate value, gep, store into their own chunks
  10781. for_array(i, cl->elems) {
  10782. Ast *elem = cl->elems[i];
  10783. if (elem->kind == Ast_FieldValue) {
  10784. ast_node(fv, FieldValue, elem);
  10785. if (lb_is_elem_const(fv->value, et)) {
  10786. continue;
  10787. }
  10788. if (is_ast_range(fv->field)) {
  10789. ast_node(ie, BinaryExpr, fv->field);
  10790. TypeAndValue lo_tav = ie->left->tav;
  10791. TypeAndValue hi_tav = ie->right->tav;
  10792. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10793. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10794. TokenKind op = ie->op.kind;
  10795. i64 lo = exact_value_to_i64(lo_tav.value);
  10796. i64 hi = exact_value_to_i64(hi_tav.value);
  10797. if (op != Token_RangeHalf) {
  10798. hi += 1;
  10799. }
  10800. lbValue value = lb_build_expr(p, fv->value);
  10801. for (i64 k = lo; k < hi; k++) {
  10802. lbCompoundLitElemTempData data = {};
  10803. data.value = value;
  10804. data.elem_index = cast(i32)k;
  10805. array_add(&temp_data, data);
  10806. }
  10807. } else {
  10808. auto tav = fv->field->tav;
  10809. GB_ASSERT(tav.mode == Addressing_Constant);
  10810. i64 index = exact_value_to_i64(tav.value);
  10811. lbValue value = lb_build_expr(p, fv->value);
  10812. lbCompoundLitElemTempData data = {};
  10813. data.value = lb_emit_conv(p, value, et);
  10814. data.expr = fv->value;
  10815. data.elem_index = cast(i32)index;
  10816. array_add(&temp_data, data);
  10817. }
  10818. } else {
  10819. if (lb_is_elem_const(elem, et)) {
  10820. continue;
  10821. }
  10822. lbCompoundLitElemTempData data = {};
  10823. data.expr = elem;
  10824. data.elem_index = cast(i32)i;
  10825. array_add(&temp_data, data);
  10826. }
  10827. }
  10828. for_array(i, temp_data) {
  10829. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  10830. }
  10831. for_array(i, temp_data) {
  10832. lbValue field_expr = temp_data[i].value;
  10833. Ast *expr = temp_data[i].expr;
  10834. auto prev_hint = lb_set_copy_elision_hint(p, lb_addr(temp_data[i].gep), expr);
  10835. if (field_expr.value == nullptr) {
  10836. field_expr = lb_build_expr(p, expr);
  10837. }
  10838. Type *t = field_expr.type;
  10839. GB_ASSERT(t->kind != Type_Tuple);
  10840. lbValue ev = lb_emit_conv(p, field_expr, et);
  10841. if (!p->copy_elision_hint.used) {
  10842. temp_data[i].value = ev;
  10843. }
  10844. lb_reset_copy_elision_hint(p, prev_hint);
  10845. }
  10846. for_array(i, temp_data) {
  10847. if (temp_data[i].value.value != nullptr) {
  10848. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10849. }
  10850. }
  10851. }
  10852. break;
  10853. }
  10854. case Type_EnumeratedArray: {
  10855. if (cl->elems.count > 0) {
  10856. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10857. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  10858. // NOTE(bill): Separate value, gep, store into their own chunks
  10859. for_array(i, cl->elems) {
  10860. Ast *elem = cl->elems[i];
  10861. if (elem->kind == Ast_FieldValue) {
  10862. ast_node(fv, FieldValue, elem);
  10863. if (lb_is_elem_const(fv->value, et)) {
  10864. continue;
  10865. }
  10866. if (is_ast_range(fv->field)) {
  10867. ast_node(ie, BinaryExpr, fv->field);
  10868. TypeAndValue lo_tav = ie->left->tav;
  10869. TypeAndValue hi_tav = ie->right->tav;
  10870. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10871. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10872. TokenKind op = ie->op.kind;
  10873. i64 lo = exact_value_to_i64(lo_tav.value);
  10874. i64 hi = exact_value_to_i64(hi_tav.value);
  10875. if (op != Token_RangeHalf) {
  10876. hi += 1;
  10877. }
  10878. lbValue value = lb_build_expr(p, fv->value);
  10879. for (i64 k = lo; k < hi; k++) {
  10880. lbCompoundLitElemTempData data = {};
  10881. data.value = value;
  10882. data.elem_index = cast(i32)k;
  10883. array_add(&temp_data, data);
  10884. }
  10885. } else {
  10886. auto tav = fv->field->tav;
  10887. GB_ASSERT(tav.mode == Addressing_Constant);
  10888. i64 index = exact_value_to_i64(tav.value);
  10889. lbValue value = lb_build_expr(p, fv->value);
  10890. lbCompoundLitElemTempData data = {};
  10891. data.value = lb_emit_conv(p, value, et);
  10892. data.expr = fv->value;
  10893. data.elem_index = cast(i32)index;
  10894. array_add(&temp_data, data);
  10895. }
  10896. } else {
  10897. if (lb_is_elem_const(elem, et)) {
  10898. continue;
  10899. }
  10900. lbCompoundLitElemTempData data = {};
  10901. data.expr = elem;
  10902. data.elem_index = cast(i32)i;
  10903. array_add(&temp_data, data);
  10904. }
  10905. }
  10906. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  10907. for_array(i, temp_data) {
  10908. i32 index = temp_data[i].elem_index - index_offset;
  10909. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  10910. }
  10911. for_array(i, temp_data) {
  10912. lbValue field_expr = temp_data[i].value;
  10913. Ast *expr = temp_data[i].expr;
  10914. auto prev_hint = lb_set_copy_elision_hint(p, lb_addr(temp_data[i].gep), expr);
  10915. if (field_expr.value == nullptr) {
  10916. field_expr = lb_build_expr(p, expr);
  10917. }
  10918. Type *t = field_expr.type;
  10919. GB_ASSERT(t->kind != Type_Tuple);
  10920. lbValue ev = lb_emit_conv(p, field_expr, et);
  10921. if (!p->copy_elision_hint.used) {
  10922. temp_data[i].value = ev;
  10923. }
  10924. lb_reset_copy_elision_hint(p, prev_hint);
  10925. }
  10926. for_array(i, temp_data) {
  10927. if (temp_data[i].value.value != nullptr) {
  10928. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10929. }
  10930. }
  10931. }
  10932. break;
  10933. }
  10934. case Type_Slice: {
  10935. if (cl->elems.count > 0) {
  10936. Type *elem_type = bt->Slice.elem;
  10937. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  10938. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  10939. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  10940. lbValue data = lb_slice_elem(p, slice);
  10941. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  10942. for_array(i, cl->elems) {
  10943. Ast *elem = cl->elems[i];
  10944. if (elem->kind == Ast_FieldValue) {
  10945. ast_node(fv, FieldValue, elem);
  10946. if (lb_is_elem_const(fv->value, et)) {
  10947. continue;
  10948. }
  10949. if (is_ast_range(fv->field)) {
  10950. ast_node(ie, BinaryExpr, fv->field);
  10951. TypeAndValue lo_tav = ie->left->tav;
  10952. TypeAndValue hi_tav = ie->right->tav;
  10953. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10954. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10955. TokenKind op = ie->op.kind;
  10956. i64 lo = exact_value_to_i64(lo_tav.value);
  10957. i64 hi = exact_value_to_i64(hi_tav.value);
  10958. if (op != Token_RangeHalf) {
  10959. hi += 1;
  10960. }
  10961. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  10962. for (i64 k = lo; k < hi; k++) {
  10963. lbCompoundLitElemTempData data = {};
  10964. data.value = value;
  10965. data.elem_index = cast(i32)k;
  10966. array_add(&temp_data, data);
  10967. }
  10968. } else {
  10969. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  10970. i64 index = exact_value_to_i64(fv->field->tav.value);
  10971. lbValue field_expr = lb_build_expr(p, fv->value);
  10972. GB_ASSERT(!is_type_tuple(field_expr.type));
  10973. lbValue ev = lb_emit_conv(p, field_expr, et);
  10974. lbCompoundLitElemTempData data = {};
  10975. data.value = ev;
  10976. data.elem_index = cast(i32)index;
  10977. array_add(&temp_data, data);
  10978. }
  10979. } else {
  10980. if (lb_is_elem_const(elem, et)) {
  10981. continue;
  10982. }
  10983. lbValue field_expr = lb_build_expr(p, elem);
  10984. GB_ASSERT(!is_type_tuple(field_expr.type));
  10985. lbValue ev = lb_emit_conv(p, field_expr, et);
  10986. lbCompoundLitElemTempData data = {};
  10987. data.value = ev;
  10988. data.elem_index = cast(i32)i;
  10989. array_add(&temp_data, data);
  10990. }
  10991. }
  10992. for_array(i, temp_data) {
  10993. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  10994. }
  10995. for_array(i, temp_data) {
  10996. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10997. }
  10998. {
  10999. lbValue count = {};
  11000. count.type = t_int;
  11001. if (lb_is_const(slice)) {
  11002. unsigned indices[1] = {1};
  11003. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  11004. } else {
  11005. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  11006. }
  11007. lb_fill_slice(p, v, data, count);
  11008. }
  11009. }
  11010. break;
  11011. }
  11012. case Type_DynamicArray: {
  11013. if (cl->elems.count == 0) {
  11014. break;
  11015. }
  11016. Type *et = bt->DynamicArray.elem;
  11017. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  11018. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  11019. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  11020. {
  11021. auto args = array_make<lbValue>(permanent_allocator(), 5);
  11022. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  11023. args[1] = size;
  11024. args[2] = align;
  11025. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  11026. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  11027. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  11028. }
  11029. lbValue items = lb_generate_local_array(p, et, item_count);
  11030. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  11031. for_array(i, cl->elems) {
  11032. Ast *elem = cl->elems[i];
  11033. if (elem->kind == Ast_FieldValue) {
  11034. ast_node(fv, FieldValue, elem);
  11035. if (is_ast_range(fv->field)) {
  11036. ast_node(ie, BinaryExpr, fv->field);
  11037. TypeAndValue lo_tav = ie->left->tav;
  11038. TypeAndValue hi_tav = ie->right->tav;
  11039. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  11040. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  11041. TokenKind op = ie->op.kind;
  11042. i64 lo = exact_value_to_i64(lo_tav.value);
  11043. i64 hi = exact_value_to_i64(hi_tav.value);
  11044. if (op != Token_RangeHalf) {
  11045. hi += 1;
  11046. }
  11047. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  11048. for (i64 k = lo; k < hi; k++) {
  11049. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  11050. lb_emit_store(p, ep, value);
  11051. }
  11052. } else {
  11053. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  11054. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  11055. lbValue ev = lb_build_expr(p, fv->value);
  11056. lbValue value = lb_emit_conv(p, ev, et);
  11057. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  11058. lb_emit_store(p, ep, value);
  11059. }
  11060. } else {
  11061. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  11062. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  11063. lb_emit_store(p, ep, value);
  11064. }
  11065. }
  11066. {
  11067. auto args = array_make<lbValue>(permanent_allocator(), 6);
  11068. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  11069. args[1] = size;
  11070. args[2] = align;
  11071. args[3] = lb_emit_conv(p, items, t_rawptr);
  11072. args[4] = lb_const_int(p->module, t_int, item_count);
  11073. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  11074. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  11075. }
  11076. break;
  11077. }
  11078. case Type_Basic: {
  11079. GB_ASSERT(is_type_any(bt));
  11080. if (cl->elems.count > 0) {
  11081. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  11082. String field_names[2] = {
  11083. str_lit("data"),
  11084. str_lit("id"),
  11085. };
  11086. Type *field_types[2] = {
  11087. t_rawptr,
  11088. t_typeid,
  11089. };
  11090. for_array(field_index, cl->elems) {
  11091. Ast *elem = cl->elems[field_index];
  11092. lbValue field_expr = {};
  11093. isize index = field_index;
  11094. if (elem->kind == Ast_FieldValue) {
  11095. ast_node(fv, FieldValue, elem);
  11096. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  11097. index = sel.index[0];
  11098. elem = fv->value;
  11099. } else {
  11100. TypeAndValue tav = type_and_value_of_expr(elem);
  11101. Selection sel = lookup_field(bt, field_names[field_index], false);
  11102. index = sel.index[0];
  11103. }
  11104. field_expr = lb_build_expr(p, elem);
  11105. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  11106. Type *ft = field_types[index];
  11107. lbValue fv = lb_emit_conv(p, field_expr, ft);
  11108. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  11109. lb_emit_store(p, gep, fv);
  11110. }
  11111. }
  11112. break;
  11113. }
  11114. case Type_BitSet: {
  11115. i64 sz = type_size_of(type);
  11116. if (cl->elems.count > 0 && sz > 0) {
  11117. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  11118. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  11119. for_array(i, cl->elems) {
  11120. Ast *elem = cl->elems[i];
  11121. GB_ASSERT(elem->kind != Ast_FieldValue);
  11122. if (lb_is_elem_const(elem, et)) {
  11123. continue;
  11124. }
  11125. lbValue expr = lb_build_expr(p, elem);
  11126. GB_ASSERT(expr.type->kind != Type_Tuple);
  11127. Type *it = bit_set_to_int(bt);
  11128. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  11129. lbValue e = lb_emit_conv(p, expr, it);
  11130. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  11131. e = lb_emit_arith(p, Token_Shl, one, e, it);
  11132. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  11133. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  11134. new_value = lb_emit_transmute(p, new_value, type);
  11135. lb_addr_store(p, v, new_value);
  11136. }
  11137. }
  11138. break;
  11139. }
  11140. }
  11141. return v;
  11142. case_end;
  11143. case_ast_node(tc, TypeCast, expr);
  11144. Type *type = type_of_expr(expr);
  11145. lbValue x = lb_build_expr(p, tc->expr);
  11146. lbValue e = {};
  11147. switch (tc->token.kind) {
  11148. case Token_cast:
  11149. e = lb_emit_conv(p, x, type);
  11150. break;
  11151. case Token_transmute:
  11152. e = lb_emit_transmute(p, x, type);
  11153. break;
  11154. default:
  11155. GB_PANIC("Invalid AST TypeCast");
  11156. }
  11157. lbAddr v = lb_add_local_generated(p, type, false);
  11158. lb_addr_store(p, v, e);
  11159. return v;
  11160. case_end;
  11161. case_ast_node(ac, AutoCast, expr);
  11162. return lb_build_addr(p, ac->expr);
  11163. case_end;
  11164. }
  11165. TokenPos token_pos = ast_token(expr).pos;
  11166. GB_PANIC("Unexpected address expression\n"
  11167. "\tAst: %.*s @ "
  11168. "%s\n",
  11169. LIT(ast_strings[expr->kind]),
  11170. token_pos_to_string(token_pos));
  11171. return {};
  11172. }
  11173. void lb_init_module(lbModule *m, Checker *c) {
  11174. m->info = &c->info;
  11175. gbString module_name = gb_string_make(heap_allocator(), "odin_package");
  11176. if (m->pkg) {
  11177. module_name = gb_string_appendc(module_name, "-");
  11178. module_name = gb_string_append_length(module_name, m->pkg->name.text, m->pkg->name.len);
  11179. } else if (USE_SEPARTE_MODULES) {
  11180. module_name = gb_string_appendc(module_name, "-builtin");
  11181. }
  11182. m->ctx = LLVMContextCreate();
  11183. m->mod = LLVMModuleCreateWithNameInContext(module_name ? module_name : "odin_package", m->ctx);
  11184. // m->debug_builder = nullptr;
  11185. if (build_context.ODIN_DEBUG) {
  11186. enum {DEBUG_METADATA_VERSION = 3};
  11187. LLVMMetadataRef debug_ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), DEBUG_METADATA_VERSION, true));
  11188. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "Debug Info Version", 18, debug_ref);
  11189. switch (build_context.metrics.os) {
  11190. case TargetOs_windows:
  11191. LLVMAddModuleFlag(m->mod,
  11192. LLVMModuleFlagBehaviorWarning,
  11193. "CodeView", 8,
  11194. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 1, true)));
  11195. break;
  11196. case TargetOs_darwin:
  11197. // NOTE(bill): Darwin only supports DWARF2 (that I know of)
  11198. LLVMAddModuleFlag(m->mod,
  11199. LLVMModuleFlagBehaviorWarning,
  11200. "Dwarf Version", 13,
  11201. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 2, true)));
  11202. break;
  11203. }
  11204. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  11205. }
  11206. gbAllocator a = heap_allocator();
  11207. map_init(&m->types, a);
  11208. map_init(&m->llvm_types, a);
  11209. map_init(&m->values, a);
  11210. map_init(&m->soa_values, a);
  11211. string_map_init(&m->members, a);
  11212. map_init(&m->procedure_values, a);
  11213. string_map_init(&m->procedures, a);
  11214. string_map_init(&m->const_strings, a);
  11215. map_init(&m->anonymous_proc_lits, a);
  11216. map_init(&m->function_type_map, a);
  11217. map_init(&m->equal_procs, a);
  11218. map_init(&m->hasher_procs, a);
  11219. array_init(&m->procedures_to_generate, a, 0, 1024);
  11220. array_init(&m->foreign_library_paths, a, 0, 1024);
  11221. map_init(&m->debug_values, a);
  11222. array_init(&m->debug_incomplete_types, a, 0, 1024);
  11223. }
  11224. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  11225. if (global_error_collector.count != 0) {
  11226. return false;
  11227. }
  11228. isize tc = c->parser->total_token_count;
  11229. if (tc < 2) {
  11230. return false;
  11231. }
  11232. String init_fullpath = c->parser->init_fullpath;
  11233. if (build_context.out_filepath.len == 0) {
  11234. gen->output_name = remove_directory_from_path(init_fullpath);
  11235. gen->output_name = remove_extension_from_path(gen->output_name);
  11236. gen->output_name = string_trim_whitespace(gen->output_name);
  11237. if (gen->output_name.len == 0) {
  11238. gen->output_name = c->info.init_scope->pkg->name;
  11239. }
  11240. gen->output_base = gen->output_name;
  11241. } else {
  11242. gen->output_name = build_context.out_filepath;
  11243. gen->output_name = string_trim_whitespace(gen->output_name);
  11244. if (gen->output_name.len == 0) {
  11245. gen->output_name = c->info.init_scope->pkg->name;
  11246. }
  11247. isize pos = string_extension_position(gen->output_name);
  11248. if (pos < 0) {
  11249. gen->output_base = gen->output_name;
  11250. } else {
  11251. gen->output_base = substring(gen->output_name, 0, pos);
  11252. }
  11253. }
  11254. gbAllocator ha = heap_allocator();
  11255. array_init(&gen->output_object_paths, ha);
  11256. array_init(&gen->output_temp_paths, ha);
  11257. gen->output_base = path_to_full_path(ha, gen->output_base);
  11258. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  11259. output_file_path = gb_string_appendc(output_file_path, ".obj");
  11260. defer (gb_string_free(output_file_path));
  11261. gen->info = &c->info;
  11262. map_init(&gen->modules, permanent_allocator(), gen->info->packages.entries.count*2);
  11263. map_init(&gen->modules_through_ctx, permanent_allocator(), gen->info->packages.entries.count*2);
  11264. map_init(&gen->anonymous_proc_lits, heap_allocator(), 1024);
  11265. gb_mutex_init(&gen->mutex);
  11266. if (USE_SEPARTE_MODULES) {
  11267. for_array(i, gen->info->packages.entries) {
  11268. AstPackage *pkg = gen->info->packages.entries[i].value;
  11269. auto m = gb_alloc_item(permanent_allocator(), lbModule);
  11270. m->pkg = pkg;
  11271. m->gen = gen;
  11272. map_set(&gen->modules, hash_pointer(pkg), m);
  11273. lb_init_module(m, c);
  11274. }
  11275. }
  11276. gen->default_module.gen = gen;
  11277. map_set(&gen->modules, hash_pointer(nullptr), &gen->default_module);
  11278. lb_init_module(&gen->default_module, c);
  11279. for_array(i, gen->modules.entries) {
  11280. lbModule *m = gen->modules.entries[i].value;
  11281. LLVMContextRef ctx = LLVMGetModuleContext(m->mod);
  11282. map_set(&gen->modules_through_ctx, hash_pointer(ctx), m);
  11283. }
  11284. return true;
  11285. }
  11286. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  11287. GB_ASSERT(type != nullptr);
  11288. type = default_type(type);
  11289. isize max_len = 7+8+1;
  11290. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  11291. u32 id = cast(u32)gb_atomic32_fetch_add(&m->gen->global_generated_index, 1);
  11292. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", id);
  11293. String name = make_string(str, len-1);
  11294. Scope *scope = nullptr;
  11295. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  11296. lbValue g = {};
  11297. g.type = alloc_type_pointer(type);
  11298. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  11299. if (value.value != nullptr) {
  11300. GB_ASSERT_MSG(LLVMIsConstant(value.value), LLVMPrintValueToString(value.value));
  11301. LLVMSetInitializer(g.value, value.value);
  11302. } else {
  11303. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  11304. }
  11305. lb_add_entity(m, e, g);
  11306. lb_add_member(m, name, g);
  11307. return lb_addr(g);
  11308. }
  11309. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  11310. AstPackage *p = m->info->runtime_package;
  11311. Entity *e = scope_lookup_current(p->scope, name);
  11312. return lb_find_value_from_entity(m, e);
  11313. }
  11314. lbValue lb_find_package_value(lbModule *m, String const &pkg, String const &name) {
  11315. Entity *e = find_entity_in_pkg(m->info, pkg, name);
  11316. lbValue *found = map_get(&m->values, hash_entity(e));
  11317. return lb_find_value_from_entity(m, e);
  11318. }
  11319. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  11320. i32 index = cast(i32)lb_type_info_index(m->info, type);
  11321. GB_ASSERT(index >= 0);
  11322. // gb_printf_err("%d %s\n", index, type_to_string(type));
  11323. LLVMValueRef indices[2] = {
  11324. LLVMConstInt(lb_type(m, t_int), 0, false),
  11325. LLVMConstInt(lb_type(m, t_int), index, false),
  11326. };
  11327. lbValue res = {};
  11328. res.type = t_type_info_ptr;
  11329. res.value = LLVMConstGEP(lb_global_type_info_data_ptr(m).value, indices, cast(unsigned)gb_count_of(indices));
  11330. return res;
  11331. }
  11332. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  11333. GB_ASSERT(p->module == &p->module->gen->default_module);
  11334. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  11335. lb_global_type_info_member_types_index += cast(i32)count;
  11336. return offset;
  11337. }
  11338. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  11339. GB_ASSERT(p->module == &p->module->gen->default_module);
  11340. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  11341. lb_global_type_info_member_names_index += cast(i32)count;
  11342. return offset;
  11343. }
  11344. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  11345. GB_ASSERT(p->module == &p->module->gen->default_module);
  11346. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  11347. lb_global_type_info_member_offsets_index += cast(i32)count;
  11348. return offset;
  11349. }
  11350. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  11351. GB_ASSERT(p->module == &p->module->gen->default_module);
  11352. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  11353. lb_global_type_info_member_usings_index += cast(i32)count;
  11354. return offset;
  11355. }
  11356. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  11357. GB_ASSERT(p->module == &p->module->gen->default_module);
  11358. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  11359. lb_global_type_info_member_tags_index += cast(i32)count;
  11360. return offset;
  11361. }
  11362. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  11363. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  11364. return lb_addr_get_ptr(p, addr);
  11365. }
  11366. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  11367. Token token = {Token_Ident};
  11368. isize name_len = prefix.len + 1 + 20;
  11369. auto suffix_id = cast(unsigned long long)id;
  11370. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  11371. gb_snprintf(text, name_len,
  11372. "%.*s-%llu", LIT(prefix), suffix_id);
  11373. text[name_len] = 0;
  11374. String s = make_string_c(text);
  11375. Type *t = alloc_type_array(elem_type, count);
  11376. lbValue g = {};
  11377. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  11378. g.type = alloc_type_pointer(t);
  11379. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  11380. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  11381. string_map_set(&m->members, s, g);
  11382. return g;
  11383. }
  11384. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  11385. lbModule *m = p->module;
  11386. LLVMContextRef ctx = m->ctx;
  11387. CheckerInfo *info = m->info;
  11388. {
  11389. // NOTE(bill): Set the type_table slice with the global backing array
  11390. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  11391. Type *type = base_type(lb_global_type_info_data_entity->type);
  11392. GB_ASSERT(is_type_array(type));
  11393. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  11394. LLVMValueRef values[2] = {
  11395. LLVMConstInBoundsGEP(lb_global_type_info_data_ptr(m).value, indices, gb_count_of(indices)),
  11396. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  11397. };
  11398. LLVMValueRef slice = llvm_const_named_struct(llvm_addr_type(global_type_table), values, gb_count_of(values));
  11399. LLVMSetInitializer(global_type_table.value, slice);
  11400. }
  11401. // Useful types
  11402. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  11403. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  11404. Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags"));
  11405. Type *t_type_info_flags = type_info_flags_entity->type;
  11406. i32 type_info_member_types_index = 0;
  11407. i32 type_info_member_names_index = 0;
  11408. i32 type_info_member_offsets_index = 0;
  11409. for_array(type_info_type_index, info->type_info_types) {
  11410. Type *t = info->type_info_types[type_info_type_index];
  11411. if (t == nullptr || t == t_invalid) {
  11412. continue;
  11413. }
  11414. isize entry_index = lb_type_info_index(info, t, false);
  11415. if (entry_index <= 0) {
  11416. continue;
  11417. }
  11418. lbValue tag = {};
  11419. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data_ptr(m), cast(i32)entry_index);
  11420. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 4);
  11421. lbValue type_info_flags = lb_const_int(p->module, t_type_info_flags, type_info_flags_of_type(t));
  11422. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  11423. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  11424. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), type_info_flags);
  11425. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 3), lb_typeid(m, t));
  11426. switch (t->kind) {
  11427. case Type_Named: {
  11428. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  11429. LLVMValueRef pkg_name = nullptr;
  11430. if (t->Named.type_name->pkg) {
  11431. pkg_name = lb_const_string(m, t->Named.type_name->pkg->name).value;
  11432. } else {
  11433. pkg_name = LLVMConstNull(lb_type(m, t_string));
  11434. }
  11435. String proc_name = {};
  11436. if (t->Named.type_name->parent_proc_decl) {
  11437. DeclInfo *decl = t->Named.type_name->parent_proc_decl;
  11438. if (decl->entity && decl->entity->kind == Entity_Procedure) {
  11439. proc_name = decl->entity->token.string;
  11440. }
  11441. }
  11442. TokenPos pos = t->Named.type_name->token.pos;
  11443. lbValue loc = lb_emit_source_code_location(p, proc_name, pos);
  11444. LLVMValueRef vals[4] = {
  11445. lb_const_string(p->module, t->Named.type_name->token.string).value,
  11446. lb_get_type_info_ptr(m, t->Named.base).value,
  11447. pkg_name,
  11448. loc.value
  11449. };
  11450. lbValue res = {};
  11451. res.type = type_deref(tag.type);
  11452. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11453. lb_emit_store(p, tag, res);
  11454. break;
  11455. }
  11456. case Type_Basic:
  11457. switch (t->Basic.kind) {
  11458. case Basic_bool:
  11459. case Basic_b8:
  11460. case Basic_b16:
  11461. case Basic_b32:
  11462. case Basic_b64:
  11463. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  11464. break;
  11465. case Basic_i8:
  11466. case Basic_u8:
  11467. case Basic_i16:
  11468. case Basic_u16:
  11469. case Basic_i32:
  11470. case Basic_u32:
  11471. case Basic_i64:
  11472. case Basic_u64:
  11473. case Basic_i128:
  11474. case Basic_u128:
  11475. case Basic_i16le:
  11476. case Basic_u16le:
  11477. case Basic_i32le:
  11478. case Basic_u32le:
  11479. case Basic_i64le:
  11480. case Basic_u64le:
  11481. case Basic_i128le:
  11482. case Basic_u128le:
  11483. case Basic_i16be:
  11484. case Basic_u16be:
  11485. case Basic_i32be:
  11486. case Basic_u32be:
  11487. case Basic_i64be:
  11488. case Basic_u64be:
  11489. case Basic_i128be:
  11490. case Basic_u128be:
  11491. case Basic_int:
  11492. case Basic_uint:
  11493. case Basic_uintptr: {
  11494. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  11495. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  11496. // NOTE(bill): This is matches the runtime layout
  11497. u8 endianness_value = 0;
  11498. if (t->Basic.flags & BasicFlag_EndianLittle) {
  11499. endianness_value = 1;
  11500. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  11501. endianness_value = 2;
  11502. }
  11503. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  11504. LLVMValueRef vals[2] = {
  11505. is_signed.value,
  11506. endianness.value,
  11507. };
  11508. lbValue res = {};
  11509. res.type = type_deref(tag.type);
  11510. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11511. lb_emit_store(p, tag, res);
  11512. break;
  11513. }
  11514. case Basic_rune:
  11515. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  11516. break;
  11517. case Basic_f16:
  11518. case Basic_f32:
  11519. case Basic_f64:
  11520. case Basic_f16le:
  11521. case Basic_f32le:
  11522. case Basic_f64le:
  11523. case Basic_f16be:
  11524. case Basic_f32be:
  11525. case Basic_f64be:
  11526. {
  11527. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  11528. // NOTE(bill): This is matches the runtime layout
  11529. u8 endianness_value = 0;
  11530. if (t->Basic.flags & BasicFlag_EndianLittle) {
  11531. endianness_value = 1;
  11532. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  11533. endianness_value = 2;
  11534. }
  11535. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  11536. LLVMValueRef vals[1] = {
  11537. endianness.value,
  11538. };
  11539. lbValue res = {};
  11540. res.type = type_deref(tag.type);
  11541. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11542. lb_emit_store(p, tag, res);
  11543. }
  11544. break;
  11545. case Basic_complex32:
  11546. case Basic_complex64:
  11547. case Basic_complex128:
  11548. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  11549. break;
  11550. case Basic_quaternion64:
  11551. case Basic_quaternion128:
  11552. case Basic_quaternion256:
  11553. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  11554. break;
  11555. case Basic_rawptr:
  11556. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  11557. break;
  11558. case Basic_string:
  11559. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  11560. break;
  11561. case Basic_cstring:
  11562. {
  11563. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  11564. LLVMValueRef vals[1] = {
  11565. lb_const_bool(m, t_bool, true).value,
  11566. };
  11567. lbValue res = {};
  11568. res.type = type_deref(tag.type);
  11569. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11570. lb_emit_store(p, tag, res);
  11571. }
  11572. break;
  11573. case Basic_any:
  11574. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  11575. break;
  11576. case Basic_typeid:
  11577. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  11578. break;
  11579. }
  11580. break;
  11581. case Type_Pointer: {
  11582. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  11583. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  11584. LLVMValueRef vals[1] = {
  11585. gep.value,
  11586. };
  11587. lbValue res = {};
  11588. res.type = type_deref(tag.type);
  11589. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11590. lb_emit_store(p, tag, res);
  11591. break;
  11592. }
  11593. case Type_Array: {
  11594. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  11595. i64 ez = type_size_of(t->Array.elem);
  11596. LLVMValueRef vals[3] = {
  11597. lb_get_type_info_ptr(m, t->Array.elem).value,
  11598. lb_const_int(m, t_int, ez).value,
  11599. lb_const_int(m, t_int, t->Array.count).value,
  11600. };
  11601. lbValue res = {};
  11602. res.type = type_deref(tag.type);
  11603. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11604. lb_emit_store(p, tag, res);
  11605. break;
  11606. }
  11607. case Type_EnumeratedArray: {
  11608. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  11609. LLVMValueRef vals[6] = {
  11610. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  11611. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  11612. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  11613. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  11614. // Unions
  11615. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  11616. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  11617. };
  11618. lbValue res = {};
  11619. res.type = type_deref(tag.type);
  11620. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11621. lb_emit_store(p, tag, res);
  11622. // NOTE(bill): Union assignment
  11623. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  11624. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  11625. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  11626. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  11627. lb_emit_store(p, min_value, min_v);
  11628. lb_emit_store(p, max_value, max_v);
  11629. break;
  11630. }
  11631. case Type_DynamicArray: {
  11632. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  11633. LLVMValueRef vals[2] = {
  11634. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  11635. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  11636. };
  11637. lbValue res = {};
  11638. res.type = type_deref(tag.type);
  11639. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11640. lb_emit_store(p, tag, res);
  11641. break;
  11642. }
  11643. case Type_Slice: {
  11644. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  11645. LLVMValueRef vals[2] = {
  11646. lb_get_type_info_ptr(m, t->Slice.elem).value,
  11647. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  11648. };
  11649. lbValue res = {};
  11650. res.type = type_deref(tag.type);
  11651. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11652. lb_emit_store(p, tag, res);
  11653. break;
  11654. }
  11655. case Type_Proc: {
  11656. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  11657. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  11658. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  11659. if (t->Proc.params != nullptr) {
  11660. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  11661. }
  11662. if (t->Proc.results != nullptr) {
  11663. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  11664. }
  11665. LLVMValueRef vals[4] = {
  11666. params,
  11667. results,
  11668. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  11669. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  11670. };
  11671. lbValue res = {};
  11672. res.type = type_deref(tag.type);
  11673. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11674. lb_emit_store(p, tag, res);
  11675. break;
  11676. }
  11677. case Type_Tuple: {
  11678. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  11679. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  11680. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  11681. for_array(i, t->Tuple.variables) {
  11682. // NOTE(bill): offset is not used for tuples
  11683. Entity *f = t->Tuple.variables[i];
  11684. lbValue index = lb_const_int(m, t_int, i);
  11685. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  11686. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  11687. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  11688. if (f->token.string.len > 0) {
  11689. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  11690. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  11691. }
  11692. }
  11693. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  11694. LLVMValueRef types_slice = llvm_const_slice(m, memory_types, count);
  11695. LLVMValueRef names_slice = llvm_const_slice(m, memory_names, count);
  11696. LLVMValueRef vals[2] = {
  11697. types_slice,
  11698. names_slice,
  11699. };
  11700. lbValue res = {};
  11701. res.type = type_deref(tag.type);
  11702. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11703. lb_emit_store(p, tag, res);
  11704. break;
  11705. }
  11706. case Type_Enum:
  11707. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  11708. {
  11709. GB_ASSERT(t->Enum.base_type != nullptr);
  11710. // GB_ASSERT_MSG(type_size_of(t_type_info_enum_value) == 16, "%lld == 16", cast(long long)type_size_of(t_type_info_enum_value));
  11711. LLVMValueRef vals[3] = {};
  11712. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  11713. if (t->Enum.fields.count > 0) {
  11714. auto fields = t->Enum.fields;
  11715. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  11716. str_lit("$enum_names"), cast(i64)entry_index);
  11717. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  11718. str_lit("$enum_values"), cast(i64)entry_index);
  11719. LLVMValueRef *name_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  11720. LLVMValueRef *value_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  11721. GB_ASSERT(is_type_integer(t->Enum.base_type));
  11722. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  11723. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  11724. for_array(i, fields) {
  11725. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  11726. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  11727. }
  11728. LLVMValueRef name_init = llvm_const_array(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  11729. LLVMValueRef value_init = llvm_const_array(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  11730. LLVMSetInitializer(name_array.value, name_init);
  11731. LLVMSetInitializer(value_array.value, value_init);
  11732. lbValue v_count = lb_const_int(m, t_int, fields.count);
  11733. vals[1] = llvm_const_slice(m, lb_array_elem(p, name_array), v_count);
  11734. vals[2] = llvm_const_slice(m, lb_array_elem(p, value_array), v_count);
  11735. } else {
  11736. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  11737. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  11738. }
  11739. lbValue res = {};
  11740. res.type = type_deref(tag.type);
  11741. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11742. lb_emit_store(p, tag, res);
  11743. }
  11744. break;
  11745. case Type_Union: {
  11746. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  11747. {
  11748. LLVMValueRef vals[7] = {};
  11749. isize variant_count = gb_max(0, t->Union.variants.count);
  11750. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  11751. // NOTE(bill): Zeroth is nil so ignore it
  11752. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  11753. Type *vt = t->Union.variants[variant_index];
  11754. lbValue tip = lb_get_type_info_ptr(m, vt);
  11755. lbValue index = lb_const_int(m, t_int, variant_index);
  11756. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  11757. lb_emit_store(p, type_info, lb_type_info(m, vt));
  11758. }
  11759. lbValue count = lb_const_int(m, t_int, variant_count);
  11760. vals[0] = llvm_const_slice(m, memory_types, count);
  11761. i64 tag_size = union_tag_size(t);
  11762. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  11763. if (tag_size > 0) {
  11764. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  11765. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  11766. } else {
  11767. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  11768. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  11769. }
  11770. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  11771. vals[3] = lb_get_equal_proc_for_type(m, t).value;
  11772. }
  11773. vals[4] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  11774. vals[5] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  11775. vals[6] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  11776. for (isize i = 0; i < gb_count_of(vals); i++) {
  11777. if (vals[i] == nullptr) {
  11778. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  11779. }
  11780. }
  11781. lbValue res = {};
  11782. res.type = type_deref(tag.type);
  11783. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11784. lb_emit_store(p, tag, res);
  11785. }
  11786. break;
  11787. }
  11788. case Type_Struct: {
  11789. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  11790. LLVMValueRef vals[12] = {};
  11791. {
  11792. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  11793. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  11794. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  11795. vals[5] = is_packed.value;
  11796. vals[6] = is_raw_union.value;
  11797. vals[7] = is_custom_align.value;
  11798. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  11799. vals[8] = lb_get_equal_proc_for_type(m, t).value;
  11800. }
  11801. if (t->Struct.soa_kind != StructSoa_None) {
  11802. lbValue kind = lb_emit_struct_ep(p, tag, 9);
  11803. Type *kind_type = type_deref(kind.type);
  11804. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  11805. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  11806. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  11807. vals[9] = soa_kind.value;
  11808. vals[10] = soa_type.value;
  11809. vals[11] = soa_len.value;
  11810. }
  11811. }
  11812. isize count = t->Struct.fields.count;
  11813. if (count > 0) {
  11814. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  11815. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  11816. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  11817. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  11818. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  11819. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  11820. for (isize source_index = 0; source_index < count; source_index++) {
  11821. // TODO(bill): Order fields in source order not layout order
  11822. Entity *f = t->Struct.fields[source_index];
  11823. lbValue tip = lb_get_type_info_ptr(m, f->type);
  11824. i64 foffset = 0;
  11825. if (!t->Struct.is_raw_union) {
  11826. foffset = t->Struct.offsets[f->Variable.field_index];
  11827. }
  11828. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  11829. lbValue index = lb_const_int(m, t_int, source_index);
  11830. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  11831. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  11832. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  11833. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  11834. if (f->token.string.len > 0) {
  11835. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  11836. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  11837. }
  11838. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  11839. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  11840. if (t->Struct.tags.count > 0) {
  11841. String tag_string = t->Struct.tags[source_index];
  11842. if (tag_string.len > 0) {
  11843. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  11844. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  11845. }
  11846. }
  11847. }
  11848. lbValue cv = lb_const_int(m, t_int, count);
  11849. vals[0] = llvm_const_slice(m, memory_types, cv);
  11850. vals[1] = llvm_const_slice(m, memory_names, cv);
  11851. vals[2] = llvm_const_slice(m, memory_offsets, cv);
  11852. vals[3] = llvm_const_slice(m, memory_usings, cv);
  11853. vals[4] = llvm_const_slice(m, memory_tags, cv);
  11854. }
  11855. for (isize i = 0; i < gb_count_of(vals); i++) {
  11856. if (vals[i] == nullptr) {
  11857. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  11858. }
  11859. }
  11860. lbValue res = {};
  11861. res.type = type_deref(tag.type);
  11862. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11863. lb_emit_store(p, tag, res);
  11864. break;
  11865. }
  11866. case Type_Map: {
  11867. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  11868. init_map_internal_types(t);
  11869. LLVMValueRef vals[5] = {
  11870. lb_get_type_info_ptr(m, t->Map.key).value,
  11871. lb_get_type_info_ptr(m, t->Map.value).value,
  11872. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  11873. lb_get_equal_proc_for_type(m, t->Map.key).value,
  11874. lb_get_hasher_proc_for_type(m, t->Map.key).value
  11875. };
  11876. lbValue res = {};
  11877. res.type = type_deref(tag.type);
  11878. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11879. lb_emit_store(p, tag, res);
  11880. break;
  11881. }
  11882. case Type_BitSet:
  11883. {
  11884. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  11885. GB_ASSERT(is_type_typed(t->BitSet.elem));
  11886. LLVMValueRef vals[4] = {
  11887. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  11888. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  11889. lb_const_int(m, t_i64, t->BitSet.lower).value,
  11890. lb_const_int(m, t_i64, t->BitSet.upper).value,
  11891. };
  11892. if (t->BitSet.underlying != nullptr) {
  11893. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  11894. }
  11895. lbValue res = {};
  11896. res.type = type_deref(tag.type);
  11897. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11898. lb_emit_store(p, tag, res);
  11899. }
  11900. break;
  11901. case Type_SimdVector:
  11902. {
  11903. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  11904. LLVMValueRef vals[3] = {};
  11905. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  11906. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  11907. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  11908. lbValue res = {};
  11909. res.type = type_deref(tag.type);
  11910. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11911. lb_emit_store(p, tag, res);
  11912. }
  11913. break;
  11914. case Type_RelativePointer:
  11915. {
  11916. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  11917. LLVMValueRef vals[2] = {
  11918. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  11919. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  11920. };
  11921. lbValue res = {};
  11922. res.type = type_deref(tag.type);
  11923. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11924. lb_emit_store(p, tag, res);
  11925. }
  11926. break;
  11927. case Type_RelativeSlice:
  11928. {
  11929. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  11930. LLVMValueRef vals[2] = {
  11931. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  11932. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  11933. };
  11934. lbValue res = {};
  11935. res.type = type_deref(tag.type);
  11936. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11937. lb_emit_store(p, tag, res);
  11938. }
  11939. break;
  11940. }
  11941. if (tag.value != nullptr) {
  11942. Type *tag_type = type_deref(tag.type);
  11943. GB_ASSERT(is_type_named(tag_type));
  11944. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  11945. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  11946. } else {
  11947. if (t != t_llvm_bool) {
  11948. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  11949. }
  11950. }
  11951. }
  11952. }
  11953. struct lbGlobalVariable {
  11954. lbValue var;
  11955. lbValue init;
  11956. DeclInfo *decl;
  11957. bool is_initialized;
  11958. };
  11959. lbProcedure *lb_create_startup_type_info(lbModule *m) {
  11960. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  11961. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  11962. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  11963. Type *params = alloc_type_tuple();
  11964. Type *results = alloc_type_tuple();
  11965. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  11966. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  11967. p->is_startup = true;
  11968. lb_begin_procedure_body(p);
  11969. lb_setup_type_info_data(p);
  11970. lb_end_procedure_body(p);
  11971. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11972. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11973. LLVMDumpValue(p->value);
  11974. gb_printf_err("\n\n\n\n");
  11975. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11976. }
  11977. lb_run_function_pass_manager(default_function_pass_manager, p);
  11978. return p;
  11979. }
  11980. lbProcedure *lb_create_startup_runtime(lbModule *main_module, lbProcedure *startup_type_info, Array<lbGlobalVariable> &global_variables) { // Startup Runtime
  11981. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(main_module->mod);
  11982. lb_populate_function_pass_manager(main_module, default_function_pass_manager, false, build_context.optimization_level);
  11983. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  11984. Type *params = alloc_type_tuple();
  11985. Type *results = alloc_type_tuple();
  11986. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  11987. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  11988. p->is_startup = true;
  11989. lb_begin_procedure_body(p);
  11990. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(main_module, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  11991. for_array(i, global_variables) {
  11992. auto *var = &global_variables[i];
  11993. if (var->is_initialized) {
  11994. continue;
  11995. }
  11996. lbModule *entity_module = main_module;
  11997. Entity *e = var->decl->entity;
  11998. GB_ASSERT(e->kind == Entity_Variable);
  11999. e->code_gen_module = entity_module;
  12000. if (var->decl->init_expr != nullptr) {
  12001. // gb_printf_err("%s\n", expr_to_string(var->decl->init_expr));
  12002. lbValue init = lb_build_expr(p, var->decl->init_expr);
  12003. LLVMValueKind value_kind = LLVMGetValueKind(init.value);
  12004. // gb_printf_err("%s %d\n", LLVMPrintValueToString(init.value));
  12005. if (lb_is_const_or_global(init)) {
  12006. if (!var->is_initialized) {
  12007. LLVMSetInitializer(var->var.value, init.value);
  12008. var->is_initialized = true;
  12009. continue;
  12010. }
  12011. } else {
  12012. var->init = init;
  12013. }
  12014. }
  12015. if (var->init.value != nullptr) {
  12016. GB_ASSERT(!var->is_initialized);
  12017. Type *t = type_deref(var->var.type);
  12018. if (is_type_any(t)) {
  12019. // NOTE(bill): Edge case for 'any' type
  12020. Type *var_type = default_type(var->init.type);
  12021. lbAddr g = lb_add_global_generated(main_module, var_type, var->init);
  12022. lb_addr_store(p, g, var->init);
  12023. lbValue gp = lb_addr_get_ptr(p, g);
  12024. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  12025. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  12026. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  12027. lb_emit_store(p, ti, lb_type_info(main_module, var_type));
  12028. } else {
  12029. LLVMTypeRef pvt = LLVMTypeOf(var->var.value);
  12030. LLVMTypeRef vt = LLVMGetElementType(pvt);
  12031. lbValue src0 = lb_emit_conv(p, var->init, t);
  12032. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  12033. LLVMValueRef dst = var->var.value;
  12034. LLVMBuildStore(p->builder, src, dst);
  12035. }
  12036. var->is_initialized = true;
  12037. }
  12038. }
  12039. lb_end_procedure_body(p);
  12040. if (!main_module->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  12041. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  12042. LLVMDumpValue(p->value);
  12043. gb_printf_err("\n\n\n\n");
  12044. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  12045. }
  12046. lb_run_function_pass_manager(default_function_pass_manager, p);
  12047. return p;
  12048. }
  12049. lbProcedure *lb_create_main_procedure(lbModule *m, lbProcedure *startup_runtime) {
  12050. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  12051. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  12052. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  12053. Type *params = alloc_type_tuple();
  12054. Type *results = alloc_type_tuple();
  12055. Type *t_ptr_cstring = alloc_type_pointer(t_cstring);
  12056. String name = str_lit("main");
  12057. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  12058. name = str_lit("mainCRTStartup");
  12059. } else {
  12060. array_init(&params->Tuple.variables, permanent_allocator(), 2);
  12061. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  12062. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), t_ptr_cstring, false, true);
  12063. }
  12064. array_init(&results->Tuple.variables, permanent_allocator(), 1);
  12065. results->Tuple.variables[0] = alloc_entity_param(nullptr, blank_token, t_i32, false, true);
  12066. Type *proc_type = alloc_type_proc(nullptr,
  12067. params, params->Tuple.variables.count,
  12068. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  12069. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  12070. p->is_startup = true;
  12071. lb_begin_procedure_body(p);
  12072. { // initialize `runtime.args__`
  12073. lbValue argc = {LLVMGetParam(p->value, 0), t_i32};
  12074. lbValue argv = {LLVMGetParam(p->value, 1), t_ptr_cstring};
  12075. LLVMSetValueName2(argc.value, "argc", 4);
  12076. LLVMSetValueName2(argv.value, "argv", 4);
  12077. argc = lb_emit_conv(p, argc, t_int);
  12078. lbAddr args = lb_addr(lb_find_runtime_value(p->module, str_lit("args__")));
  12079. lb_fill_slice(p, args, argv, argc);
  12080. }
  12081. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  12082. if (build_context.command_kind == Command_test) {
  12083. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  12084. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  12085. Type *slice_type = alloc_type_slice(t_Internal_Test);
  12086. lbAddr all_tests_array_addr = lb_add_global_generated(p->module, array_type, {});
  12087. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  12088. LLVMTypeRef lbt_Internal_Test = lb_type(m, t_Internal_Test);
  12089. LLVMValueRef indices[2] = {};
  12090. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  12091. for_array(i, m->info->testing_procedures) {
  12092. Entity *testing_proc = m->info->testing_procedures[i];
  12093. String name = testing_proc->token.string;
  12094. String pkg_name = {};
  12095. if (testing_proc->pkg != nullptr) {
  12096. pkg_name = testing_proc->pkg->name;
  12097. }
  12098. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name);
  12099. lbValue v_name = lb_find_or_add_entity_string(m, name);
  12100. lbValue v_proc = lb_find_procedure_value_from_entity(m, testing_proc);
  12101. indices[1] = LLVMConstInt(lb_type(m, t_int), i, false);
  12102. LLVMValueRef vals[3] = {};
  12103. vals[0] = v_pkg.value;
  12104. vals[1] = v_name.value;
  12105. vals[2] = v_proc.value;
  12106. GB_ASSERT(LLVMIsConstant(vals[0]));
  12107. GB_ASSERT(LLVMIsConstant(vals[1]));
  12108. GB_ASSERT(LLVMIsConstant(vals[2]));
  12109. LLVMValueRef dst = LLVMConstInBoundsGEP(all_tests_array.value, indices, gb_count_of(indices));
  12110. LLVMValueRef src = llvm_const_named_struct(lbt_Internal_Test, vals, gb_count_of(vals));
  12111. LLVMBuildStore(p->builder, src, dst);
  12112. }
  12113. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  12114. lb_fill_slice(p, all_tests_slice,
  12115. lb_array_elem(p, all_tests_array),
  12116. lb_const_int(m, t_int, m->info->testing_procedures.count));
  12117. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  12118. auto args = array_make<lbValue>(heap_allocator(), 1);
  12119. args[0] = lb_addr_load(p, all_tests_slice);
  12120. lb_emit_call(p, runner, args);
  12121. } else {
  12122. lbValue entry_point = lb_find_procedure_value_from_entity(m, m->info->entry_point);
  12123. lb_emit_call(p, entry_point, {});
  12124. }
  12125. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  12126. lb_end_procedure_body(p);
  12127. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  12128. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  12129. LLVMDumpValue(p->value);
  12130. gb_printf_err("\n\n\n\n");
  12131. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  12132. }
  12133. lb_run_function_pass_manager(default_function_pass_manager, p);
  12134. return p;
  12135. }
  12136. String lb_filepath_ll_for_module(lbModule *m) {
  12137. String path = m->gen->output_base;
  12138. if (m->pkg) {
  12139. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  12140. } else if (USE_SEPARTE_MODULES) {
  12141. path = concatenate_strings(permanent_allocator(), path, STR_LIT("-builtin"));
  12142. }
  12143. path = concatenate_strings(permanent_allocator(), path, STR_LIT(".ll"));
  12144. return path;
  12145. }
  12146. String lb_filepath_obj_for_module(lbModule *m) {
  12147. String path = m->gen->output_base;
  12148. if (m->pkg) {
  12149. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  12150. }
  12151. String ext = {};
  12152. if (build_context.build_mode == BuildMode_Assembly) {
  12153. ext = STR_LIT(".S");
  12154. } else {
  12155. switch (build_context.metrics.os) {
  12156. case TargetOs_windows:
  12157. ext = STR_LIT(".obj");
  12158. break;
  12159. case TargetOs_darwin:
  12160. case TargetOs_linux:
  12161. case TargetOs_essence:
  12162. ext = STR_LIT(".o");
  12163. break;
  12164. case TargetOs_js:
  12165. ext = STR_LIT(".wasm-obj");
  12166. break;
  12167. }
  12168. }
  12169. return concatenate_strings(permanent_allocator(), path, ext);
  12170. }
  12171. bool lb_is_module_empty(lbModule *m) {
  12172. if (LLVMGetFirstFunction(m->mod) == nullptr &&
  12173. LLVMGetFirstGlobal(m->mod) == nullptr) {
  12174. return true;
  12175. }
  12176. for (auto fn = LLVMGetFirstFunction(m->mod); fn != nullptr; fn = LLVMGetNextFunction(fn)) {
  12177. if (LLVMGetFirstBasicBlock(fn) != nullptr) {
  12178. return false;
  12179. }
  12180. }
  12181. for (auto g = LLVMGetFirstGlobal(m->mod); g != nullptr; g = LLVMGetNextGlobal(g)) {
  12182. if (LLVMGetLinkage(g) == LLVMExternalLinkage) {
  12183. continue;
  12184. }
  12185. if (!LLVMIsExternallyInitialized(g)) {
  12186. return false;
  12187. }
  12188. }
  12189. return true;
  12190. }
  12191. struct lbLLVMEmitWorker {
  12192. LLVMTargetMachineRef target_machine;
  12193. LLVMCodeGenFileType code_gen_file_type;
  12194. String filepath_obj;
  12195. lbModule *m;
  12196. };
  12197. WORKER_TASK_PROC(lb_llvm_emit_worker_proc) {
  12198. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  12199. char *llvm_error = nullptr;
  12200. auto wd = cast(lbLLVMEmitWorker *)data;
  12201. if (LLVMTargetMachineEmitToFile(wd->target_machine, wd->m->mod, cast(char *)wd->filepath_obj.text, wd->code_gen_file_type, &llvm_error)) {
  12202. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12203. gb_exit(1);
  12204. }
  12205. return 0;
  12206. }
  12207. WORKER_TASK_PROC(lb_llvm_function_pass_worker_proc) {
  12208. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  12209. auto m = cast(lbModule *)data;
  12210. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  12211. LLVMPassManagerRef function_pass_manager_minimal = LLVMCreateFunctionPassManagerForModule(m->mod);
  12212. LLVMPassManagerRef function_pass_manager_size = LLVMCreateFunctionPassManagerForModule(m->mod);
  12213. LLVMPassManagerRef function_pass_manager_speed = LLVMCreateFunctionPassManagerForModule(m->mod);
  12214. LLVMInitializeFunctionPassManager(default_function_pass_manager);
  12215. LLVMInitializeFunctionPassManager(function_pass_manager_minimal);
  12216. LLVMInitializeFunctionPassManager(function_pass_manager_size);
  12217. LLVMInitializeFunctionPassManager(function_pass_manager_speed);
  12218. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  12219. lb_populate_function_pass_manager_specific(m, function_pass_manager_minimal, 0);
  12220. lb_populate_function_pass_manager_specific(m, function_pass_manager_size, 1);
  12221. lb_populate_function_pass_manager_specific(m, function_pass_manager_speed, 2);
  12222. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  12223. LLVMFinalizeFunctionPassManager(function_pass_manager_minimal);
  12224. LLVMFinalizeFunctionPassManager(function_pass_manager_size);
  12225. LLVMFinalizeFunctionPassManager(function_pass_manager_speed);
  12226. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(m->mod);
  12227. LLVMInitializeFunctionPassManager(default_function_pass_manager_without_memcpy);
  12228. lb_populate_function_pass_manager(m, default_function_pass_manager_without_memcpy, true, build_context.optimization_level);
  12229. LLVMFinalizeFunctionPassManager(default_function_pass_manager_without_memcpy);
  12230. for_array(i, m->procedures_to_generate) {
  12231. lbProcedure *p = m->procedures_to_generate[i];
  12232. if (p->body != nullptr) { // Build Procedure
  12233. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  12234. lb_run_function_pass_manager(default_function_pass_manager_without_memcpy, p);
  12235. } else {
  12236. if (p->entity && p->entity->kind == Entity_Procedure) {
  12237. switch (p->entity->Procedure.optimization_mode) {
  12238. case ProcedureOptimizationMode_None:
  12239. case ProcedureOptimizationMode_Minimal:
  12240. lb_run_function_pass_manager(function_pass_manager_minimal, p);
  12241. break;
  12242. case ProcedureOptimizationMode_Size:
  12243. lb_run_function_pass_manager(function_pass_manager_size, p);
  12244. break;
  12245. case ProcedureOptimizationMode_Speed:
  12246. lb_run_function_pass_manager(function_pass_manager_speed, p);
  12247. break;
  12248. default:
  12249. lb_run_function_pass_manager(default_function_pass_manager, p);
  12250. break;
  12251. }
  12252. } else {
  12253. lb_run_function_pass_manager(default_function_pass_manager, p);
  12254. }
  12255. }
  12256. }
  12257. }
  12258. for_array(i, m->equal_procs.entries) {
  12259. lbProcedure *p = m->equal_procs.entries[i].value;
  12260. lb_run_function_pass_manager(default_function_pass_manager, p);
  12261. }
  12262. for_array(i, m->hasher_procs.entries) {
  12263. lbProcedure *p = m->hasher_procs.entries[i].value;
  12264. lb_run_function_pass_manager(default_function_pass_manager, p);
  12265. }
  12266. return 0;
  12267. }
  12268. struct lbLLVMModulePassWorkerData {
  12269. lbModule *m;
  12270. LLVMTargetMachineRef target_machine;
  12271. };
  12272. WORKER_TASK_PROC(lb_llvm_module_pass_worker_proc) {
  12273. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  12274. auto wd = cast(lbLLVMModulePassWorkerData *)data;
  12275. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  12276. lb_populate_module_pass_manager(wd->target_machine, module_pass_manager, build_context.optimization_level);
  12277. LLVMRunPassManager(module_pass_manager, wd->m->mod);
  12278. return 0;
  12279. }
  12280. void lb_generate_code(lbGenerator *gen) {
  12281. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  12282. #define TIME_SECTION_WITH_LEN(str, len) do { if (build_context.show_more_timings) timings_start_section(&global_timings, make_string((u8 *)str, len)); } while (0)
  12283. TIME_SECTION("LLVM Initializtion");
  12284. isize thread_count = gb_max(build_context.thread_count, 1);
  12285. isize worker_count = thread_count-1;
  12286. LLVMBool do_threading = (LLVMIsMultithreaded() && USE_SEPARTE_MODULES && MULTITHREAD_OBJECT_GENERATION && worker_count > 0);
  12287. thread_pool_init(&lb_thread_pool, heap_allocator(), worker_count, "LLVMBackend");
  12288. defer (thread_pool_destroy(&lb_thread_pool));
  12289. lbModule *default_module = &gen->default_module;
  12290. CheckerInfo *info = gen->info;
  12291. auto *min_dep_set = &info->minimum_dependency_set;
  12292. LLVMInitializeAllTargetInfos();
  12293. LLVMInitializeAllTargets();
  12294. LLVMInitializeAllTargetMCs();
  12295. LLVMInitializeAllAsmPrinters();
  12296. LLVMInitializeAllAsmParsers();
  12297. LLVMInitializeAllDisassemblers();
  12298. LLVMInitializeNativeTarget();
  12299. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  12300. char const *target_data_layout = alloc_cstring(permanent_allocator(), build_context.metrics.target_data_layout);
  12301. for_array(i, gen->modules.entries) {
  12302. LLVMSetTarget(gen->modules.entries[i].value->mod, target_triple);
  12303. }
  12304. LLVMTargetRef target = {};
  12305. char *llvm_error = nullptr;
  12306. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  12307. GB_ASSERT(target != nullptr);
  12308. TIME_SECTION("LLVM Create Target Machine");
  12309. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  12310. if (build_context.metrics.arch == TargetArch_wasm32) {
  12311. code_mode = LLVMCodeModelJITDefault;
  12312. }
  12313. char const *host_cpu_name = LLVMGetHostCPUName();
  12314. char const *llvm_cpu = "generic";
  12315. char const *llvm_features = "";
  12316. if (build_context.microarch.len != 0) {
  12317. if (build_context.microarch == "native") {
  12318. llvm_cpu = host_cpu_name;
  12319. } else {
  12320. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  12321. }
  12322. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  12323. llvm_features = LLVMGetHostCPUFeatures();
  12324. }
  12325. }
  12326. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  12327. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  12328. switch (build_context.optimization_level) {
  12329. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  12330. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  12331. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  12332. case 3: code_gen_level = LLVMCodeGenLevelDefault; break; // NOTE(bill): force -opt:3 to be the same as -opt:2
  12333. // case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  12334. }
  12335. // NOTE(bill): Target Machine Creation
  12336. // NOTE(bill, 2021-05-04): Target machines must be unique to each module because they are not thread safe
  12337. auto target_machines = array_make<LLVMTargetMachineRef>(permanent_allocator(), gen->modules.entries.count);
  12338. for_array(i, gen->modules.entries) {
  12339. target_machines[i] = LLVMCreateTargetMachine(
  12340. target, target_triple, llvm_cpu,
  12341. llvm_features,
  12342. code_gen_level,
  12343. LLVMRelocDefault,
  12344. code_mode);
  12345. LLVMSetModuleDataLayout(gen->modules.entries[i].value->mod, LLVMCreateTargetDataLayout(target_machines[i]));
  12346. }
  12347. for_array(i, gen->modules.entries) {
  12348. lbModule *m = gen->modules.entries[i].value;
  12349. if (m->debug_builder) { // Debug Info
  12350. for_array(i, info->files.entries) {
  12351. AstFile *f = info->files.entries[i].value;
  12352. String fullpath = f->fullpath;
  12353. String filename = remove_directory_from_path(fullpath);
  12354. String directory = directory_from_path(fullpath);
  12355. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  12356. cast(char const *)filename.text, filename.len,
  12357. cast(char const *)directory.text, directory.len);
  12358. lb_set_llvm_metadata(m, f, res);
  12359. }
  12360. gbString producer = gb_string_make(heap_allocator(), "odin");
  12361. // producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  12362. // #ifdef NIGHTLY
  12363. // producer = gb_string_appendc(producer, "-nightly");
  12364. // #endif
  12365. // #ifdef GIT_SHA
  12366. // producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  12367. // #endif
  12368. gbString split_name = gb_string_make(heap_allocator(), "");
  12369. LLVMBool is_optimized = build_context.optimization_level > 0;
  12370. AstFile *init_file = m->info->init_package->files[0];
  12371. if (m->info->entry_point && m->info->entry_point->identifier && m->info->entry_point->identifier->file) {
  12372. init_file = m->info->entry_point->identifier->file;
  12373. }
  12374. LLVMBool split_debug_inlining = false;
  12375. LLVMBool debug_info_for_profiling = false;
  12376. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  12377. lb_get_llvm_metadata(m, init_file),
  12378. producer, gb_string_length(producer),
  12379. is_optimized, "", 0,
  12380. 1, split_name, gb_string_length(split_name),
  12381. LLVMDWARFEmissionFull,
  12382. 0, split_debug_inlining,
  12383. debug_info_for_profiling,
  12384. "", 0, // sys_root
  12385. "", 0 // SDK
  12386. );
  12387. GB_ASSERT(m->debug_compile_unit != nullptr);
  12388. }
  12389. }
  12390. TIME_SECTION("LLVM Global Variables");
  12391. {
  12392. lbModule *m = default_module;
  12393. { // Add type info data
  12394. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  12395. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  12396. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  12397. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  12398. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  12399. if (!USE_SEPARTE_MODULES) {
  12400. LLVMSetLinkage(g, LLVMInternalLinkage);
  12401. }
  12402. lbValue value = {};
  12403. value.value = g;
  12404. value.type = alloc_type_pointer(t);
  12405. lb_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(LB_TYPE_INFO_DATA_NAME), t, EntityState_Resolved);
  12406. lb_add_entity(m, lb_global_type_info_data_entity, value);
  12407. }
  12408. { // Type info member buffer
  12409. // NOTE(bill): Removes need for heap allocation by making it global memory
  12410. isize count = 0;
  12411. for_array(entry_index, m->info->type_info_types) {
  12412. Type *t = m->info->type_info_types[entry_index];
  12413. isize index = lb_type_info_index(m->info, t, false);
  12414. if (index < 0) {
  12415. continue;
  12416. }
  12417. switch (t->kind) {
  12418. case Type_Union:
  12419. count += t->Union.variants.count;
  12420. break;
  12421. case Type_Struct:
  12422. count += t->Struct.fields.count;
  12423. break;
  12424. case Type_Tuple:
  12425. count += t->Tuple.variables.count;
  12426. break;
  12427. }
  12428. }
  12429. if (count > 0) {
  12430. {
  12431. char const *name = LB_TYPE_INFO_TYPES_NAME;
  12432. Type *t = alloc_type_array(t_type_info_ptr, count);
  12433. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  12434. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  12435. LLVMSetLinkage(g, LLVMInternalLinkage);
  12436. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  12437. }
  12438. {
  12439. char const *name = LB_TYPE_INFO_NAMES_NAME;
  12440. Type *t = alloc_type_array(t_string, count);
  12441. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  12442. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  12443. LLVMSetLinkage(g, LLVMInternalLinkage);
  12444. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  12445. }
  12446. {
  12447. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  12448. Type *t = alloc_type_array(t_uintptr, count);
  12449. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  12450. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  12451. LLVMSetLinkage(g, LLVMInternalLinkage);
  12452. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  12453. }
  12454. {
  12455. char const *name = LB_TYPE_INFO_USINGS_NAME;
  12456. Type *t = alloc_type_array(t_bool, count);
  12457. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  12458. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  12459. LLVMSetLinkage(g, LLVMInternalLinkage);
  12460. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  12461. }
  12462. {
  12463. char const *name = LB_TYPE_INFO_TAGS_NAME;
  12464. Type *t = alloc_type_array(t_string, count);
  12465. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  12466. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  12467. LLVMSetLinkage(g, LLVMInternalLinkage);
  12468. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  12469. }
  12470. }
  12471. }
  12472. }
  12473. isize global_variable_max_count = 0;
  12474. Entity *entry_point = info->entry_point;
  12475. bool has_dll_main = false;
  12476. bool has_win_main = false;
  12477. for_array(i, info->entities) {
  12478. Entity *e = info->entities[i];
  12479. String name = e->token.string;
  12480. bool is_global = e->pkg != nullptr;
  12481. if (e->kind == Entity_Variable) {
  12482. global_variable_max_count++;
  12483. } else if (e->kind == Entity_Procedure && !is_global) {
  12484. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  12485. GB_ASSERT(e == entry_point);
  12486. // entry_point = e;
  12487. }
  12488. if (e->Procedure.is_export ||
  12489. (e->Procedure.link_name.len > 0) ||
  12490. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  12491. if (!has_dll_main && name == "DllMain") {
  12492. has_dll_main = true;
  12493. } else if (!has_win_main && name == "WinMain") {
  12494. has_win_main = true;
  12495. }
  12496. }
  12497. }
  12498. }
  12499. auto global_variables = array_make<lbGlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  12500. for_array(i, info->variable_init_order) {
  12501. DeclInfo *d = info->variable_init_order[i];
  12502. Entity *e = d->entity;
  12503. if ((e->scope->flags & ScopeFlag_File) == 0) {
  12504. continue;
  12505. }
  12506. if (!ptr_set_exists(min_dep_set, e)) {
  12507. continue;
  12508. }
  12509. DeclInfo *decl = decl_info_of_entity(e);
  12510. if (decl == nullptr) {
  12511. continue;
  12512. }
  12513. GB_ASSERT(e->kind == Entity_Variable);
  12514. bool is_foreign = e->Variable.is_foreign;
  12515. bool is_export = e->Variable.is_export;
  12516. lbModule *m = &gen->default_module;
  12517. String name = lb_get_entity_name(m, e);
  12518. lbValue g = {};
  12519. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  12520. g.type = alloc_type_pointer(e->type);
  12521. if (e->Variable.thread_local_model != "") {
  12522. LLVMSetThreadLocal(g.value, true);
  12523. String m = e->Variable.thread_local_model;
  12524. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  12525. if (m == "default") {
  12526. mode = LLVMGeneralDynamicTLSModel;
  12527. } else if (m == "localdynamic") {
  12528. mode = LLVMLocalDynamicTLSModel;
  12529. } else if (m == "initialexec") {
  12530. mode = LLVMInitialExecTLSModel;
  12531. } else if (m == "localexec") {
  12532. mode = LLVMLocalExecTLSModel;
  12533. } else {
  12534. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  12535. }
  12536. LLVMSetThreadLocalMode(g.value, mode);
  12537. }
  12538. if (is_foreign) {
  12539. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  12540. LLVMSetExternallyInitialized(g.value, true);
  12541. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  12542. } else {
  12543. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  12544. }
  12545. if (is_export) {
  12546. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  12547. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  12548. } else {
  12549. if (USE_SEPARTE_MODULES) {
  12550. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  12551. } else {
  12552. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  12553. }
  12554. }
  12555. if (e->Variable.link_section.len > 0) {
  12556. LLVMSetSection(g.value, alloc_cstring(permanent_allocator(), e->Variable.link_section));
  12557. }
  12558. lbGlobalVariable var = {};
  12559. var.var = g;
  12560. var.decl = decl;
  12561. if (decl->init_expr != nullptr) {
  12562. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  12563. if (!is_type_any(e->type)) {
  12564. if (tav.mode != Addressing_Invalid) {
  12565. if (tav.value.kind != ExactValue_Invalid) {
  12566. ExactValue v = tav.value;
  12567. lbValue init = lb_const_value(m, tav.type, v);
  12568. LLVMSetInitializer(g.value, init.value);
  12569. var.is_initialized = true;
  12570. }
  12571. }
  12572. }
  12573. if (!var.is_initialized &&
  12574. (is_type_untyped_nil(tav.type) || is_type_untyped_undef(tav.type))) {
  12575. var.is_initialized = true;
  12576. }
  12577. }
  12578. array_add(&global_variables, var);
  12579. lb_add_entity(m, e, g);
  12580. lb_add_member(m, name, g);
  12581. if (m->debug_builder) {
  12582. String global_name = e->token.string;
  12583. if (global_name.len != 0 && global_name != "_") {
  12584. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  12585. LLVMMetadataRef llvm_scope = llvm_file;
  12586. LLVMBool local_to_unit = LLVMGetLinkage(g.value) == LLVMInternalLinkage;
  12587. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  12588. LLVMMetadataRef llvm_decl = nullptr;
  12589. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  12590. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  12591. m->debug_builder, llvm_scope,
  12592. cast(char const *)global_name.text, global_name.len,
  12593. "", 0, // linkage
  12594. llvm_file, e->token.pos.line,
  12595. lb_debug_type(m, e->type),
  12596. local_to_unit,
  12597. llvm_expr,
  12598. llvm_decl,
  12599. align_in_bits
  12600. );
  12601. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  12602. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  12603. }
  12604. }
  12605. }
  12606. TIME_SECTION("LLVM Global Procedures and Types");
  12607. for_array(i, info->entities) {
  12608. Entity *e = info->entities[i];
  12609. String name = e->token.string;
  12610. DeclInfo *decl = e->decl_info;
  12611. Scope * scope = e->scope;
  12612. if ((scope->flags & ScopeFlag_File) == 0) {
  12613. continue;
  12614. }
  12615. Scope *package_scope = scope->parent;
  12616. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  12617. switch (e->kind) {
  12618. case Entity_Variable:
  12619. // NOTE(bill): Handled above as it requires a specific load order
  12620. continue;
  12621. case Entity_ProcGroup:
  12622. continue;
  12623. case Entity_TypeName:
  12624. case Entity_Procedure:
  12625. break;
  12626. }
  12627. bool polymorphic_struct = false;
  12628. if (e->type != nullptr && e->kind == Entity_TypeName) {
  12629. Type *bt = base_type(e->type);
  12630. if (bt->kind == Type_Struct) {
  12631. polymorphic_struct = is_type_polymorphic(bt);
  12632. }
  12633. }
  12634. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  12635. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  12636. continue;
  12637. }
  12638. lbModule *m = &gen->default_module;
  12639. if (USE_SEPARTE_MODULES) {
  12640. m = lb_pkg_module(gen, e->pkg);
  12641. }
  12642. String mangled_name = lb_get_entity_name(m, e);
  12643. switch (e->kind) {
  12644. case Entity_TypeName:
  12645. lb_type(m, e->type);
  12646. break;
  12647. case Entity_Procedure:
  12648. {
  12649. lbProcedure *p = lb_create_procedure(m, e);
  12650. array_add(&m->procedures_to_generate, p);
  12651. }
  12652. break;
  12653. }
  12654. }
  12655. TIME_SECTION("LLVM Runtime Type Information Creation");
  12656. lbProcedure *startup_type_info = lb_create_startup_type_info(default_module);
  12657. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables)");
  12658. lbProcedure *startup_runtime = lb_create_startup_runtime(default_module, startup_type_info, global_variables);
  12659. TIME_SECTION("LLVM Procedure Generation");
  12660. for_array(j, gen->modules.entries) {
  12661. lbModule *m = gen->modules.entries[j].value;
  12662. for_array(i, m->procedures_to_generate) {
  12663. lbProcedure *p = m->procedures_to_generate[i];
  12664. if (p->is_done) {
  12665. continue;
  12666. }
  12667. if (p->body != nullptr) { // Build Procedure
  12668. m->curr_procedure = p;
  12669. lb_begin_procedure_body(p);
  12670. lb_build_stmt(p, p->body);
  12671. lb_end_procedure_body(p);
  12672. p->is_done = true;
  12673. m->curr_procedure = nullptr;
  12674. }
  12675. lb_end_procedure(p);
  12676. // Add Flags
  12677. if (p->body != nullptr) {
  12678. if (p->name == "memcpy" || p->name == "memmove" ||
  12679. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  12680. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  12681. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  12682. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  12683. }
  12684. }
  12685. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  12686. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  12687. LLVMDumpValue(p->value);
  12688. gb_printf_err("\n\n\n\n");
  12689. String filepath_ll = lb_filepath_ll_for_module(m);
  12690. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  12691. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12692. }
  12693. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  12694. gb_exit(1);
  12695. }
  12696. }
  12697. }
  12698. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  12699. TIME_SECTION("LLVM main");
  12700. lb_create_main_procedure(default_module, startup_runtime);
  12701. }
  12702. if (build_context.ODIN_DEBUG) {
  12703. TIME_SECTION("LLVM Debug Info Complete Types and Finalize");
  12704. for_array(j, gen->modules.entries) {
  12705. lbModule *m = gen->modules.entries[j].value;
  12706. if (m->debug_builder != nullptr) {
  12707. lb_debug_complete_types(m);
  12708. LLVMDIBuilderFinalize(m->debug_builder);
  12709. }
  12710. }
  12711. }
  12712. TIME_SECTION("LLVM Function Pass");
  12713. for_array(i, gen->modules.entries) {
  12714. lbModule *m = gen->modules.entries[i].value;
  12715. lb_llvm_function_pass_worker_proc(m);
  12716. }
  12717. TIME_SECTION("LLVM Module Pass");
  12718. for_array(i, gen->modules.entries) {
  12719. lbModule *m = gen->modules.entries[i].value;
  12720. auto wd = gb_alloc_item(permanent_allocator(), lbLLVMModulePassWorkerData);
  12721. wd->m = m;
  12722. wd->target_machine = target_machines[i];
  12723. lb_llvm_module_pass_worker_proc(wd);
  12724. }
  12725. llvm_error = nullptr;
  12726. defer (LLVMDisposeMessage(llvm_error));
  12727. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  12728. if (build_context.build_mode == BuildMode_Assembly) {
  12729. code_gen_file_type = LLVMAssemblyFile;
  12730. }
  12731. for_array(j, gen->modules.entries) {
  12732. lbModule *m = gen->modules.entries[j].value;
  12733. if (LLVMVerifyModule(m->mod, LLVMReturnStatusAction, &llvm_error)) {
  12734. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  12735. if (build_context.keep_temp_files) {
  12736. TIME_SECTION("LLVM Print Module to File");
  12737. String filepath_ll = lb_filepath_ll_for_module(m);
  12738. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  12739. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12740. gb_exit(1);
  12741. return;
  12742. }
  12743. }
  12744. gb_exit(1);
  12745. return;
  12746. }
  12747. }
  12748. llvm_error = nullptr;
  12749. if (build_context.keep_temp_files ||
  12750. build_context.build_mode == BuildMode_LLVM_IR) {
  12751. TIME_SECTION("LLVM Print Module to File");
  12752. for_array(j, gen->modules.entries) {
  12753. lbModule *m = gen->modules.entries[j].value;
  12754. if (lb_is_module_empty(m)) {
  12755. continue;
  12756. }
  12757. String filepath_ll = lb_filepath_ll_for_module(m);
  12758. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  12759. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12760. gb_exit(1);
  12761. return;
  12762. }
  12763. array_add(&gen->output_temp_paths, filepath_ll);
  12764. }
  12765. if (build_context.build_mode == BuildMode_LLVM_IR) {
  12766. gb_exit(0);
  12767. return;
  12768. }
  12769. }
  12770. TIME_SECTION("LLVM Add Foreign Library Paths");
  12771. for_array(j, gen->modules.entries) {
  12772. lbModule *m = gen->modules.entries[j].value;
  12773. for_array(i, m->info->required_foreign_imports_through_force) {
  12774. Entity *e = m->info->required_foreign_imports_through_force[i];
  12775. lb_add_foreign_library_path(m, e);
  12776. }
  12777. if (lb_is_module_empty(m)) {
  12778. continue;
  12779. }
  12780. }
  12781. TIME_SECTION("LLVM Object Generation");
  12782. if (do_threading) {
  12783. for_array(j, gen->modules.entries) {
  12784. lbModule *m = gen->modules.entries[j].value;
  12785. if (lb_is_module_empty(m)) {
  12786. continue;
  12787. }
  12788. String filepath_ll = lb_filepath_ll_for_module(m);
  12789. String filepath_obj = lb_filepath_obj_for_module(m);
  12790. array_add(&gen->output_object_paths, filepath_obj);
  12791. array_add(&gen->output_temp_paths, filepath_ll);
  12792. auto *wd = gb_alloc_item(heap_allocator(), lbLLVMEmitWorker);
  12793. wd->target_machine = target_machines[j];
  12794. wd->code_gen_file_type = code_gen_file_type;
  12795. wd->filepath_obj = filepath_obj;
  12796. wd->m = m;
  12797. thread_pool_add_task(&lb_thread_pool, lb_llvm_emit_worker_proc, wd);
  12798. }
  12799. thread_pool_start(&lb_thread_pool);
  12800. thread_pool_wait_to_process(&lb_thread_pool);
  12801. } else {
  12802. for_array(j, gen->modules.entries) {
  12803. lbModule *m = gen->modules.entries[j].value;
  12804. if (lb_is_module_empty(m)) {
  12805. continue;
  12806. }
  12807. String filepath_obj = lb_filepath_obj_for_module(m);
  12808. array_add(&gen->output_object_paths, filepath_obj);
  12809. String short_name = remove_directory_from_path(filepath_obj);
  12810. gbString section_name = gb_string_make(heap_allocator(), "LLVM Generate Object: ");
  12811. section_name = gb_string_append_length(section_name, short_name.text, short_name.len);
  12812. TIME_SECTION_WITH_LEN(section_name, gb_string_length(section_name));
  12813. if (LLVMTargetMachineEmitToFile(target_machines[j], m->mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  12814. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12815. gb_exit(1);
  12816. return;
  12817. }
  12818. }
  12819. }
  12820. #undef TIME_SECTION
  12821. }