llvm_backend.cpp 509 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363
  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. lbAddr lb_addr_swizzle(lbValue addr, Type *array_type, u8 swizzle_count, u8 swizzle_indices[4]) {
  111. GB_ASSERT(is_type_array(array_type));
  112. GB_ASSERT(1 < swizzle_count && swizzle_count <= 4);
  113. lbAddr v = {lbAddr_Swizzle, addr};
  114. v.swizzle.type = array_type;
  115. v.swizzle.count = swizzle_count;
  116. gb_memmove(v.swizzle.indices, swizzle_indices, swizzle_count);
  117. return v;
  118. }
  119. Type *lb_addr_type(lbAddr const &addr) {
  120. if (addr.addr.value == nullptr) {
  121. return nullptr;
  122. }
  123. if (addr.kind == lbAddr_Map) {
  124. Type *t = base_type(addr.map.type);
  125. GB_ASSERT(is_type_map(t));
  126. return t->Map.value;
  127. }
  128. if (addr.kind == lbAddr_Swizzle) {
  129. return addr.swizzle.type;
  130. }
  131. return type_deref(addr.addr.type);
  132. }
  133. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  134. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  135. }
  136. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  137. if (addr.addr.value == nullptr) {
  138. GB_PANIC("Illegal addr -> nullptr");
  139. return {};
  140. }
  141. switch (addr.kind) {
  142. case lbAddr_Map: {
  143. Type *map_type = base_type(addr.map.type);
  144. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  145. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  146. auto args = array_make<lbValue>(permanent_allocator(), 2);
  147. args[0] = h;
  148. args[1] = key;
  149. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  150. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  151. }
  152. case lbAddr_RelativePointer: {
  153. Type *rel_ptr = base_type(lb_addr_type(addr));
  154. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  155. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  156. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  157. offset = lb_emit_load(p, offset);
  158. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  159. offset = lb_emit_conv(p, offset, t_i64);
  160. }
  161. offset = lb_emit_conv(p, offset, t_uintptr);
  162. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  163. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  164. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  165. // NOTE(bill): nil check
  166. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  167. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  168. return final_ptr;
  169. }
  170. case lbAddr_SoaVariable:
  171. // TODO(bill): FIX THIS HACK
  172. return lb_address_from_load(p, lb_addr_load(p, addr));
  173. case lbAddr_Context:
  174. GB_PANIC("lbAddr_Context should be handled elsewhere");
  175. break;
  176. case lbAddr_Swizzle:
  177. // TOOD(bill): is this good enough logic?
  178. break;
  179. }
  180. return addr.addr;
  181. }
  182. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  183. lbAddr addr = lb_build_addr(p, expr);
  184. return lb_addr_get_ptr(p, addr);
  185. }
  186. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  187. if (build_context.no_bounds_check) {
  188. return;
  189. }
  190. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  191. return;
  192. }
  193. index = lb_emit_conv(p, index, t_int);
  194. len = lb_emit_conv(p, len, t_int);
  195. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  196. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  197. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  198. auto args = array_make<lbValue>(permanent_allocator(), 5);
  199. args[0] = file;
  200. args[1] = line;
  201. args[2] = column;
  202. args[3] = index;
  203. args[4] = len;
  204. lb_emit_runtime_call(p, "bounds_check_error", args);
  205. }
  206. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  207. if (build_context.no_bounds_check) {
  208. return;
  209. }
  210. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  211. return;
  212. }
  213. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  214. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  215. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  216. high = lb_emit_conv(p, high, t_int);
  217. if (!lower_value_used) {
  218. auto args = array_make<lbValue>(permanent_allocator(), 5);
  219. args[0] = file;
  220. args[1] = line;
  221. args[2] = column;
  222. args[3] = high;
  223. args[4] = len;
  224. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  225. } else {
  226. // No need to convert unless used
  227. low = lb_emit_conv(p, low, t_int);
  228. auto args = array_make<lbValue>(permanent_allocator(), 6);
  229. args[0] = file;
  230. args[1] = line;
  231. args[2] = column;
  232. args[3] = low;
  233. args[4] = high;
  234. args[5] = len;
  235. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  236. }
  237. }
  238. bool lb_try_update_alignment(lbValue ptr, unsigned alignment) {
  239. LLVMValueRef addr_ptr = ptr.value;
  240. if (LLVMIsAGlobalValue(addr_ptr) || LLVMIsAAllocaInst(addr_ptr) || LLVMIsALoadInst(addr_ptr)) {
  241. if (LLVMGetAlignment(addr_ptr) < alignment) {
  242. if (LLVMIsAAllocaInst(addr_ptr) || LLVMIsAGlobalValue(addr_ptr)) {
  243. LLVMSetAlignment(addr_ptr, alignment);
  244. }
  245. }
  246. return LLVMGetAlignment(addr_ptr) >= alignment;
  247. }
  248. return false;
  249. }
  250. bool lb_try_vector_cast(lbModule *m, lbValue ptr, LLVMTypeRef *vector_type_) {
  251. Type *array_type = base_type(type_deref(ptr.type));
  252. GB_ASSERT(is_type_array_like(array_type));
  253. i64 count = get_array_type_count(array_type);
  254. Type *elem_type = base_array_type(array_type);
  255. // TODO(bill): Determine what is the correct limit for doing vector arithmetic
  256. if (type_size_of(array_type) <= build_context.max_align &&
  257. is_type_valid_vector_elem(elem_type)) {
  258. // Try to treat it like a vector if possible
  259. bool possible = false;
  260. LLVMTypeRef vector_type = LLVMVectorType(lb_type(m, elem_type), cast(unsigned)count);
  261. unsigned vector_alignment = cast(unsigned)lb_alignof(vector_type);
  262. LLVMValueRef addr_ptr = ptr.value;
  263. if (LLVMIsAAllocaInst(addr_ptr) || LLVMIsAGlobalValue(addr_ptr)) {
  264. unsigned alignment = LLVMGetAlignment(addr_ptr);
  265. alignment = gb_max(alignment, vector_alignment);
  266. possible = true;
  267. LLVMSetAlignment(addr_ptr, alignment);
  268. } else if (LLVMIsALoadInst(addr_ptr)) {
  269. unsigned alignment = LLVMGetAlignment(addr_ptr);
  270. possible = alignment >= vector_alignment;
  271. }
  272. // NOTE: Due to alignment requirements, if the pointer is not correctly aligned
  273. // then it cannot be treated as a vector
  274. if (possible) {
  275. if (vector_type_) *vector_type_ =vector_type;
  276. return true;
  277. }
  278. }
  279. return false;
  280. }
  281. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  282. if (addr.addr.value == nullptr) {
  283. return;
  284. }
  285. GB_ASSERT(value.type != nullptr);
  286. if (is_type_untyped_undef(value.type)) {
  287. Type *t = lb_addr_type(addr);
  288. value.type = t;
  289. value.value = LLVMGetUndef(lb_type(p->module, t));
  290. } else if (is_type_untyped_nil(value.type)) {
  291. Type *t = lb_addr_type(addr);
  292. value.type = t;
  293. value.value = LLVMConstNull(lb_type(p->module, t));
  294. }
  295. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  296. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  297. }
  298. if (addr.kind == lbAddr_RelativePointer) {
  299. Type *rel_ptr = base_type(lb_addr_type(addr));
  300. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  301. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  302. GB_ASSERT(is_type_pointer(addr.addr.type));
  303. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  304. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  305. lbValue offset = {};
  306. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  307. offset.type = t_uintptr;
  308. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  309. offset = lb_emit_conv(p, offset, t_i64);
  310. }
  311. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  312. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  313. offset = lb_emit_select(p,
  314. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  315. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  316. offset
  317. );
  318. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  319. return;
  320. } else if (addr.kind == lbAddr_RelativeSlice) {
  321. Type *rel_ptr = base_type(lb_addr_type(addr));
  322. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  323. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  324. GB_ASSERT(is_type_pointer(addr.addr.type));
  325. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  326. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  327. lbValue offset = {};
  328. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  329. offset.type = t_uintptr;
  330. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  331. offset = lb_emit_conv(p, offset, t_i64);
  332. }
  333. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  334. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  335. offset = lb_emit_select(p,
  336. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  337. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  338. offset
  339. );
  340. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  341. lbValue len = lb_slice_len(p, value);
  342. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  343. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  344. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  345. return;
  346. } else if (addr.kind == lbAddr_Map) {
  347. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  348. return;
  349. } else if (addr.kind == lbAddr_Context) {
  350. lbAddr old_addr = lb_find_or_generate_context_ptr(p);
  351. // IMPORTANT NOTE(bill, 2021-04-22): reuse unused 'context' variables to minimize stack usage
  352. // This has to be done manually since the optimizer cannot determine when this is possible
  353. bool create_new = true;
  354. for_array(i, p->context_stack) {
  355. lbContextData *ctx_data = &p->context_stack[i];
  356. if (ctx_data->ctx.addr.value == old_addr.addr.value) {
  357. if (ctx_data->uses > 0) {
  358. create_new = true;
  359. } else if (p->scope_index > ctx_data->scope_index) {
  360. create_new = true;
  361. } else {
  362. // gb_printf_err("%.*s (curr:%td) (ctx:%td) (uses:%td)\n", LIT(p->name), p->scope_index, ctx_data->scope_index, ctx_data->uses);
  363. create_new = false;
  364. }
  365. break;
  366. }
  367. }
  368. lbValue next = {};
  369. if (create_new) {
  370. lbValue old = lb_addr_load(p, old_addr);
  371. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  372. lb_addr_store(p, next_addr, old);
  373. lb_push_context_onto_stack(p, next_addr);
  374. next = next_addr.addr;
  375. } else {
  376. next = old_addr.addr;
  377. }
  378. if (addr.ctx.sel.index.count > 0) {
  379. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  380. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  381. lb_emit_store(p, lhs, rhs);
  382. } else {
  383. lbValue lhs = next;
  384. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  385. lb_emit_store(p, lhs, rhs);
  386. }
  387. return;
  388. } else if (addr.kind == lbAddr_SoaVariable) {
  389. Type *t = type_deref(addr.addr.type);
  390. t = base_type(t);
  391. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  392. Type *elem_type = t->Struct.soa_elem;
  393. value = lb_emit_conv(p, value, elem_type);
  394. elem_type = base_type(elem_type);
  395. lbValue index = addr.soa.index;
  396. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  397. Type *t = base_type(type_deref(addr.addr.type));
  398. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  399. lbValue len = lb_soa_struct_len(p, addr.addr);
  400. if (addr.soa.index_expr != nullptr) {
  401. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  402. }
  403. }
  404. isize field_count = 0;
  405. switch (elem_type->kind) {
  406. case Type_Struct:
  407. field_count = elem_type->Struct.fields.count;
  408. break;
  409. case Type_Array:
  410. field_count = cast(isize)elem_type->Array.count;
  411. break;
  412. }
  413. for (isize i = 0; i < field_count; i++) {
  414. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  415. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  416. if (t->Struct.soa_kind == StructSoa_Fixed) {
  417. dst = lb_emit_array_ep(p, dst, index);
  418. lb_emit_store(p, dst, src);
  419. } else {
  420. lbValue field = lb_emit_load(p, dst);
  421. dst = lb_emit_ptr_offset(p, field, index);
  422. lb_emit_store(p, dst, src);
  423. }
  424. }
  425. return;
  426. } else if (addr.kind == lbAddr_Swizzle) {
  427. GB_ASSERT(addr.swizzle.count <= 4);
  428. GB_ASSERT(value.value != nullptr);
  429. value = lb_emit_conv(p, value, lb_addr_type(addr));
  430. lbValue dst = lb_addr_get_ptr(p, addr);
  431. lbValue src = lb_address_from_load_or_generate_local(p, value);
  432. {
  433. lbValue src_ptrs[4] = {};
  434. lbValue src_loads[4] = {};
  435. lbValue dst_ptrs[4] = {};
  436. for (u8 i = 0; i < addr.swizzle.count; i++) {
  437. src_ptrs[i] = lb_emit_array_epi(p, src, i);
  438. }
  439. for (u8 i = 0; i < addr.swizzle.count; i++) {
  440. dst_ptrs[i] = lb_emit_array_epi(p, dst, addr.swizzle.indices[i]);
  441. }
  442. for (u8 i = 0; i < addr.swizzle.count; i++) {
  443. src_loads[i] = lb_emit_load(p, src_ptrs[i]);
  444. }
  445. for (u8 i = 0; i < addr.swizzle.count; i++) {
  446. lb_emit_store(p, dst_ptrs[i], src_loads[i]);
  447. }
  448. }
  449. return;
  450. }
  451. GB_ASSERT(value.value != nullptr);
  452. value = lb_emit_conv(p, value, lb_addr_type(addr));
  453. // if (lb_is_const_or_global(value)) {
  454. // // NOTE(bill): Just bypass the actual storage and set the initializer
  455. // if (LLVMGetValueKind(addr.addr.value) == LLVMGlobalVariableValueKind) {
  456. // LLVMValueRef dst = addr.addr.value;
  457. // LLVMValueRef src = value.value;
  458. // LLVMSetInitializer(dst, src);
  459. // return;
  460. // }
  461. // }
  462. lb_emit_store(p, addr.addr, value);
  463. }
  464. void lb_const_store(lbValue ptr, lbValue value) {
  465. GB_ASSERT(lb_is_const(ptr));
  466. GB_ASSERT(lb_is_const(value));
  467. GB_ASSERT(is_type_pointer(ptr.type));
  468. LLVMSetInitializer(ptr.value, value.value);
  469. }
  470. bool lb_is_type_proc_recursive(Type *t) {
  471. for (;;) {
  472. if (t == nullptr) {
  473. return false;
  474. }
  475. switch (t->kind) {
  476. case Type_Named:
  477. t = t->Named.base;
  478. break;
  479. case Type_Pointer:
  480. t = t->Pointer.elem;
  481. break;
  482. case Type_Array:
  483. t = t->Array.elem;
  484. break;
  485. case Type_EnumeratedArray:
  486. t = t->EnumeratedArray.elem;
  487. break;
  488. case Type_Slice:
  489. t = t->Slice.elem;
  490. break;
  491. case Type_DynamicArray:
  492. t = t->DynamicArray.elem;
  493. break;
  494. case Type_Proc:
  495. return true;
  496. default:
  497. return false;
  498. }
  499. }
  500. }
  501. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  502. GB_ASSERT(value.value != nullptr);
  503. Type *a = type_deref(ptr.type);
  504. if (is_type_boolean(a)) {
  505. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  506. value = lb_emit_conv(p, value, a);
  507. }
  508. Type *ca = core_type(a);
  509. if (ca->kind == Type_Basic) {
  510. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  511. }
  512. if (lb_is_type_proc_recursive(a)) {
  513. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  514. // stored as regular pointer with no procedure information
  515. LLVMTypeRef src_t = LLVMGetElementType(LLVMTypeOf(ptr.value));
  516. LLVMValueRef v = LLVMBuildPointerCast(p->builder, value.value, src_t, "");
  517. LLVMBuildStore(p->builder, v, ptr.value);
  518. } else {
  519. Type *ca = core_type(a);
  520. if (ca->kind == Type_Basic || ca->kind == Type_Proc) {
  521. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  522. } else {
  523. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  524. }
  525. LLVMBuildStore(p->builder, value.value, ptr.value);
  526. }
  527. }
  528. LLVMTypeRef llvm_addr_type(lbValue addr_val) {
  529. return LLVMGetElementType(LLVMTypeOf(addr_val.value));
  530. }
  531. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  532. lbModule *m = p->module;
  533. GB_ASSERT(value.value != nullptr);
  534. GB_ASSERT(is_type_pointer(value.type));
  535. Type *t = type_deref(value.type);
  536. LLVMValueRef v = LLVMBuildLoad2(p->builder, llvm_addr_type(value), value.value, "");
  537. return lbValue{v, t};
  538. }
  539. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  540. GB_ASSERT(addr.addr.value != nullptr);
  541. if (addr.kind == lbAddr_RelativePointer) {
  542. Type *rel_ptr = base_type(lb_addr_type(addr));
  543. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  544. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  545. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  546. offset = lb_emit_load(p, offset);
  547. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  548. offset = lb_emit_conv(p, offset, t_i64);
  549. }
  550. offset = lb_emit_conv(p, offset, t_uintptr);
  551. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  552. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  553. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  554. // NOTE(bill): nil check
  555. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  556. lbValue final_ptr = {};
  557. final_ptr.type = absolute_ptr.type;
  558. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  559. return lb_emit_load(p, final_ptr);
  560. } else if (addr.kind == lbAddr_RelativeSlice) {
  561. Type *rel_ptr = base_type(lb_addr_type(addr));
  562. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  563. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  564. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  565. lbValue offset = lb_emit_load(p, offset_ptr);
  566. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  567. offset = lb_emit_conv(p, offset, t_i64);
  568. }
  569. offset = lb_emit_conv(p, offset, t_uintptr);
  570. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  571. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  572. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  573. Type *slice_elem = slice_type->Slice.elem;
  574. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  575. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  576. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  577. // NOTE(bill): nil check
  578. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  579. lbValue data = {};
  580. data.type = absolute_ptr.type;
  581. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  582. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  583. len = lb_emit_conv(p, len, t_int);
  584. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  585. lb_fill_slice(p, slice, data, len);
  586. return lb_addr_load(p, slice);
  587. } else if (addr.kind == lbAddr_Map) {
  588. Type *map_type = base_type(addr.map.type);
  589. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  590. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  591. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  592. auto args = array_make<lbValue>(permanent_allocator(), 2);
  593. args[0] = h;
  594. args[1] = key;
  595. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  596. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  597. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  598. lbBlock *then = lb_create_block(p, "map.get.then");
  599. lbBlock *done = lb_create_block(p, "map.get.done");
  600. lb_emit_if(p, ok, then, done);
  601. lb_start_block(p, then);
  602. {
  603. // TODO(bill): mem copy it instead?
  604. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  605. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  606. lb_emit_store(p, gep0, lb_emit_load(p, value));
  607. }
  608. lb_emit_jump(p, done);
  609. lb_start_block(p, done);
  610. if (is_type_tuple(addr.map.result)) {
  611. return lb_addr_load(p, v);
  612. } else {
  613. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  614. return lb_emit_load(p, single);
  615. }
  616. } else if (addr.kind == lbAddr_Context) {
  617. lbValue a = addr.addr;
  618. for_array(i, p->context_stack) {
  619. lbContextData *ctx_data = &p->context_stack[i];
  620. if (ctx_data->ctx.addr.value == a.value) {
  621. ctx_data->uses += 1;
  622. break;
  623. }
  624. }
  625. a.value = LLVMBuildPointerCast(p->builder, a.value, lb_type(p->module, t_context_ptr), "");
  626. if (addr.ctx.sel.index.count > 0) {
  627. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  628. return lb_emit_load(p, b);
  629. } else {
  630. return lb_emit_load(p, a);
  631. }
  632. } else if (addr.kind == lbAddr_SoaVariable) {
  633. Type *t = type_deref(addr.addr.type);
  634. t = base_type(t);
  635. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  636. Type *elem = t->Struct.soa_elem;
  637. lbValue len = {};
  638. if (t->Struct.soa_kind == StructSoa_Fixed) {
  639. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  640. } else {
  641. lbValue v = lb_emit_load(p, addr.addr);
  642. len = lb_soa_struct_len(p, v);
  643. }
  644. lbAddr res = lb_add_local_generated(p, elem, true);
  645. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  646. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  647. }
  648. if (t->Struct.soa_kind == StructSoa_Fixed) {
  649. for_array(i, t->Struct.fields) {
  650. Entity *field = t->Struct.fields[i];
  651. Type *base_type = field->type;
  652. GB_ASSERT(base_type->kind == Type_Array);
  653. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  654. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  655. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  656. lbValue src = lb_emit_load(p, src_ptr);
  657. lb_emit_store(p, dst, src);
  658. }
  659. } else {
  660. isize field_count = t->Struct.fields.count;
  661. if (t->Struct.soa_kind == StructSoa_Slice) {
  662. field_count -= 1;
  663. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  664. field_count -= 3;
  665. }
  666. for (isize i = 0; i < field_count; i++) {
  667. Entity *field = t->Struct.fields[i];
  668. Type *base_type = field->type;
  669. GB_ASSERT(base_type->kind == Type_Pointer);
  670. Type *elem = base_type->Pointer.elem;
  671. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  672. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  673. lbValue src = lb_emit_load(p, src_ptr);
  674. src = lb_emit_ptr_offset(p, src, addr.soa.index);
  675. src = lb_emit_load(p, src);
  676. lb_emit_store(p, dst, src);
  677. }
  678. }
  679. return lb_addr_load(p, res);
  680. } else if (addr.kind == lbAddr_Swizzle) {
  681. Type *array_type = base_type(addr.swizzle.type);
  682. GB_ASSERT(array_type->kind == Type_Array);
  683. unsigned res_align = cast(unsigned)type_align_of(addr.swizzle.type);
  684. static u8 const ordered_indices[4] = {0, 1, 2, 3};
  685. if (gb_memcompare(ordered_indices, addr.swizzle.indices, addr.swizzle.count) == 0) {
  686. if (lb_try_update_alignment(addr.addr, res_align)) {
  687. Type *pt = alloc_type_pointer(addr.swizzle.type);
  688. lbValue res = {};
  689. res.value = LLVMBuildPointerCast(p->builder, addr.addr.value, lb_type(p->module, pt), "");
  690. res.type = pt;
  691. return lb_emit_load(p, res);
  692. }
  693. }
  694. Type *elem_type = base_type(array_type->Array.elem);
  695. lbAddr res = lb_add_local_generated(p, addr.swizzle.type, false);
  696. lbValue ptr = lb_addr_get_ptr(p, res);
  697. GB_ASSERT(is_type_pointer(ptr.type));
  698. LLVMTypeRef vector_type = nullptr;
  699. if (lb_try_vector_cast(p->module, addr.addr, &vector_type)) {
  700. LLVMSetAlignment(res.addr.value, cast(unsigned)lb_alignof(vector_type));
  701. LLVMValueRef vp = LLVMBuildPointerCast(p->builder, addr.addr.value, LLVMPointerType(vector_type, 0), "");
  702. LLVMValueRef v = LLVMBuildLoad2(p->builder, vector_type, vp, "");
  703. LLVMValueRef scalars[4] = {};
  704. for (u8 i = 0; i < addr.swizzle.count; i++) {
  705. scalars[i] = LLVMConstInt(lb_type(p->module, t_u32), addr.swizzle.indices[i], false);
  706. }
  707. LLVMValueRef mask = LLVMConstVector(scalars, addr.swizzle.count);
  708. LLVMValueRef sv = LLVMBuildShuffleVector(p->builder, v, LLVMGetUndef(vector_type), mask, "");
  709. LLVMValueRef dst = LLVMBuildPointerCast(p->builder, ptr.value, LLVMPointerType(LLVMTypeOf(sv), 0), "");
  710. LLVMBuildStore(p->builder, sv, dst);
  711. } else {
  712. for (u8 i = 0; i < addr.swizzle.count; i++) {
  713. u8 index = addr.swizzle.indices[i];
  714. lbValue dst = lb_emit_array_epi(p, ptr, i);
  715. lbValue src = lb_emit_array_epi(p, addr.addr, index);
  716. lb_emit_store(p, dst, lb_emit_load(p, src));
  717. }
  718. }
  719. return lb_addr_load(p, res);
  720. }
  721. if (is_type_proc(addr.addr.type)) {
  722. return addr.addr;
  723. }
  724. return lb_emit_load(p, addr.addr);
  725. }
  726. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  727. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  728. }
  729. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  730. Type *t = u.type;
  731. GB_ASSERT_MSG(is_type_pointer(t) &&
  732. is_type_union(type_deref(t)), "%s", type_to_string(t));
  733. Type *ut = type_deref(t);
  734. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  735. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  736. GB_ASSERT(type_size_of(ut) > 0);
  737. Type *tag_type = union_tag_type(ut);
  738. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  739. unsigned element_count = LLVMCountStructElementTypes(uvt);
  740. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  741. lbValue tag_ptr = {};
  742. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  743. tag_ptr.type = alloc_type_pointer(tag_type);
  744. return tag_ptr;
  745. }
  746. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  747. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  748. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  749. return lb_emit_load(p, tag_ptr);
  750. }
  751. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  752. Type *t = type_deref(parent.type);
  753. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  754. // No tag needed!
  755. } else {
  756. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  757. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  758. }
  759. }
  760. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  761. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  762. lb_emit_store(p, underlying, variant);
  763. lb_emit_store_union_variant_tag(p, parent, variant_type);
  764. }
  765. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  766. unsigned field_count = LLVMCountStructElementTypes(src);
  767. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  768. LLVMGetStructElementTypes(src, fields);
  769. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  770. }
  771. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  772. switch (alignment) {
  773. case 1:
  774. return LLVMArrayType(lb_type(m, t_u8), 0);
  775. case 2:
  776. return LLVMArrayType(lb_type(m, t_u16), 0);
  777. case 4:
  778. return LLVMArrayType(lb_type(m, t_u32), 0);
  779. case 8:
  780. return LLVMArrayType(lb_type(m, t_u64), 0);
  781. case 16:
  782. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  783. default:
  784. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  785. break;
  786. }
  787. return nullptr;
  788. }
  789. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  790. if (!elem_type_can_be_constant(elem_type)) {
  791. return false;
  792. }
  793. if (elem->kind == Ast_FieldValue) {
  794. elem = elem->FieldValue.value;
  795. }
  796. TypeAndValue tav = type_and_value_of_expr(elem);
  797. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  798. return tav.value.kind != ExactValue_Invalid;
  799. }
  800. String lb_mangle_name(lbModule *m, Entity *e) {
  801. String name = e->token.string;
  802. AstPackage *pkg = e->pkg;
  803. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  804. String pkgn = pkg->name;
  805. GB_ASSERT(!rune_is_digit(pkgn[0]));
  806. if (pkgn == "llvm") {
  807. pkgn = str_lit("llvm$");
  808. }
  809. isize max_len = pkgn.len + 1 + name.len + 1;
  810. bool require_suffix_id = is_type_polymorphic(e->type, true);
  811. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  812. require_suffix_id = true;
  813. } else if (is_blank_ident(e->token)) {
  814. require_suffix_id = true;
  815. }if (e->flags & EntityFlag_NotExported) {
  816. require_suffix_id = true;
  817. }
  818. if (require_suffix_id) {
  819. max_len += 21;
  820. }
  821. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  822. isize new_name_len = gb_snprintf(
  823. new_name, max_len,
  824. "%.*s.%.*s", LIT(pkgn), LIT(name)
  825. );
  826. if (require_suffix_id) {
  827. char *str = new_name + new_name_len-1;
  828. isize len = max_len-new_name_len;
  829. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  830. new_name_len += extra-1;
  831. }
  832. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  833. return mangled_name;
  834. }
  835. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  836. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  837. // and as a result, the declaration does not have time to determine what it should be
  838. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  839. if (e->TypeName.ir_mangled_name.len != 0) {
  840. return e->TypeName.ir_mangled_name;
  841. }
  842. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  843. if (p == nullptr) {
  844. Entity *proc = nullptr;
  845. if (e->parent_proc_decl != nullptr) {
  846. proc = e->parent_proc_decl->entity;
  847. } else {
  848. Scope *scope = e->scope;
  849. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  850. scope = scope->parent;
  851. }
  852. GB_ASSERT(scope != nullptr);
  853. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  854. proc = scope->procedure_entity;
  855. }
  856. GB_ASSERT(proc->kind == Entity_Procedure);
  857. if (proc->code_gen_procedure != nullptr) {
  858. p = proc->code_gen_procedure;
  859. }
  860. }
  861. // NOTE(bill): Generate a new name
  862. // parent_proc.name-guid
  863. String ts_name = e->token.string;
  864. if (p != nullptr) {
  865. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  866. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  867. u32 guid = ++p->module->nested_type_name_guid;
  868. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  869. String name = make_string(cast(u8 *)name_text, name_len-1);
  870. e->TypeName.ir_mangled_name = name;
  871. return name;
  872. } else {
  873. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  874. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  875. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  876. static u32 guid = 0;
  877. guid += 1;
  878. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  879. String name = make_string(cast(u8 *)name_text, name_len-1);
  880. e->TypeName.ir_mangled_name = name;
  881. return name;
  882. }
  883. }
  884. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  885. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  886. return e->TypeName.ir_mangled_name;
  887. }
  888. GB_ASSERT(e != nullptr);
  889. if (e->pkg == nullptr) {
  890. return e->token.string;
  891. }
  892. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  893. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  894. }
  895. String name = {};
  896. bool no_name_mangle = false;
  897. if (e->kind == Entity_Variable) {
  898. bool is_foreign = e->Variable.is_foreign;
  899. bool is_export = e->Variable.is_export;
  900. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  901. if (e->Variable.link_name.len > 0) {
  902. return e->Variable.link_name;
  903. }
  904. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  905. return e->Procedure.link_name;
  906. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  907. no_name_mangle = true;
  908. }
  909. if (!no_name_mangle) {
  910. name = lb_mangle_name(m, e);
  911. }
  912. if (name.len == 0) {
  913. name = e->token.string;
  914. }
  915. if (e->kind == Entity_TypeName) {
  916. e->TypeName.ir_mangled_name = name;
  917. } else if (e->kind == Entity_Procedure) {
  918. e->Procedure.link_name = name;
  919. }
  920. return name;
  921. }
  922. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  923. Type *original_type = type;
  924. LLVMContextRef ctx = m->ctx;
  925. i64 size = type_size_of(type); // Check size
  926. GB_ASSERT(type != t_invalid);
  927. switch (type->kind) {
  928. case Type_Basic:
  929. switch (type->Basic.kind) {
  930. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  931. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  932. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  933. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  934. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  935. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  936. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  937. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  938. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  939. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  940. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  941. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  942. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  943. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  944. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  945. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  946. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  947. case Basic_f16: return LLVMHalfTypeInContext(ctx);
  948. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  949. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  950. case Basic_f16le: return LLVMHalfTypeInContext(ctx);
  951. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  952. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  953. case Basic_f16be: return LLVMHalfTypeInContext(ctx);
  954. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  955. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  956. case Basic_complex32:
  957. {
  958. char const *name = "..complex32";
  959. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  960. if (type != nullptr) {
  961. return type;
  962. }
  963. type = LLVMStructCreateNamed(ctx, name);
  964. LLVMTypeRef fields[2] = {
  965. lb_type(m, t_f16),
  966. lb_type(m, t_f16),
  967. };
  968. LLVMStructSetBody(type, fields, 2, false);
  969. return type;
  970. }
  971. case Basic_complex64:
  972. {
  973. char const *name = "..complex64";
  974. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  975. if (type != nullptr) {
  976. return type;
  977. }
  978. type = LLVMStructCreateNamed(ctx, name);
  979. LLVMTypeRef fields[2] = {
  980. lb_type(m, t_f32),
  981. lb_type(m, t_f32),
  982. };
  983. LLVMStructSetBody(type, fields, 2, false);
  984. return type;
  985. }
  986. case Basic_complex128:
  987. {
  988. char const *name = "..complex128";
  989. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  990. if (type != nullptr) {
  991. return type;
  992. }
  993. type = LLVMStructCreateNamed(ctx, name);
  994. LLVMTypeRef fields[2] = {
  995. lb_type(m, t_f64),
  996. lb_type(m, t_f64),
  997. };
  998. LLVMStructSetBody(type, fields, 2, false);
  999. return type;
  1000. }
  1001. case Basic_quaternion64:
  1002. {
  1003. char const *name = "..quaternion64";
  1004. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1005. if (type != nullptr) {
  1006. return type;
  1007. }
  1008. type = LLVMStructCreateNamed(ctx, name);
  1009. LLVMTypeRef fields[4] = {
  1010. lb_type(m, t_f16),
  1011. lb_type(m, t_f16),
  1012. lb_type(m, t_f16),
  1013. lb_type(m, t_f16),
  1014. };
  1015. LLVMStructSetBody(type, fields, 4, false);
  1016. return type;
  1017. }
  1018. case Basic_quaternion128:
  1019. {
  1020. char const *name = "..quaternion128";
  1021. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1022. if (type != nullptr) {
  1023. return type;
  1024. }
  1025. type = LLVMStructCreateNamed(ctx, name);
  1026. LLVMTypeRef fields[4] = {
  1027. lb_type(m, t_f32),
  1028. lb_type(m, t_f32),
  1029. lb_type(m, t_f32),
  1030. lb_type(m, t_f32),
  1031. };
  1032. LLVMStructSetBody(type, fields, 4, false);
  1033. return type;
  1034. }
  1035. case Basic_quaternion256:
  1036. {
  1037. char const *name = "..quaternion256";
  1038. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1039. if (type != nullptr) {
  1040. return type;
  1041. }
  1042. type = LLVMStructCreateNamed(ctx, name);
  1043. LLVMTypeRef fields[4] = {
  1044. lb_type(m, t_f64),
  1045. lb_type(m, t_f64),
  1046. lb_type(m, t_f64),
  1047. lb_type(m, t_f64),
  1048. };
  1049. LLVMStructSetBody(type, fields, 4, false);
  1050. return type;
  1051. }
  1052. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  1053. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  1054. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  1055. case Basic_rawptr: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  1056. case Basic_string:
  1057. {
  1058. char const *name = "..string";
  1059. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1060. if (type != nullptr) {
  1061. return type;
  1062. }
  1063. type = LLVMStructCreateNamed(ctx, name);
  1064. LLVMTypeRef fields[2] = {
  1065. LLVMPointerType(lb_type(m, t_u8), 0),
  1066. lb_type(m, t_int),
  1067. };
  1068. LLVMStructSetBody(type, fields, 2, false);
  1069. return type;
  1070. }
  1071. case Basic_cstring: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  1072. case Basic_any:
  1073. {
  1074. char const *name = "..any";
  1075. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1076. if (type != nullptr) {
  1077. return type;
  1078. }
  1079. type = LLVMStructCreateNamed(ctx, name);
  1080. LLVMTypeRef fields[2] = {
  1081. lb_type(m, t_rawptr),
  1082. lb_type(m, t_typeid),
  1083. };
  1084. LLVMStructSetBody(type, fields, 2, false);
  1085. return type;
  1086. }
  1087. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.word_size);
  1088. // Endian Specific Types
  1089. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  1090. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  1091. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  1092. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  1093. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  1094. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  1095. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  1096. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  1097. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  1098. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  1099. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  1100. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  1101. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  1102. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  1103. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  1104. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  1105. // Untyped types
  1106. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1107. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1108. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1109. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1110. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1111. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1112. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1113. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1114. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1115. }
  1116. break;
  1117. case Type_Named:
  1118. {
  1119. Type *base = base_type(type->Named.base);
  1120. switch (base->kind) {
  1121. case Type_Basic:
  1122. return lb_type_internal(m, base);
  1123. case Type_Named:
  1124. case Type_Generic:
  1125. GB_PANIC("INVALID TYPE");
  1126. break;
  1127. case Type_Pointer:
  1128. case Type_Array:
  1129. case Type_EnumeratedArray:
  1130. case Type_Slice:
  1131. case Type_DynamicArray:
  1132. case Type_Map:
  1133. case Type_Enum:
  1134. case Type_BitSet:
  1135. case Type_SimdVector:
  1136. return lb_type_internal(m, base);
  1137. // TODO(bill): Deal with this correctly. Can this be named?
  1138. case Type_Proc:
  1139. return lb_type_internal(m, base);
  1140. case Type_Tuple:
  1141. return lb_type_internal(m, base);
  1142. }
  1143. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  1144. if (found) {
  1145. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1146. if (kind == LLVMStructTypeKind) {
  1147. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1148. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1149. if (llvm_type != nullptr) {
  1150. return llvm_type;
  1151. }
  1152. llvm_type = LLVMStructCreateNamed(ctx, name);
  1153. map_set(&m->types, hash_type(type), llvm_type);
  1154. lb_clone_struct_type(llvm_type, *found);
  1155. return llvm_type;
  1156. }
  1157. }
  1158. switch (base->kind) {
  1159. case Type_Struct:
  1160. case Type_Union:
  1161. {
  1162. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1163. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1164. if (llvm_type != nullptr) {
  1165. return llvm_type;
  1166. }
  1167. llvm_type = LLVMStructCreateNamed(ctx, name);
  1168. map_set(&m->types, hash_type(type), llvm_type);
  1169. lb_clone_struct_type(llvm_type, lb_type(m, base));
  1170. return llvm_type;
  1171. }
  1172. }
  1173. return lb_type_internal(m, base);
  1174. }
  1175. case Type_Pointer:
  1176. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1177. case Type_Array: {
  1178. m->internal_type_level -= 1;
  1179. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1180. m->internal_type_level += 1;
  1181. return t;
  1182. }
  1183. case Type_EnumeratedArray: {
  1184. m->internal_type_level -= 1;
  1185. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1186. m->internal_type_level += 1;
  1187. return t;
  1188. }
  1189. case Type_Slice:
  1190. {
  1191. LLVMTypeRef fields[2] = {
  1192. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1193. lb_type(m, t_int), // len
  1194. };
  1195. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1196. }
  1197. break;
  1198. case Type_DynamicArray:
  1199. {
  1200. LLVMTypeRef fields[4] = {
  1201. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1202. lb_type(m, t_int), // len
  1203. lb_type(m, t_int), // cap
  1204. lb_type(m, t_allocator), // allocator
  1205. };
  1206. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1207. }
  1208. break;
  1209. case Type_Map:
  1210. return lb_type(m, type->Map.internal_type);
  1211. case Type_Struct:
  1212. {
  1213. if (type->Struct.is_raw_union) {
  1214. unsigned field_count = 2;
  1215. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1216. i64 alignment = type_align_of(type);
  1217. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1218. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1219. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1220. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1221. }
  1222. isize offset = 0;
  1223. if (type->Struct.custom_align > 0) {
  1224. offset = 1;
  1225. }
  1226. m->internal_type_level += 1;
  1227. defer (m->internal_type_level -= 1);
  1228. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1229. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1230. for_array(i, type->Struct.fields) {
  1231. Entity *field = type->Struct.fields[i];
  1232. fields[i+offset] = lb_type(m, field->type);
  1233. }
  1234. if (type->Struct.custom_align > 0) {
  1235. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1236. }
  1237. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1238. }
  1239. break;
  1240. case Type_Union:
  1241. if (type->Union.variants.count == 0) {
  1242. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1243. } else {
  1244. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1245. // LLVM takes the first element's alignment as the entire alignment (like C)
  1246. i64 align = type_align_of(type);
  1247. i64 size = type_size_of(type);
  1248. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1249. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1250. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1251. }
  1252. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1253. LLVMTypeRef fields[3] = {};
  1254. unsigned field_count = 1;
  1255. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1256. if (is_type_union_maybe_pointer(type)) {
  1257. field_count += 1;
  1258. fields[1] = lb_type(m, type->Union.variants[0]);
  1259. } else {
  1260. field_count += 2;
  1261. if (block_size == align) {
  1262. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1263. } else {
  1264. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1265. }
  1266. fields[2] = lb_type(m, union_tag_type(type));
  1267. }
  1268. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1269. }
  1270. break;
  1271. case Type_Enum:
  1272. return lb_type(m, base_enum_type(type));
  1273. case Type_Tuple:
  1274. if (type->Tuple.variables.count == 1) {
  1275. return lb_type(m, type->Tuple.variables[0]->type);
  1276. } else {
  1277. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1278. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1279. for_array(i, type->Tuple.variables) {
  1280. Entity *field = type->Tuple.variables[i];
  1281. LLVMTypeRef param_type = nullptr;
  1282. param_type = lb_type(m, field->type);
  1283. fields[i] = param_type;
  1284. }
  1285. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1286. }
  1287. case Type_Proc:
  1288. // if (m->internal_type_level > 256) { // TODO HACK(bill): is this really enough?
  1289. if (m->internal_type_level > 1) { // TODO HACK(bill): is this really enough?
  1290. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1291. } else {
  1292. unsigned param_count = 0;
  1293. if (type->Proc.calling_convention == ProcCC_Odin) {
  1294. param_count += 1;
  1295. }
  1296. if (type->Proc.param_count != 0) {
  1297. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1298. for_array(i, type->Proc.params->Tuple.variables) {
  1299. Entity *e = type->Proc.params->Tuple.variables[i];
  1300. if (e->kind != Entity_Variable) {
  1301. continue;
  1302. }
  1303. if (e->flags & EntityFlag_CVarArg) {
  1304. continue;
  1305. }
  1306. param_count += 1;
  1307. }
  1308. }
  1309. m->internal_type_level += 1;
  1310. defer (m->internal_type_level -= 1);
  1311. LLVMTypeRef ret = nullptr;
  1312. LLVMTypeRef *params = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1313. if (type->Proc.result_count != 0) {
  1314. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1315. ret = lb_type(m, single_ret);
  1316. if (ret != nullptr) {
  1317. if (is_type_boolean(single_ret) &&
  1318. is_calling_convention_none(type->Proc.calling_convention) &&
  1319. type_size_of(single_ret) <= 1) {
  1320. ret = LLVMInt1TypeInContext(m->ctx);
  1321. }
  1322. }
  1323. }
  1324. unsigned param_index = 0;
  1325. if (type->Proc.param_count != 0) {
  1326. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1327. for_array(i, type->Proc.params->Tuple.variables) {
  1328. Entity *e = type->Proc.params->Tuple.variables[i];
  1329. if (e->kind != Entity_Variable) {
  1330. continue;
  1331. }
  1332. if (e->flags & EntityFlag_CVarArg) {
  1333. continue;
  1334. }
  1335. Type *e_type = reduce_tuple_to_single_type(e->type);
  1336. LLVMTypeRef param_type = nullptr;
  1337. if (is_type_boolean(e_type) &&
  1338. type_size_of(e_type) <= 1) {
  1339. param_type = LLVMInt1TypeInContext(m->ctx);
  1340. } else {
  1341. if (is_type_proc(e_type)) {
  1342. param_type = lb_type(m, t_rawptr);
  1343. } else {
  1344. param_type = lb_type(m, e_type);
  1345. }
  1346. }
  1347. params[param_index++] = param_type;
  1348. }
  1349. }
  1350. if (param_index < param_count) {
  1351. params[param_index++] = lb_type(m, t_rawptr);
  1352. }
  1353. GB_ASSERT(param_index == param_count);
  1354. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1355. {
  1356. for_array(j, ft->args) {
  1357. auto arg = ft->args[j];
  1358. GB_ASSERT_MSG(LLVMGetTypeContext(arg.type) == ft->ctx,
  1359. "\n\t%s %td/%td"
  1360. "\n\tArgTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1361. LLVMPrintTypeToString(arg.type),
  1362. j, ft->args.count,
  1363. LLVMGetTypeContext(arg.type), ft->ctx, LLVMGetGlobalContext());
  1364. }
  1365. GB_ASSERT_MSG(LLVMGetTypeContext(ft->ret.type) == ft->ctx,
  1366. "\n\t%s"
  1367. "\n\tRetTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1368. LLVMPrintTypeToString(ft->ret.type),
  1369. LLVMGetTypeContext(ft->ret.type), ft->ctx, LLVMGetGlobalContext());
  1370. }
  1371. map_set(&m->function_type_map, hash_type(type), ft);
  1372. LLVMTypeRef new_abi_fn_ptr_type = lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1373. LLVMTypeRef new_abi_fn_type = LLVMGetElementType(new_abi_fn_ptr_type);
  1374. GB_ASSERT_MSG(LLVMGetTypeContext(new_abi_fn_type) == m->ctx,
  1375. "\n\tFuncTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1376. LLVMGetTypeContext(new_abi_fn_type), m->ctx, LLVMGetGlobalContext());
  1377. return new_abi_fn_ptr_type;
  1378. }
  1379. break;
  1380. case Type_BitSet:
  1381. {
  1382. Type *ut = bit_set_to_int(type);
  1383. return lb_type(m, ut);
  1384. }
  1385. case Type_SimdVector:
  1386. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1387. case Type_RelativePointer:
  1388. return lb_type_internal(m, type->RelativePointer.base_integer);
  1389. case Type_RelativeSlice:
  1390. {
  1391. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1392. unsigned field_count = 2;
  1393. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1394. fields[0] = base_integer;
  1395. fields[1] = base_integer;
  1396. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1397. }
  1398. }
  1399. GB_PANIC("Invalid type %s", type_to_string(type));
  1400. return LLVMInt32TypeInContext(ctx);
  1401. }
  1402. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1403. type = default_type(type);
  1404. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1405. if (found) {
  1406. return *found;
  1407. }
  1408. LLVMTypeRef llvm_type = nullptr;
  1409. m->internal_type_level += 1;
  1410. llvm_type = lb_type_internal(m, type);
  1411. m->internal_type_level -= 1;
  1412. if (m->internal_type_level == 0) {
  1413. map_set(&m->types, hash_type(type), llvm_type);
  1414. if (is_type_named(type)) {
  1415. map_set(&m->llvm_types, hash_pointer(llvm_type), type);
  1416. }
  1417. }
  1418. return llvm_type;
  1419. }
  1420. lbFunctionType *lb_get_function_type(lbModule *m, lbProcedure *p, Type *pt) {
  1421. lbFunctionType **ft_found = nullptr;
  1422. ft_found = map_get(&m->function_type_map, hash_type(pt));
  1423. if (!ft_found) {
  1424. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  1425. ft_found = map_get(&m->function_type_map, hash_type(pt));
  1426. }
  1427. GB_ASSERT(ft_found != nullptr);
  1428. return *ft_found;
  1429. }
  1430. LLVMMetadataRef lb_get_llvm_metadata(lbModule *m, void *key) {
  1431. if (key == nullptr) {
  1432. return nullptr;
  1433. }
  1434. auto found = map_get(&m->debug_values, hash_pointer(key));
  1435. if (found) {
  1436. return *found;
  1437. }
  1438. return nullptr;
  1439. }
  1440. void lb_set_llvm_metadata(lbModule *m, void *key, LLVMMetadataRef value) {
  1441. if (key != nullptr) {
  1442. map_set(&m->debug_values, hash_pointer(key), value);
  1443. }
  1444. }
  1445. LLVMMetadataRef lb_get_llvm_file_metadata_from_node(lbModule *m, Ast *node) {
  1446. if (node == nullptr) {
  1447. return nullptr;
  1448. }
  1449. return lb_get_llvm_metadata(m, node->file);
  1450. }
  1451. LLVMMetadataRef lb_get_current_debug_scope(lbProcedure *p) {
  1452. GB_ASSERT_MSG(p->debug_info != nullptr, "missing debug information for %.*s", LIT(p->name));
  1453. for (isize i = p->scope_stack.count-1; i >= 0; i--) {
  1454. Scope *s = p->scope_stack[i];
  1455. LLVMMetadataRef md = lb_get_llvm_metadata(p->module, s);
  1456. if (md) {
  1457. return md;
  1458. }
  1459. }
  1460. return p->debug_info;
  1461. }
  1462. LLVMMetadataRef lb_debug_location_from_token_pos(lbProcedure *p, TokenPos pos) {
  1463. LLVMMetadataRef scope = lb_get_current_debug_scope(p);
  1464. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  1465. return LLVMDIBuilderCreateDebugLocation(p->module->ctx, cast(unsigned)pos.line, cast(unsigned)pos.column, scope, nullptr);
  1466. }
  1467. LLVMMetadataRef lb_debug_location_from_ast(lbProcedure *p, Ast *node) {
  1468. GB_ASSERT(node != nullptr);
  1469. return lb_debug_location_from_token_pos(p, ast_token(node).pos);
  1470. }
  1471. LLVMMetadataRef lb_debug_type_internal_proc(lbModule *m, Type *type) {
  1472. Type *original_type = type;
  1473. LLVMContextRef ctx = m->ctx;
  1474. i64 size = type_size_of(type); // Check size
  1475. GB_ASSERT(type != t_invalid);
  1476. unsigned const word_size = cast(unsigned)build_context.word_size;
  1477. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1478. GB_ASSERT(type->kind == Type_Proc);
  1479. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1480. unsigned parameter_count = 1;
  1481. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1482. Entity *e = type->Proc.params->Tuple.variables[i];
  1483. if (e->kind == Entity_Variable) {
  1484. parameter_count += 1;
  1485. }
  1486. }
  1487. LLVMMetadataRef *parameters = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, parameter_count);
  1488. unsigned param_index = 0;
  1489. if (type->Proc.result_count == 0) {
  1490. parameters[param_index++] = nullptr;
  1491. } else {
  1492. parameters[param_index++] = lb_debug_type(m, type->Proc.results);
  1493. }
  1494. LLVMMetadataRef parent_scope = nullptr;
  1495. LLVMMetadataRef scope = nullptr;
  1496. LLVMMetadataRef file = nullptr;
  1497. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1498. Entity *e = type->Proc.params->Tuple.variables[i];
  1499. if (e->kind != Entity_Variable) {
  1500. continue;
  1501. }
  1502. parameters[param_index] = lb_debug_type(m, e->type);
  1503. param_index += 1;
  1504. }
  1505. LLVMDIFlags flags = LLVMDIFlagZero;
  1506. if (type->Proc.diverging) {
  1507. flags = LLVMDIFlagNoReturn;
  1508. }
  1509. return LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, parameters, parameter_count, flags);
  1510. }
  1511. LLVMMetadataRef lb_debug_struct_field(lbModule *m, String const &name, Type *type, u64 offset_in_bits) {
  1512. unsigned field_line = 1;
  1513. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1514. AstPackage *pkg = m->info->runtime_package;
  1515. GB_ASSERT(pkg->files.count != 0);
  1516. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1517. LLVMMetadataRef scope = file;
  1518. return LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1519. 8*cast(u64)type_size_of(type), 8*cast(u32)type_align_of(type), offset_in_bits,
  1520. field_flags, lb_debug_type(m, type)
  1521. );
  1522. }
  1523. LLVMMetadataRef lb_debug_basic_struct(lbModule *m, String const &name, u64 size_in_bits, u32 align_in_bits, LLVMMetadataRef *elements, unsigned element_count) {
  1524. AstPackage *pkg = m->info->runtime_package;
  1525. GB_ASSERT(pkg->files.count != 0);
  1526. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1527. LLVMMetadataRef scope = file;
  1528. 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);
  1529. }
  1530. LLVMMetadataRef lb_debug_type_basic_type(lbModule *m, String const &name, u64 size_in_bits, LLVMDWARFTypeEncoding encoding, LLVMDIFlags flags = LLVMDIFlagZero) {
  1531. LLVMMetadataRef basic_type = LLVMDIBuilderCreateBasicType(m->debug_builder, cast(char const *)name.text, name.len, size_in_bits, encoding, flags);
  1532. #if 1
  1533. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, basic_type, cast(char const *)name.text, name.len, nullptr, 0, nullptr, cast(u32)size_in_bits);
  1534. return final_decl;
  1535. #else
  1536. return basic_type;
  1537. #endif
  1538. }
  1539. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1540. Type *original_type = type;
  1541. LLVMContextRef ctx = m->ctx;
  1542. i64 size = type_size_of(type); // Check size
  1543. GB_ASSERT(type != t_invalid);
  1544. unsigned const word_size = cast(unsigned)build_context.word_size;
  1545. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1546. switch (type->kind) {
  1547. case Type_Basic:
  1548. switch (type->Basic.kind) {
  1549. case Basic_llvm_bool: return lb_debug_type_basic_type(m, str_lit("llvm bool"), 1, LLVMDWARFTypeEncoding_Boolean);
  1550. case Basic_bool: return lb_debug_type_basic_type(m, str_lit("bool"), 8, LLVMDWARFTypeEncoding_Boolean);
  1551. case Basic_b8: return lb_debug_type_basic_type(m, str_lit("b8"), 8, LLVMDWARFTypeEncoding_Boolean);
  1552. case Basic_b16: return lb_debug_type_basic_type(m, str_lit("b16"), 16, LLVMDWARFTypeEncoding_Boolean);
  1553. case Basic_b32: return lb_debug_type_basic_type(m, str_lit("b32"), 32, LLVMDWARFTypeEncoding_Boolean);
  1554. case Basic_b64: return lb_debug_type_basic_type(m, str_lit("b64"), 64, LLVMDWARFTypeEncoding_Boolean);
  1555. case Basic_i8: return lb_debug_type_basic_type(m, str_lit("i8"), 8, LLVMDWARFTypeEncoding_Signed);
  1556. case Basic_u8: return lb_debug_type_basic_type(m, str_lit("u8"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1557. case Basic_i16: return lb_debug_type_basic_type(m, str_lit("i16"), 16, LLVMDWARFTypeEncoding_Signed);
  1558. case Basic_u16: return lb_debug_type_basic_type(m, str_lit("u16"), 16, LLVMDWARFTypeEncoding_Unsigned);
  1559. case Basic_i32: return lb_debug_type_basic_type(m, str_lit("i32"), 32, LLVMDWARFTypeEncoding_Signed);
  1560. case Basic_u32: return lb_debug_type_basic_type(m, str_lit("u32"), 32, LLVMDWARFTypeEncoding_Unsigned);
  1561. case Basic_i64: return lb_debug_type_basic_type(m, str_lit("i64"), 64, LLVMDWARFTypeEncoding_Signed);
  1562. case Basic_u64: return lb_debug_type_basic_type(m, str_lit("u64"), 64, LLVMDWARFTypeEncoding_Unsigned);
  1563. case Basic_i128: return lb_debug_type_basic_type(m, str_lit("i128"), 128, LLVMDWARFTypeEncoding_Signed);
  1564. case Basic_u128: return lb_debug_type_basic_type(m, str_lit("u128"), 128, LLVMDWARFTypeEncoding_Unsigned);
  1565. case Basic_rune: return lb_debug_type_basic_type(m, str_lit("rune"), 32, LLVMDWARFTypeEncoding_Utf);
  1566. case Basic_f16: return lb_debug_type_basic_type(m, str_lit("f16"), 16, LLVMDWARFTypeEncoding_Float);
  1567. case Basic_f32: return lb_debug_type_basic_type(m, str_lit("f32"), 32, LLVMDWARFTypeEncoding_Float);
  1568. case Basic_f64: return lb_debug_type_basic_type(m, str_lit("f64"), 64, LLVMDWARFTypeEncoding_Float);
  1569. case Basic_int: return lb_debug_type_basic_type(m, str_lit("int"), word_bits, LLVMDWARFTypeEncoding_Signed);
  1570. case Basic_uint: return lb_debug_type_basic_type(m, str_lit("uint"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1571. case Basic_uintptr: return lb_debug_type_basic_type(m, str_lit("uintptr"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1572. case Basic_typeid:
  1573. return lb_debug_type_basic_type(m, str_lit("typeid"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1574. // Endian Specific Types
  1575. case Basic_i16le: return lb_debug_type_basic_type(m, str_lit("i16le"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1576. case Basic_u16le: return lb_debug_type_basic_type(m, str_lit("u16le"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1577. case Basic_i32le: return lb_debug_type_basic_type(m, str_lit("i32le"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1578. case Basic_u32le: return lb_debug_type_basic_type(m, str_lit("u32le"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1579. case Basic_i64le: return lb_debug_type_basic_type(m, str_lit("i64le"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1580. case Basic_u64le: return lb_debug_type_basic_type(m, str_lit("u64le"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1581. case Basic_i128le: return lb_debug_type_basic_type(m, str_lit("i128le"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1582. case Basic_u128le: return lb_debug_type_basic_type(m, str_lit("u128le"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1583. case Basic_f16le: return lb_debug_type_basic_type(m, str_lit("f16le"), 16, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1584. case Basic_f32le: return lb_debug_type_basic_type(m, str_lit("f32le"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1585. case Basic_f64le: return lb_debug_type_basic_type(m, str_lit("f64le"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1586. case Basic_i16be: return lb_debug_type_basic_type(m, str_lit("i16be"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1587. case Basic_u16be: return lb_debug_type_basic_type(m, str_lit("u16be"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1588. case Basic_i32be: return lb_debug_type_basic_type(m, str_lit("i32be"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1589. case Basic_u32be: return lb_debug_type_basic_type(m, str_lit("u32be"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1590. case Basic_i64be: return lb_debug_type_basic_type(m, str_lit("i64be"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1591. case Basic_u64be: return lb_debug_type_basic_type(m, str_lit("u64be"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1592. case Basic_i128be: return lb_debug_type_basic_type(m, str_lit("i128be"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1593. case Basic_u128be: return lb_debug_type_basic_type(m, str_lit("u128be"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1594. case Basic_f16be: return lb_debug_type_basic_type(m, str_lit("f16be"), 16, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1595. case Basic_f32be: return lb_debug_type_basic_type(m, str_lit("f32be"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1596. case Basic_f64be: return lb_debug_type_basic_type(m, str_lit("f64be"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1597. case Basic_complex32:
  1598. {
  1599. LLVMMetadataRef elements[2] = {};
  1600. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f16, 0);
  1601. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f16, 4);
  1602. return lb_debug_basic_struct(m, str_lit("complex32"), 64, 32, elements, gb_count_of(elements));
  1603. }
  1604. case Basic_complex64:
  1605. {
  1606. LLVMMetadataRef elements[2] = {};
  1607. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f32, 0);
  1608. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 4);
  1609. return lb_debug_basic_struct(m, str_lit("complex64"), 64, 32, elements, gb_count_of(elements));
  1610. }
  1611. case Basic_complex128:
  1612. {
  1613. LLVMMetadataRef elements[2] = {};
  1614. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f64, 0);
  1615. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 8);
  1616. return lb_debug_basic_struct(m, str_lit("complex128"), 128, 64, elements, gb_count_of(elements));
  1617. }
  1618. case Basic_quaternion64:
  1619. {
  1620. LLVMMetadataRef elements[4] = {};
  1621. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f16, 0);
  1622. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f16, 4);
  1623. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f16, 8);
  1624. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f16, 12);
  1625. return lb_debug_basic_struct(m, str_lit("quaternion64"), 128, 32, elements, gb_count_of(elements));
  1626. }
  1627. case Basic_quaternion128:
  1628. {
  1629. LLVMMetadataRef elements[4] = {};
  1630. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 0);
  1631. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f32, 4);
  1632. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f32, 8);
  1633. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f32, 12);
  1634. return lb_debug_basic_struct(m, str_lit("quaternion128"), 128, 32, elements, gb_count_of(elements));
  1635. }
  1636. case Basic_quaternion256:
  1637. {
  1638. LLVMMetadataRef elements[4] = {};
  1639. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 0);
  1640. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f64, 8);
  1641. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f64, 16);
  1642. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f64, 24);
  1643. return lb_debug_basic_struct(m, str_lit("quaternion256"), 256, 32, elements, gb_count_of(elements));
  1644. }
  1645. case Basic_rawptr:
  1646. {
  1647. LLVMMetadataRef void_type = lb_debug_type_basic_type(m, str_lit("void"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1648. return LLVMDIBuilderCreatePointerType(m->debug_builder, void_type, word_bits, word_bits, LLVMDWARFTypeEncoding_Address, "rawptr", 6);
  1649. }
  1650. case Basic_string:
  1651. {
  1652. LLVMMetadataRef elements[2] = {};
  1653. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_u8_ptr, 0);
  1654. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, word_bits);
  1655. return lb_debug_basic_struct(m, str_lit("string"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1656. }
  1657. case Basic_cstring:
  1658. {
  1659. LLVMMetadataRef char_type = lb_debug_type_basic_type(m, str_lit("char"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1660. return LLVMDIBuilderCreatePointerType(m->debug_builder, char_type, word_bits, word_bits, 0, "cstring", 7);
  1661. }
  1662. case Basic_any:
  1663. {
  1664. LLVMMetadataRef elements[2] = {};
  1665. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_rawptr, 0);
  1666. elements[1] = lb_debug_struct_field(m, str_lit("id"), t_typeid, word_bits);
  1667. return lb_debug_basic_struct(m, str_lit("any"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1668. }
  1669. // Untyped types
  1670. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1671. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1672. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1673. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1674. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1675. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1676. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1677. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1678. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1679. default: GB_PANIC("Basic Unhandled"); break;
  1680. }
  1681. break;
  1682. case Type_Named:
  1683. GB_PANIC("Type_Named should be handled in lb_debug_type separately");
  1684. case Type_Pointer:
  1685. return LLVMDIBuilderCreatePointerType(m->debug_builder, lb_debug_type(m, type->Pointer.elem), word_bits, word_bits, 0, nullptr, 0);
  1686. case Type_Array: {
  1687. LLVMMetadataRef subscripts[1] = {};
  1688. subscripts[0] = LLVMDIBuilderGetOrCreateSubrange(m->debug_builder,
  1689. 0ll,
  1690. type->Array.count
  1691. );
  1692. return LLVMDIBuilderCreateArrayType(m->debug_builder,
  1693. 8*cast(uint64_t)type_size_of(type),
  1694. 8*cast(unsigned)type_align_of(type),
  1695. lb_debug_type(m, type->Array.elem),
  1696. subscripts, gb_count_of(subscripts));
  1697. }
  1698. case Type_EnumeratedArray: {
  1699. LLVMMetadataRef subscripts[1] = {};
  1700. subscripts[0] = LLVMDIBuilderGetOrCreateSubrange(m->debug_builder,
  1701. 0ll,
  1702. type->EnumeratedArray.count
  1703. );
  1704. LLVMMetadataRef array_type = LLVMDIBuilderCreateArrayType(m->debug_builder,
  1705. 8*cast(uint64_t)type_size_of(type),
  1706. 8*cast(unsigned)type_align_of(type),
  1707. lb_debug_type(m, type->EnumeratedArray.elem),
  1708. subscripts, gb_count_of(subscripts));
  1709. gbString name = type_to_string(type, temporary_allocator());
  1710. return LLVMDIBuilderCreateTypedef(m->debug_builder, array_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1711. }
  1712. case Type_Struct:
  1713. case Type_Union:
  1714. case Type_Slice:
  1715. case Type_DynamicArray:
  1716. case Type_Map:
  1717. case Type_BitSet:
  1718. {
  1719. unsigned tag = DW_TAG_structure_type;
  1720. if (is_type_raw_union(type) || is_type_union(type)) {
  1721. tag = DW_TAG_union_type;
  1722. }
  1723. u64 size_in_bits = cast(u64)(8*type_size_of(type));
  1724. u32 align_in_bits = cast(u32)(8*type_size_of(type));
  1725. LLVMDIFlags flags = LLVMDIFlagZero;
  1726. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1727. m->debug_builder, tag, "", 0, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1728. );
  1729. lbIncompleteDebugType idt = {};
  1730. idt.type = type;
  1731. idt.metadata = temp_forward_decl;
  1732. array_add(&m->debug_incomplete_types, idt);
  1733. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1734. return temp_forward_decl;
  1735. }
  1736. case Type_Enum:
  1737. {
  1738. LLVMMetadataRef scope = nullptr;
  1739. LLVMMetadataRef file = nullptr;
  1740. unsigned line = 0;
  1741. unsigned element_count = cast(unsigned)type->Enum.fields.count;
  1742. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1743. Type *bt = base_enum_type(type);
  1744. LLVMBool is_unsigned = is_type_unsigned(bt);
  1745. for (unsigned i = 0; i < element_count; i++) {
  1746. Entity *f = type->Enum.fields[i];
  1747. GB_ASSERT(f->kind == Entity_Constant);
  1748. String name = f->token.string;
  1749. i64 value = exact_value_to_i64(f->Constant.value);
  1750. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1751. }
  1752. LLVMMetadataRef class_type = lb_debug_type(m, bt);
  1753. 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);
  1754. }
  1755. case Type_Tuple:
  1756. if (type->Tuple.variables.count == 1) {
  1757. return lb_debug_type(m, type->Tuple.variables[0]->type);
  1758. } else {
  1759. type_set_offsets(type);
  1760. LLVMMetadataRef parent_scope = nullptr;
  1761. LLVMMetadataRef scope = nullptr;
  1762. LLVMMetadataRef file = nullptr;
  1763. unsigned line = 0;
  1764. u64 size_in_bits = 8*cast(u64)type_size_of(type);
  1765. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1766. LLVMDIFlags flags = LLVMDIFlagZero;
  1767. unsigned element_count = cast(unsigned)type->Tuple.variables.count;
  1768. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1769. for (unsigned i = 0; i < element_count; i++) {
  1770. Entity *f = type->Tuple.variables[i];
  1771. GB_ASSERT(f->kind == Entity_Variable);
  1772. String name = f->token.string;
  1773. unsigned field_line = 0;
  1774. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1775. u64 offset_in_bits = 8*cast(u64)type->Tuple.offsets[i];
  1776. elements[i] = LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1777. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type), offset_in_bits,
  1778. field_flags, lb_debug_type(m, f->type)
  1779. );
  1780. }
  1781. return LLVMDIBuilderCreateStructType(m->debug_builder, parent_scope, "", 0, file, line,
  1782. size_in_bits, align_in_bits, flags,
  1783. nullptr, elements, element_count, 0, nullptr,
  1784. "", 0
  1785. );
  1786. }
  1787. case Type_Proc:
  1788. {
  1789. LLVMMetadataRef proc_underlying_type = lb_debug_type_internal_proc(m, type);
  1790. LLVMMetadataRef pointer_type = LLVMDIBuilderCreatePointerType(m->debug_builder, proc_underlying_type, word_bits, word_bits, 0, nullptr, 0);
  1791. gbString name = type_to_string(type, temporary_allocator());
  1792. return LLVMDIBuilderCreateTypedef(m->debug_builder, pointer_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1793. }
  1794. break;
  1795. case Type_SimdVector:
  1796. 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);
  1797. case Type_RelativePointer: {
  1798. LLVMMetadataRef base_integer = lb_debug_type(m, type->RelativePointer.base_integer);
  1799. gbString name = type_to_string(type, temporary_allocator());
  1800. return LLVMDIBuilderCreateTypedef(m->debug_builder, base_integer, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1801. }
  1802. case Type_RelativeSlice:
  1803. {
  1804. unsigned element_count = 0;
  1805. LLVMMetadataRef elements[2] = {};
  1806. Type *base_integer = type->RelativeSlice.base_integer;
  1807. elements[0] = lb_debug_struct_field(m, str_lit("data_offset"), base_integer, 0);
  1808. elements[1] = lb_debug_struct_field(m, str_lit("len"), base_integer, 8*type_size_of(base_integer));
  1809. gbString name = type_to_string(type, temporary_allocator());
  1810. 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);
  1811. }
  1812. }
  1813. GB_PANIC("Invalid type %s", type_to_string(type));
  1814. return nullptr;
  1815. }
  1816. LLVMMetadataRef lb_get_base_scope_metadata(lbModule *m, Scope *scope) {
  1817. LLVMMetadataRef found = nullptr;
  1818. for (;;) {
  1819. if (scope == nullptr) {
  1820. return nullptr;
  1821. }
  1822. if (scope->flags & ScopeFlag_Proc) {
  1823. found = lb_get_llvm_metadata(m, scope->procedure_entity);
  1824. if (found) {
  1825. return found;
  1826. }
  1827. }
  1828. if (scope->flags & ScopeFlag_File) {
  1829. found = lb_get_llvm_metadata(m, scope->file);
  1830. if (found) {
  1831. return found;
  1832. }
  1833. }
  1834. scope = scope->parent;
  1835. }
  1836. }
  1837. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1838. GB_ASSERT(type != nullptr);
  1839. LLVMMetadataRef found = lb_get_llvm_metadata(m, type);
  1840. if (found != nullptr) {
  1841. return found;
  1842. }
  1843. if (type->kind == Type_Named) {
  1844. LLVMMetadataRef file = nullptr;
  1845. unsigned line = 0;
  1846. LLVMMetadataRef scope = nullptr;
  1847. if (type->Named.type_name != nullptr) {
  1848. Entity *e = type->Named.type_name;
  1849. scope = lb_get_base_scope_metadata(m, e->scope);
  1850. if (scope != nullptr) {
  1851. file = LLVMDIScopeGetFile(scope);
  1852. }
  1853. line = cast(unsigned)e->token.pos.line;
  1854. }
  1855. // TODO(bill): location data for Type_Named
  1856. u64 size_in_bits = 8*type_size_of(type);
  1857. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1858. String name = type->Named.name;
  1859. char const *name_text = cast(char const *)name.text;
  1860. size_t name_len = cast(size_t)name.len;
  1861. unsigned tag = DW_TAG_structure_type;
  1862. if (is_type_raw_union(type) || is_type_union(type)) {
  1863. tag = DW_TAG_union_type;
  1864. }
  1865. LLVMDIFlags flags = LLVMDIFlagZero;
  1866. Type *bt = base_type(type->Named.base);
  1867. lbIncompleteDebugType idt = {};
  1868. idt.type = type;
  1869. switch (bt->kind) {
  1870. case Type_Enum:
  1871. {
  1872. unsigned line = 0;
  1873. unsigned element_count = cast(unsigned)bt->Enum.fields.count;
  1874. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1875. Type *ct = base_enum_type(type);
  1876. LLVMBool is_unsigned = is_type_unsigned(ct);
  1877. for (unsigned i = 0; i < element_count; i++) {
  1878. Entity *f = bt->Enum.fields[i];
  1879. GB_ASSERT(f->kind == Entity_Constant);
  1880. String name = f->token.string;
  1881. i64 value = exact_value_to_i64(f->Constant.value);
  1882. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1883. }
  1884. LLVMMetadataRef class_type = lb_debug_type(m, ct);
  1885. 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);
  1886. }
  1887. case Type_Basic:
  1888. case Type_Pointer:
  1889. case Type_Array:
  1890. case Type_EnumeratedArray:
  1891. case Type_Tuple:
  1892. case Type_Proc:
  1893. case Type_SimdVector:
  1894. case Type_RelativePointer:
  1895. case Type_RelativeSlice:
  1896. {
  1897. LLVMMetadataRef debug_bt = lb_debug_type(m, bt);
  1898. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, debug_bt, name_text, name_len, file, line, scope, align_in_bits);
  1899. lb_set_llvm_metadata(m, type, final_decl);
  1900. return final_decl;
  1901. }
  1902. case Type_Slice:
  1903. case Type_DynamicArray:
  1904. case Type_Map:
  1905. case Type_Struct:
  1906. case Type_Union:
  1907. case Type_BitSet:
  1908. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1909. m->debug_builder, tag, name_text, name_len, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1910. );
  1911. idt.metadata = temp_forward_decl;
  1912. array_add(&m->debug_incomplete_types, idt);
  1913. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1914. return temp_forward_decl;
  1915. }
  1916. }
  1917. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1918. lb_set_llvm_metadata(m, type, dt);
  1919. return dt;
  1920. }
  1921. void lb_debug_complete_types(lbModule *m) {
  1922. unsigned const word_size = cast(unsigned)build_context.word_size;
  1923. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1924. for_array(debug_incomplete_type_index, m->debug_incomplete_types) {
  1925. auto const &idt = m->debug_incomplete_types[debug_incomplete_type_index];
  1926. GB_ASSERT(idt.type != nullptr);
  1927. GB_ASSERT(idt.metadata != nullptr);
  1928. Type *t = idt.type;
  1929. Type *bt = base_type(t);
  1930. LLVMMetadataRef parent_scope = nullptr;
  1931. LLVMMetadataRef file = nullptr;
  1932. unsigned line_number = 0;
  1933. u64 size_in_bits = 8*type_size_of(t);
  1934. u32 align_in_bits = cast(u32)(8*type_align_of(t));
  1935. LLVMDIFlags flags = LLVMDIFlagZero;
  1936. LLVMMetadataRef derived_from = nullptr;
  1937. LLVMMetadataRef *elements = nullptr;
  1938. unsigned element_count = 0;
  1939. unsigned runtime_lang = 0; // Objective-C runtime version
  1940. char const *unique_id = "";
  1941. LLVMMetadataRef vtable_holder = nullptr;
  1942. size_t unique_id_len = 0;
  1943. LLVMMetadataRef record_scope = nullptr;
  1944. switch (bt->kind) {
  1945. case Type_Slice:
  1946. case Type_DynamicArray:
  1947. case Type_Map:
  1948. case Type_Struct:
  1949. case Type_Union:
  1950. case Type_BitSet: {
  1951. bool is_union = is_type_raw_union(bt) || is_type_union(bt);
  1952. String name = str_lit("<anonymous-struct>");
  1953. if (t->kind == Type_Named) {
  1954. name = t->Named.name;
  1955. if (t->Named.type_name && t->Named.type_name->pkg && t->Named.type_name->pkg->name.len != 0) {
  1956. name = concatenate3_strings(temporary_allocator(), t->Named.type_name->pkg->name, str_lit("."), t->Named.name);
  1957. }
  1958. LLVMMetadataRef file = nullptr;
  1959. unsigned line = 0;
  1960. LLVMMetadataRef file_scope = nullptr;
  1961. if (t->Named.type_name != nullptr) {
  1962. Entity *e = t->Named.type_name;
  1963. file_scope = lb_get_llvm_metadata(m, e->scope);
  1964. if (file_scope != nullptr) {
  1965. file = LLVMDIScopeGetFile(file_scope);
  1966. }
  1967. line = cast(unsigned)e->token.pos.line;
  1968. }
  1969. // TODO(bill): location data for Type_Named
  1970. } else {
  1971. name = make_string_c(type_to_string(t, temporary_allocator()));
  1972. }
  1973. switch (bt->kind) {
  1974. case Type_Slice:
  1975. element_count = 2;
  1976. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1977. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->Slice.elem), 0*word_bits);
  1978. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1979. break;
  1980. case Type_DynamicArray:
  1981. element_count = 4;
  1982. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1983. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->DynamicArray.elem), 0*word_bits);
  1984. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1985. elements[2] = lb_debug_struct_field(m, str_lit("cap"), t_int, 2*word_bits);
  1986. elements[3] = lb_debug_struct_field(m, str_lit("allocator"), t_allocator, 3*word_bits);
  1987. break;
  1988. case Type_Map:
  1989. bt = bt->Map.internal_type;
  1990. /*fallthrough*/
  1991. case Type_Struct:
  1992. if (file == nullptr) {
  1993. if (bt->Struct.node) {
  1994. file = lb_get_llvm_metadata(m, bt->Struct.node->file);
  1995. line_number = cast(unsigned)ast_token(bt->Struct.node).pos.line;
  1996. }
  1997. }
  1998. type_set_offsets(bt);
  1999. {
  2000. isize element_offset = 0;
  2001. record_scope = lb_get_llvm_metadata(m, bt->Struct.scope);
  2002. switch (bt->Struct.soa_kind) {
  2003. case StructSoa_Slice: element_offset = 1; break;
  2004. case StructSoa_Dynamic: element_offset = 3; break;
  2005. }
  2006. element_count = cast(unsigned)(bt->Struct.fields.count + element_offset);
  2007. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  2008. switch (bt->Struct.soa_kind) {
  2009. case StructSoa_Slice:
  2010. elements[0] = LLVMDIBuilderCreateMemberType(
  2011. m->debug_builder, record_scope,
  2012. ".len", 4,
  2013. file, 0,
  2014. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  2015. 8*type_size_of(bt)-word_bits,
  2016. LLVMDIFlagZero, lb_debug_type(m, t_int)
  2017. );
  2018. break;
  2019. case StructSoa_Dynamic:
  2020. elements[0] = LLVMDIBuilderCreateMemberType(
  2021. m->debug_builder, record_scope,
  2022. ".len", 4,
  2023. file, 0,
  2024. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  2025. 8*type_size_of(bt)-word_bits + 0*word_bits,
  2026. LLVMDIFlagZero, lb_debug_type(m, t_int)
  2027. );
  2028. elements[1] = LLVMDIBuilderCreateMemberType(
  2029. m->debug_builder, record_scope,
  2030. ".cap", 4,
  2031. file, 0,
  2032. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  2033. 8*type_size_of(bt)-word_bits + 1*word_bits,
  2034. LLVMDIFlagZero, lb_debug_type(m, t_int)
  2035. );
  2036. elements[2] = LLVMDIBuilderCreateMemberType(
  2037. m->debug_builder, record_scope,
  2038. ".allocator", 12,
  2039. file, 0,
  2040. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  2041. 8*type_size_of(bt)-word_bits + 2*word_bits,
  2042. LLVMDIFlagZero, lb_debug_type(m, t_allocator)
  2043. );
  2044. break;
  2045. }
  2046. for_array(j, bt->Struct.fields) {
  2047. Entity *f = bt->Struct.fields[j];
  2048. String fname = f->token.string;
  2049. unsigned field_line = 0;
  2050. LLVMDIFlags field_flags = LLVMDIFlagZero;
  2051. u64 offset_in_bits = 8*cast(u64)bt->Struct.offsets[j];
  2052. elements[element_offset+j] = LLVMDIBuilderCreateMemberType(
  2053. m->debug_builder, record_scope,
  2054. cast(char const *)fname.text, cast(size_t)fname.len,
  2055. file, field_line,
  2056. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type),
  2057. offset_in_bits,
  2058. field_flags, lb_debug_type(m, f->type)
  2059. );
  2060. }
  2061. }
  2062. break;
  2063. case Type_Union:
  2064. {
  2065. if (file == nullptr) {
  2066. GB_ASSERT(bt->Union.node != nullptr);
  2067. file = lb_get_llvm_metadata(m, bt->Union.node->file);
  2068. line_number = cast(unsigned)ast_token(bt->Union.node).pos.line;
  2069. }
  2070. isize index_offset = 1;
  2071. if (is_type_union_maybe_pointer(bt)) {
  2072. index_offset = 0;
  2073. }
  2074. record_scope = lb_get_llvm_metadata(m, bt->Union.scope);
  2075. element_count = cast(unsigned)bt->Union.variants.count;
  2076. if (index_offset > 0) {
  2077. element_count += 1;
  2078. }
  2079. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  2080. if (index_offset > 0) {
  2081. Type *tag_type = union_tag_type(bt);
  2082. unsigned field_line = 0;
  2083. u64 offset_in_bits = 8*cast(u64)bt->Union.variant_block_size;
  2084. LLVMDIFlags field_flags = LLVMDIFlagZero;
  2085. elements[0] = LLVMDIBuilderCreateMemberType(
  2086. m->debug_builder, record_scope,
  2087. "tag", 3,
  2088. file, field_line,
  2089. 8*cast(u64)type_size_of(tag_type), 8*cast(u32)type_align_of(tag_type),
  2090. offset_in_bits,
  2091. field_flags, lb_debug_type(m, tag_type)
  2092. );
  2093. }
  2094. for_array(j, bt->Union.variants) {
  2095. Type *variant = bt->Union.variants[j];
  2096. unsigned field_index = cast(unsigned)(index_offset+j);
  2097. char name[16] = {};
  2098. gb_snprintf(name, gb_size_of(name), "v%u", field_index);
  2099. isize name_len = gb_strlen(name);
  2100. unsigned field_line = 0;
  2101. LLVMDIFlags field_flags = LLVMDIFlagZero;
  2102. u64 offset_in_bits = 0;
  2103. elements[field_index] = LLVMDIBuilderCreateMemberType(
  2104. m->debug_builder, record_scope,
  2105. name, name_len,
  2106. file, field_line,
  2107. 8*cast(u64)type_size_of(variant), 8*cast(u32)type_align_of(variant),
  2108. offset_in_bits,
  2109. field_flags, lb_debug_type(m, variant)
  2110. );
  2111. }
  2112. }
  2113. break;
  2114. case Type_BitSet:
  2115. {
  2116. if (file == nullptr) {
  2117. GB_ASSERT(bt->BitSet.node != nullptr);
  2118. file = lb_get_llvm_metadata(m, bt->BitSet.node->file);
  2119. line_number = cast(unsigned)ast_token(bt->BitSet.node).pos.line;
  2120. }
  2121. LLVMMetadataRef bit_set_field_type = lb_debug_type(m, t_bool);
  2122. LLVMMetadataRef scope = file;
  2123. Type *elem = base_type(bt->BitSet.elem);
  2124. if (elem->kind == Type_Enum) {
  2125. element_count = cast(unsigned)elem->Enum.fields.count;
  2126. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  2127. for_array(i, elem->Enum.fields) {
  2128. Entity *f = elem->Enum.fields[i];
  2129. GB_ASSERT(f->kind == Entity_Constant);
  2130. i64 val = exact_value_to_i64(f->Constant.value);
  2131. String name = f->token.string;
  2132. u64 offset_in_bits = cast(u64)(val - bt->BitSet.lower);
  2133. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  2134. m->debug_builder,
  2135. scope,
  2136. cast(char const *)name.text, name.len,
  2137. file, line_number,
  2138. 1,
  2139. offset_in_bits,
  2140. 0,
  2141. LLVMDIFlagZero,
  2142. bit_set_field_type
  2143. );
  2144. }
  2145. } else {
  2146. char name[32] = {};
  2147. GB_ASSERT(is_type_integer(elem));
  2148. i64 count = bt->BitSet.upper - bt->BitSet.lower + 1;
  2149. GB_ASSERT(0 <= count);
  2150. element_count = cast(unsigned)count;
  2151. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  2152. for (unsigned i = 0; i < element_count; i++) {
  2153. u64 offset_in_bits = i;
  2154. i64 val = bt->BitSet.lower + cast(i64)i;
  2155. gb_snprintf(name, gb_count_of(name), "%lld", cast(long long)val);
  2156. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  2157. m->debug_builder,
  2158. scope,
  2159. name, gb_strlen(name),
  2160. file, line_number,
  2161. 1,
  2162. offset_in_bits,
  2163. 0,
  2164. LLVMDIFlagZero,
  2165. bit_set_field_type
  2166. );
  2167. }
  2168. }
  2169. }
  2170. }
  2171. LLVMMetadataRef final_metadata = nullptr;
  2172. if (is_union) {
  2173. final_metadata = LLVMDIBuilderCreateUnionType(
  2174. m->debug_builder,
  2175. parent_scope,
  2176. cast(char const *)name.text, cast(size_t)name.len,
  2177. file, line_number,
  2178. size_in_bits, align_in_bits,
  2179. flags,
  2180. elements, element_count,
  2181. runtime_lang,
  2182. unique_id, unique_id_len
  2183. );
  2184. } else {
  2185. final_metadata = LLVMDIBuilderCreateStructType(
  2186. m->debug_builder,
  2187. parent_scope,
  2188. cast(char const *)name.text, cast(size_t)name.len,
  2189. file, line_number,
  2190. size_in_bits, align_in_bits,
  2191. flags,
  2192. derived_from,
  2193. elements, element_count,
  2194. runtime_lang,
  2195. vtable_holder,
  2196. unique_id, unique_id_len
  2197. );
  2198. }
  2199. LLVMMetadataReplaceAllUsesWith(idt.metadata, final_metadata);
  2200. lb_set_llvm_metadata(m, idt.type, final_metadata);
  2201. } break;
  2202. default:
  2203. GB_PANIC("invalid incomplete debug type");
  2204. break;
  2205. }
  2206. }
  2207. array_clear(&m->debug_incomplete_types);
  2208. }
  2209. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  2210. if (e != nullptr) {
  2211. map_set(&m->values, hash_entity(e), val);
  2212. }
  2213. }
  2214. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  2215. if (name.len > 0) {
  2216. string_map_set(&m->members, name, val);
  2217. }
  2218. }
  2219. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  2220. string_map_set(&m->members, key, val);
  2221. }
  2222. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  2223. if (p->entity != nullptr) {
  2224. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  2225. }
  2226. string_map_set(&m->procedures, p->name, p);
  2227. }
  2228. LLVMValueRef llvm_const_cast(LLVMValueRef val, LLVMTypeRef dst) {
  2229. LLVMTypeRef src = LLVMTypeOf(val);
  2230. if (src == dst) {
  2231. return val;
  2232. }
  2233. if (LLVMIsNull(val)) {
  2234. return LLVMConstNull(dst);
  2235. }
  2236. GB_ASSERT(LLVMSizeOf(dst) == LLVMSizeOf(src));
  2237. LLVMTypeKind kind = LLVMGetTypeKind(dst);
  2238. switch (kind) {
  2239. case LLVMPointerTypeKind:
  2240. return LLVMConstPointerCast(val, dst);
  2241. case LLVMStructTypeKind:
  2242. return LLVMConstBitCast(val, dst);
  2243. default:
  2244. GB_PANIC("Unhandled const cast %s to %s", LLVMPrintTypeToString(src), LLVMPrintTypeToString(dst));
  2245. }
  2246. return val;
  2247. }
  2248. LLVMValueRef llvm_const_named_struct(LLVMTypeRef t, LLVMValueRef *values, isize value_count_) {
  2249. unsigned value_count = cast(unsigned)value_count_;
  2250. unsigned elem_count = LLVMCountStructElementTypes(t);
  2251. GB_ASSERT(value_count == elem_count);
  2252. for (unsigned i = 0; i < elem_count; i++) {
  2253. LLVMTypeRef elem_type = LLVMStructGetTypeAtIndex(t, i);
  2254. values[i] = llvm_const_cast(values[i], elem_type);
  2255. }
  2256. return LLVMConstNamedStruct(t, values, value_count);
  2257. }
  2258. LLVMValueRef llvm_const_array(LLVMTypeRef elem_type, LLVMValueRef *values, isize value_count_) {
  2259. unsigned value_count = cast(unsigned)value_count_;
  2260. for (unsigned i = 0; i < value_count; i++) {
  2261. values[i] = llvm_const_cast(values[i], elem_type);
  2262. }
  2263. return LLVMConstArray(elem_type, values, value_count);
  2264. }
  2265. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  2266. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  2267. LLVMValueRef values[2] = {
  2268. str_elem.value,
  2269. str_len.value,
  2270. };
  2271. lbValue res = {};
  2272. res.type = t_string;
  2273. res.value = llvm_const_named_struct(lb_type(p->module, t_string), values, gb_count_of(values));
  2274. return res;
  2275. } else {
  2276. lbAddr res = lb_add_local_generated(p, t_string, false);
  2277. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  2278. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  2279. return lb_addr_load(p, res);
  2280. }
  2281. }
  2282. LLVMAttributeRef lb_create_enum_attribute_with_type(LLVMContextRef ctx, char const *name, LLVMTypeRef type) {
  2283. String s = make_string_c(name);
  2284. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  2285. // and the current LLVM C API does not expose this functionality yet.
  2286. // It is better to ignore the attributes for the time being
  2287. if (s == "byval") {
  2288. // return nullptr;
  2289. } else if (s == "byref") {
  2290. return nullptr;
  2291. } else if (s == "preallocated") {
  2292. return nullptr;
  2293. } else if (s == "sret") {
  2294. // return nullptr;
  2295. }
  2296. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  2297. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  2298. return LLVMCreateEnumAttribute(ctx, kind, 0);
  2299. }
  2300. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  2301. String s = make_string_c(name);
  2302. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  2303. // and the current LLVM C API does not expose this functionality yet.
  2304. // It is better to ignore the attributes for the time being
  2305. if (s == "byval") {
  2306. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2307. } else if (s == "byref") {
  2308. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2309. } else if (s == "preallocated") {
  2310. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2311. } else if (s == "sret") {
  2312. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2313. }
  2314. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  2315. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  2316. return LLVMCreateEnumAttribute(ctx, kind, value);
  2317. }
  2318. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  2319. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  2320. GB_ASSERT(attr != nullptr);
  2321. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  2322. }
  2323. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  2324. lb_add_proc_attribute_at_index(p, index, name, 0);
  2325. }
  2326. void lb_add_attribute_to_proc(lbModule *m, LLVMValueRef proc_value, char const *name, u64 value=0) {
  2327. LLVMAddAttributeAtIndex(proc_value, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(m->ctx, name, value));
  2328. }
  2329. void lb_ensure_abi_function_type(lbModule *m, lbProcedure *p) {
  2330. if (p->abi_function_type != nullptr) {
  2331. return;
  2332. }
  2333. auto hash = hash_type(p->type);
  2334. lbFunctionType **ft_found = map_get(&m->function_type_map, hash);
  2335. if (ft_found == nullptr) {
  2336. LLVMTypeRef llvm_proc_type = lb_type(p->module, p->type);
  2337. ft_found = map_get(&m->function_type_map, hash);
  2338. }
  2339. GB_ASSERT(ft_found != nullptr);
  2340. p->abi_function_type = *ft_found;
  2341. GB_ASSERT(p->abi_function_type != nullptr);
  2342. }
  2343. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity, bool ignore_body) {
  2344. GB_ASSERT(entity != nullptr);
  2345. GB_ASSERT(entity->kind == Entity_Procedure);
  2346. if (!entity->Procedure.is_foreign) {
  2347. GB_ASSERT(entity->flags |= EntityFlag_ProcBodyChecked);
  2348. }
  2349. String link_name = {};
  2350. if (ignore_body) {
  2351. lbModule *other_module = lb_pkg_module(m->gen, entity->pkg);
  2352. link_name = lb_get_entity_name(other_module, entity);
  2353. } else {
  2354. link_name = lb_get_entity_name(m, entity);
  2355. }
  2356. {
  2357. StringHashKey key = string_hash_string(link_name);
  2358. lbValue *found = string_map_get(&m->members, key);
  2359. if (found) {
  2360. lb_add_entity(m, entity, *found);
  2361. return string_map_must_get(&m->procedures, key);
  2362. }
  2363. }
  2364. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2365. p->module = m;
  2366. entity->code_gen_module = m;
  2367. entity->code_gen_procedure = p;
  2368. p->entity = entity;
  2369. p->name = link_name;
  2370. DeclInfo *decl = entity->decl_info;
  2371. ast_node(pl, ProcLit, decl->proc_lit);
  2372. Type *pt = base_type(entity->type);
  2373. GB_ASSERT(pt->kind == Type_Proc);
  2374. p->type = entity->type;
  2375. p->type_expr = decl->type_expr;
  2376. p->body = pl->body;
  2377. p->inlining = pl->inlining;
  2378. p->is_foreign = entity->Procedure.is_foreign;
  2379. p->is_export = entity->Procedure.is_export;
  2380. p->is_entry_point = false;
  2381. gbAllocator a = heap_allocator();
  2382. p->children.allocator = a;
  2383. p->params.allocator = a;
  2384. p->defer_stmts.allocator = a;
  2385. p->blocks.allocator = a;
  2386. p->branch_blocks.allocator = a;
  2387. p->context_stack.allocator = a;
  2388. p->scope_stack.allocator = a;
  2389. if (p->is_foreign) {
  2390. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  2391. }
  2392. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2393. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2394. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2395. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2396. lb_ensure_abi_function_type(m, p);
  2397. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  2398. if (false) {
  2399. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2400. // TODO(bill): Clean up this logic
  2401. if (!is_arch_wasm()) {
  2402. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2403. }
  2404. LLVMSetFunctionCallConv(p->value, cc_kind);
  2405. }
  2406. if (pt->Proc.diverging) {
  2407. lb_add_attribute_to_proc(m, p->value, "noreturn");
  2408. }
  2409. if (pt->Proc.calling_convention == ProcCC_Naked) {
  2410. lb_add_attribute_to_proc(m, p->value, "naked");
  2411. }
  2412. switch (p->inlining) {
  2413. case ProcInlining_inline:
  2414. lb_add_attribute_to_proc(m, p->value, "alwaysinline");
  2415. break;
  2416. case ProcInlining_no_inline:
  2417. lb_add_attribute_to_proc(m, p->value, "noinline");
  2418. break;
  2419. }
  2420. if (entity->flags & EntityFlag_Cold) {
  2421. lb_add_attribute_to_proc(m, p->value, "cold");
  2422. }
  2423. switch (entity->Procedure.optimization_mode) {
  2424. case ProcedureOptimizationMode_None:
  2425. lb_add_attribute_to_proc(m, p->value, "optnone");
  2426. break;
  2427. case ProcedureOptimizationMode_Minimal:
  2428. lb_add_attribute_to_proc(m, p->value, "optnone");
  2429. break;
  2430. case ProcedureOptimizationMode_Size:
  2431. lb_add_attribute_to_proc(m, p->value, "optsize");
  2432. break;
  2433. case ProcedureOptimizationMode_Speed:
  2434. // TODO(bill): handle this correctly
  2435. lb_add_attribute_to_proc(m, p->value, "optsize");
  2436. break;
  2437. }
  2438. // lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2439. // // TODO(bill): Clean up this logic
  2440. // if (build_context.metrics.os != TargetOs_js) {
  2441. // cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2442. // }
  2443. // LLVMSetFunctionCallConv(p->value, cc_kind);
  2444. lbValue proc_value = {p->value, p->type};
  2445. lb_add_entity(m, entity, proc_value);
  2446. lb_add_member(m, p->name, proc_value);
  2447. lb_add_procedure_value(m, p);
  2448. if (p->is_export) {
  2449. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  2450. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  2451. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  2452. if (is_arch_wasm()) {
  2453. char const *export_name = alloc_cstring(permanent_allocator(), p->name);
  2454. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  2455. }
  2456. } else if (!p->is_foreign) {
  2457. if (!USE_SEPARTE_MODULES) {
  2458. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  2459. // NOTE(bill): if a procedure is defined in package runtime and uses a custom link name,
  2460. // then it is very likely it is required by LLVM and thus cannot have internal linkage
  2461. if (entity->pkg != nullptr && entity->pkg->kind == Package_Runtime && p->body != nullptr) {
  2462. GB_ASSERT(entity->kind == Entity_Procedure);
  2463. if (entity->Procedure.link_name != "") {
  2464. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  2465. }
  2466. }
  2467. }
  2468. }
  2469. if (p->is_foreign) {
  2470. if (is_arch_wasm()) {
  2471. char const *import_name = alloc_cstring(permanent_allocator(), p->name);
  2472. char const *module_name = "env";
  2473. if (entity->Procedure.foreign_library != nullptr) {
  2474. Entity *foreign_library = entity->Procedure.foreign_library;
  2475. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  2476. if (foreign_library->LibraryName.paths.count > 0) {
  2477. module_name = alloc_cstring(permanent_allocator(), foreign_library->LibraryName.paths[0]);
  2478. }
  2479. }
  2480. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  2481. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  2482. }
  2483. }
  2484. // NOTE(bill): offset==0 is the return value
  2485. isize offset = 1;
  2486. if (pt->Proc.return_by_pointer) {
  2487. offset = 2;
  2488. }
  2489. isize parameter_index = 0;
  2490. if (pt->Proc.param_count) {
  2491. TypeTuple *params = &pt->Proc.params->Tuple;
  2492. for (isize i = 0; i < pt->Proc.param_count; i++) {
  2493. Entity *e = params->variables[i];
  2494. Type *original_type = e->type;
  2495. if (e->kind != Entity_Variable) continue;
  2496. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  2497. continue;
  2498. }
  2499. if (e->flags&EntityFlag_NoAlias) {
  2500. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2501. }
  2502. parameter_index += 1;
  2503. }
  2504. }
  2505. if (ignore_body) {
  2506. p->body = nullptr;
  2507. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  2508. }
  2509. if (m->debug_builder) { // Debug Information
  2510. Type *bt = base_type(p->type);
  2511. unsigned line = cast(unsigned)entity->token.pos.line;
  2512. LLVMMetadataRef scope = nullptr;
  2513. LLVMMetadataRef file = nullptr;
  2514. LLVMMetadataRef type = nullptr;
  2515. scope = p->module->debug_compile_unit;
  2516. type = lb_debug_type_internal_proc(m, bt);
  2517. if (entity->file != nullptr) {
  2518. file = lb_get_llvm_metadata(m, entity->file);
  2519. scope = file;
  2520. } else if (entity->identifier != nullptr && entity->identifier->file != nullptr) {
  2521. file = lb_get_llvm_metadata(m, entity->identifier->file);
  2522. scope = file;
  2523. } else if (entity->scope != nullptr) {
  2524. file = lb_get_llvm_metadata(m, entity->scope->file);
  2525. scope = file;
  2526. }
  2527. GB_ASSERT_MSG(file != nullptr, "%.*s", LIT(entity->token.string));
  2528. // LLVMBool is_local_to_unit = !entity->Procedure.is_export;
  2529. LLVMBool is_local_to_unit = false;
  2530. LLVMBool is_definition = p->body != nullptr;
  2531. unsigned scope_line = line;
  2532. u32 flags = LLVMDIFlagStaticMember;
  2533. LLVMBool is_optimized = false;
  2534. if (bt->Proc.diverging) {
  2535. flags |= LLVMDIFlagNoReturn;
  2536. }
  2537. if (p->body == nullptr) {
  2538. flags |= LLVMDIFlagPrototyped;
  2539. is_optimized = false;
  2540. }
  2541. if (p->body != nullptr) {
  2542. p->debug_info = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  2543. cast(char const *)entity->token.string.text, entity->token.string.len,
  2544. cast(char const *)p->name.text, p->name.len,
  2545. file, line, type,
  2546. is_local_to_unit, is_definition,
  2547. scope_line, cast(LLVMDIFlags)flags, is_optimized
  2548. );
  2549. GB_ASSERT(p->debug_info != nullptr);
  2550. LLVMSetSubprogram(p->value, p->debug_info);
  2551. lb_set_llvm_metadata(m, p, p->debug_info);
  2552. }
  2553. }
  2554. return p;
  2555. }
  2556. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  2557. {
  2558. lbValue *found = string_map_get(&m->members, link_name);
  2559. GB_ASSERT(found == nullptr);
  2560. }
  2561. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2562. p->module = m;
  2563. p->name = link_name;
  2564. p->type = type;
  2565. p->type_expr = nullptr;
  2566. p->body = nullptr;
  2567. p->tags = 0;
  2568. p->inlining = ProcInlining_none;
  2569. p->is_foreign = false;
  2570. p->is_export = false;
  2571. p->is_entry_point = false;
  2572. gbAllocator a = permanent_allocator();
  2573. p->children.allocator = a;
  2574. p->params.allocator = a;
  2575. p->defer_stmts.allocator = a;
  2576. p->blocks.allocator = a;
  2577. p->branch_blocks.allocator = a;
  2578. p->context_stack.allocator = a;
  2579. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2580. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2581. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2582. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2583. Type *pt = p->type;
  2584. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2585. // TODO(bill): Clean up this logic
  2586. if (!is_arch_wasm()) {
  2587. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2588. }
  2589. LLVMSetFunctionCallConv(p->value, cc_kind);
  2590. lbValue proc_value = {p->value, p->type};
  2591. lb_add_member(m, p->name, proc_value);
  2592. lb_add_procedure_value(m, p);
  2593. // NOTE(bill): offset==0 is the return value
  2594. isize offset = 1;
  2595. if (pt->Proc.return_by_pointer) {
  2596. lb_add_proc_attribute_at_index(p, 1, "sret");
  2597. lb_add_proc_attribute_at_index(p, 1, "noalias");
  2598. offset = 2;
  2599. }
  2600. isize parameter_index = 0;
  2601. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2602. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2603. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  2604. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  2605. }
  2606. return p;
  2607. }
  2608. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  2609. lbParamPasskind kind = lbParamPass_Value;
  2610. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  2611. if (is_type_pointer(abi_type)) {
  2612. GB_ASSERT(e->kind == Entity_Variable);
  2613. Type *av = core_type(type_deref(abi_type));
  2614. if (are_types_identical(av, core_type(e->type))) {
  2615. kind = lbParamPass_Pointer;
  2616. if (e->flags&EntityFlag_Value) {
  2617. kind = lbParamPass_ConstRef;
  2618. }
  2619. } else {
  2620. kind = lbParamPass_BitCast;
  2621. }
  2622. } else if (is_type_integer(abi_type)) {
  2623. kind = lbParamPass_Integer;
  2624. } else if (abi_type == t_llvm_bool) {
  2625. kind = lbParamPass_Value;
  2626. } else if (is_type_boolean(abi_type)) {
  2627. kind = lbParamPass_Integer;
  2628. } else if (is_type_simd_vector(abi_type)) {
  2629. kind = lbParamPass_BitCast;
  2630. } else if (is_type_float(abi_type)) {
  2631. kind = lbParamPass_BitCast;
  2632. } else if (is_type_tuple(abi_type)) {
  2633. kind = lbParamPass_Tuple;
  2634. } else if (is_type_proc(abi_type)) {
  2635. kind = lbParamPass_Value;
  2636. } else {
  2637. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  2638. }
  2639. }
  2640. if (kind_) *kind_ = kind;
  2641. lbValue res = {};
  2642. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  2643. res.type = abi_type;
  2644. return res;
  2645. }
  2646. Type *struct_type_from_systemv_distribute_struct_fields(Type *abi_type) {
  2647. GB_ASSERT(is_type_tuple(abi_type));
  2648. Type *final_type = alloc_type_struct();
  2649. final_type->Struct.fields = abi_type->Tuple.variables;
  2650. return final_type;
  2651. }
  2652. void lb_start_block(lbProcedure *p, lbBlock *b) {
  2653. GB_ASSERT(b != nullptr);
  2654. if (!b->appended) {
  2655. b->appended = true;
  2656. LLVMAppendExistingBasicBlock(p->value, b->block);
  2657. }
  2658. LLVMPositionBuilderAtEnd(p->builder, b->block);
  2659. p->curr_block = b;
  2660. }
  2661. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  2662. LLVMContextRef ctx = p->module->ctx;
  2663. LLVMTypeRef src_type = LLVMTypeOf(val);
  2664. if (src_type == dst_type) {
  2665. return val;
  2666. }
  2667. i64 src_size = lb_sizeof(src_type);
  2668. i64 dst_size = lb_sizeof(dst_type);
  2669. i64 src_align = lb_alignof(src_type);
  2670. i64 dst_align = lb_alignof(dst_type);
  2671. if (LLVMIsALoadInst(val)) {
  2672. src_align = gb_min(src_align, LLVMGetAlignment(val));
  2673. }
  2674. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  2675. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  2676. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  2677. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2678. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  2679. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  2680. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2681. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  2682. }
  2683. if (src_size != dst_size) {
  2684. if ((lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  2685. // Okay
  2686. } else {
  2687. goto general_end;
  2688. }
  2689. }
  2690. if (src_kind == dst_kind) {
  2691. if (src_kind == LLVMPointerTypeKind) {
  2692. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  2693. } else if (src_kind == LLVMArrayTypeKind) {
  2694. // ignore
  2695. } else if (src_kind != LLVMStructTypeKind) {
  2696. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  2697. }
  2698. } else {
  2699. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  2700. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  2701. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  2702. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  2703. }
  2704. }
  2705. general_end:;
  2706. // make the alignment big if necessary
  2707. if (LLVMIsALoadInst(val) && src_align < dst_align) {
  2708. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2709. if (LLVMGetInstructionOpcode(val_ptr) == LLVMAlloca) {
  2710. src_align = gb_max(LLVMGetAlignment(val_ptr), dst_align);
  2711. LLVMSetAlignment(val_ptr, cast(unsigned)src_align);
  2712. }
  2713. }
  2714. src_size = align_formula(src_size, src_align);
  2715. dst_size = align_formula(dst_size, dst_align);
  2716. if (LLVMIsALoadInst(val) && (src_size >= dst_size && src_align >= dst_align)) {
  2717. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2718. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  2719. LLVMValueRef loaded_val = LLVMBuildLoad(p->builder, val_ptr, "");
  2720. // LLVMSetAlignment(loaded_val, gb_min(src_align, dst_align));
  2721. return loaded_val;
  2722. } else {
  2723. GB_ASSERT(p->decl_block != p->curr_block);
  2724. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2725. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  2726. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2727. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2728. max_align = gb_max(max_align, 4);
  2729. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  2730. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2731. LLVMBuildStore(p->builder, val, nptr);
  2732. return LLVMBuildLoad(p->builder, ptr, "");
  2733. }
  2734. }
  2735. void lb_add_debug_local_variable(lbProcedure *p, LLVMValueRef ptr, Type *type, Token const &token) {
  2736. if (p->debug_info == nullptr) {
  2737. return;
  2738. }
  2739. if (type == nullptr) {
  2740. return;
  2741. }
  2742. if (type == t_invalid) {
  2743. return;
  2744. }
  2745. if (p->body == nullptr) {
  2746. return;
  2747. }
  2748. lbModule *m = p->module;
  2749. String const &name = token.string;
  2750. if (name == "" || name == "_") {
  2751. return;
  2752. }
  2753. if (lb_get_llvm_metadata(m, ptr) != nullptr) {
  2754. // Already been set
  2755. return;
  2756. }
  2757. AstFile *file = p->body->file;
  2758. LLVMMetadataRef llvm_scope = lb_get_current_debug_scope(p);
  2759. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, file);
  2760. GB_ASSERT(llvm_scope != nullptr);
  2761. if (llvm_file == nullptr) {
  2762. llvm_file = LLVMDIScopeGetFile(llvm_scope);
  2763. }
  2764. if (llvm_file == nullptr) {
  2765. return;
  2766. }
  2767. unsigned alignment_in_bits = cast(unsigned)(8*type_align_of(type));
  2768. LLVMDIFlags flags = LLVMDIFlagZero;
  2769. LLVMBool always_preserve = build_context.optimization_level == 0;
  2770. LLVMMetadataRef debug_type = lb_debug_type(m, type);
  2771. LLVMMetadataRef var_info = LLVMDIBuilderCreateAutoVariable(
  2772. m->debug_builder, llvm_scope,
  2773. cast(char const *)name.text, cast(size_t)name.len,
  2774. llvm_file, token.pos.line,
  2775. debug_type,
  2776. always_preserve, flags, alignment_in_bits
  2777. );
  2778. LLVMValueRef storage = ptr;
  2779. LLVMValueRef instr = ptr;
  2780. LLVMMetadataRef llvm_debug_loc = lb_debug_location_from_token_pos(p, token.pos);
  2781. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  2782. lb_set_llvm_metadata(m, ptr, llvm_expr);
  2783. LLVMDIBuilderInsertDeclareBefore(m->debug_builder, storage, var_info, llvm_expr, llvm_debug_loc, instr);
  2784. }
  2785. void lb_add_debug_context_variable(lbProcedure *p, lbAddr const &ctx) {
  2786. if (!p->debug_info || !p->body) {
  2787. return;
  2788. }
  2789. LLVMMetadataRef loc = LLVMGetCurrentDebugLocation2(p->builder);
  2790. if (!loc) {
  2791. return;
  2792. }
  2793. TokenPos pos = {};
  2794. pos.file_id = p->body->file ? p->body->file->id : 0;
  2795. pos.line = LLVMDILocationGetLine(loc);
  2796. pos.column = LLVMDILocationGetColumn(loc);
  2797. Token token = {};
  2798. token.kind = Token_context;
  2799. token.string = str_lit("context");
  2800. token.pos = pos;
  2801. lb_add_debug_local_variable(p, ctx.addr.value, t_context, token);
  2802. }
  2803. void lb_begin_procedure_body(lbProcedure *p) {
  2804. DeclInfo *decl = decl_info_of_entity(p->entity);
  2805. if (decl != nullptr) {
  2806. for_array(i, decl->labels) {
  2807. BlockLabel bl = decl->labels[i];
  2808. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2809. array_add(&p->branch_blocks, bb);
  2810. }
  2811. }
  2812. p->builder = LLVMCreateBuilderInContext(p->module->ctx);
  2813. p->decl_block = lb_create_block(p, "decls", true);
  2814. p->entry_block = lb_create_block(p, "entry", true);
  2815. lb_start_block(p, p->entry_block);
  2816. GB_ASSERT(p->type != nullptr);
  2817. lb_ensure_abi_function_type(p->module, p);
  2818. {
  2819. lbFunctionType *ft = p->abi_function_type;
  2820. unsigned param_offset = 0;
  2821. lbValue return_ptr_value = {};
  2822. if (ft->ret.kind == lbArg_Indirect) {
  2823. // NOTE(bill): this must be parameter 0
  2824. String name = str_lit("agg.result");
  2825. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2826. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), ptr_type, false, false);
  2827. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2828. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2829. LLVMSetValueName2(return_ptr_value.value, cast(char const *)name.text, name.len);
  2830. return_ptr_value.type = ptr_type;
  2831. p->return_ptr = lb_addr(return_ptr_value);
  2832. lb_add_entity(p->module, e, return_ptr_value);
  2833. param_offset += 1;
  2834. }
  2835. if (p->type->Proc.params != nullptr) {
  2836. TypeTuple *params = &p->type->Proc.params->Tuple;
  2837. unsigned param_index = 0;
  2838. for_array(i, params->variables) {
  2839. Entity *e = params->variables[i];
  2840. if (e->kind != Entity_Variable) {
  2841. continue;
  2842. }
  2843. lbArgType *arg_type = &ft->args[param_index];
  2844. if (arg_type->kind == lbArg_Ignore) {
  2845. continue;
  2846. } else if (arg_type->kind == lbArg_Direct) {
  2847. lbParamPasskind kind = lbParamPass_Value;
  2848. LLVMTypeRef param_type = lb_type(p->module, e->type);
  2849. if (param_type != arg_type->type) {
  2850. kind = lbParamPass_BitCast;
  2851. }
  2852. LLVMValueRef value = LLVMGetParam(p->value, param_offset+param_index);
  2853. value = OdinLLVMBuildTransmute(p, value, param_type);
  2854. lbValue param = {};
  2855. param.value = value;
  2856. param.type = e->type;
  2857. array_add(&p->params, param);
  2858. if (e->token.string.len != 0) {
  2859. lbAddr l = lb_add_local(p, e->type, e, false, param_index);
  2860. lb_addr_store(p, l, param);
  2861. }
  2862. param_index += 1;
  2863. } else if (arg_type->kind == lbArg_Indirect) {
  2864. LLVMValueRef value_ptr = LLVMGetParam(p->value, param_offset+param_index);
  2865. LLVMValueRef value = LLVMBuildLoad(p->builder, value_ptr, "");
  2866. lbValue param = {};
  2867. param.value = value;
  2868. param.type = e->type;
  2869. array_add(&p->params, param);
  2870. lbValue ptr = {};
  2871. ptr.value = value_ptr;
  2872. ptr.type = alloc_type_pointer(e->type);
  2873. lb_add_entity(p->module, e, ptr);
  2874. param_index += 1;
  2875. }
  2876. }
  2877. }
  2878. if (p->type->Proc.has_named_results) {
  2879. GB_ASSERT(p->type->Proc.result_count > 0);
  2880. TypeTuple *results = &p->type->Proc.results->Tuple;
  2881. for_array(i, results->variables) {
  2882. Entity *e = results->variables[i];
  2883. GB_ASSERT(e->kind == Entity_Variable);
  2884. if (e->token.string != "") {
  2885. GB_ASSERT(!is_blank_ident(e->token));
  2886. lbAddr res = {};
  2887. if (return_ptr_value.value) {
  2888. lbValue ptr = return_ptr_value;
  2889. if (results->variables.count != 1) {
  2890. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2891. }
  2892. res = lb_addr(ptr);
  2893. lb_add_entity(p->module, e, ptr);
  2894. } else {
  2895. res = lb_add_local(p, e->type, e);
  2896. }
  2897. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2898. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2899. lb_addr_store(p, res, c);
  2900. }
  2901. }
  2902. }
  2903. }
  2904. }
  2905. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2906. lb_push_context_onto_stack_from_implicit_parameter(p);
  2907. }
  2908. lb_start_block(p, p->entry_block);
  2909. if (p->debug_info != nullptr) {
  2910. TokenPos pos = {};
  2911. if (p->body != nullptr) {
  2912. pos = ast_token(p->body).pos;
  2913. } else if (p->type_expr != nullptr) {
  2914. pos = ast_token(p->type_expr).pos;
  2915. } else if (p->entity != nullptr) {
  2916. pos = p->entity->token.pos;
  2917. }
  2918. if (pos.file_id != 0) {
  2919. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  2920. }
  2921. if (p->context_stack.count != 0) {
  2922. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  2923. }
  2924. }
  2925. }
  2926. void lb_end_procedure_body(lbProcedure *p) {
  2927. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2928. LLVMBuildBr(p->builder, p->entry_block->block);
  2929. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2930. LLVMValueRef instr = nullptr;
  2931. // Make sure there is a "ret void" at the end of a procedure with no return type
  2932. if (p->type->Proc.result_count == 0) {
  2933. instr = LLVMGetLastInstruction(p->curr_block->block);
  2934. if (!lb_is_instr_terminating(instr)) {
  2935. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2936. LLVMBuildRetVoid(p->builder);
  2937. }
  2938. }
  2939. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  2940. LLVMBasicBlockRef block = nullptr;
  2941. // Make sure every block terminates, and if not, make it unreachable
  2942. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  2943. instr = LLVMGetLastInstruction(block);
  2944. if (instr == nullptr || !lb_is_instr_terminating(instr)) {
  2945. LLVMPositionBuilderAtEnd(p->builder, block);
  2946. LLVMBuildUnreachable(p->builder);
  2947. }
  2948. }
  2949. p->curr_block = nullptr;
  2950. p->state_flags = 0;
  2951. }
  2952. void lb_end_procedure(lbProcedure *p) {
  2953. LLVMDisposeBuilder(p->builder);
  2954. }
  2955. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2956. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2957. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2958. array_add(&from->succs, to);
  2959. array_add(&to->preds, from);
  2960. }
  2961. }
  2962. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2963. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  2964. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2965. b->appended = false;
  2966. if (append) {
  2967. b->appended = true;
  2968. LLVMAppendExistingBasicBlock(p->value, b->block);
  2969. }
  2970. b->scope = p->curr_scope;
  2971. b->scope_index = p->scope_index;
  2972. b->preds.allocator = heap_allocator();
  2973. b->succs.allocator = heap_allocator();
  2974. array_add(&p->blocks, b);
  2975. return b;
  2976. }
  2977. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2978. if (p->curr_block == nullptr) {
  2979. return;
  2980. }
  2981. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2982. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2983. return;
  2984. }
  2985. lb_add_edge(p->curr_block, target_block);
  2986. LLVMBuildBr(p->builder, target_block->block);
  2987. p->curr_block = nullptr;
  2988. }
  2989. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2990. lbBlock *b = p->curr_block;
  2991. if (b == nullptr) {
  2992. return;
  2993. }
  2994. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2995. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2996. return;
  2997. }
  2998. lb_add_edge(b, true_block);
  2999. lb_add_edge(b, false_block);
  3000. LLVMValueRef cv = cond.value;
  3001. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  3002. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  3003. }
  3004. bool lb_is_expr_untyped_const(Ast *expr) {
  3005. auto const &tv = type_and_value_of_expr(expr);
  3006. if (is_type_untyped(tv.type)) {
  3007. return tv.value.kind != ExactValue_Invalid;
  3008. }
  3009. return false;
  3010. }
  3011. lbValue lb_expr_untyped_const_to_typed(lbModule *m, Ast *expr, Type *t) {
  3012. GB_ASSERT(is_type_typed(t));
  3013. auto const &tv = type_and_value_of_expr(expr);
  3014. return lb_const_value(m, t, tv.value);
  3015. }
  3016. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  3017. GB_ASSERT(cond != nullptr);
  3018. GB_ASSERT(true_block != nullptr);
  3019. GB_ASSERT(false_block != nullptr);
  3020. switch (cond->kind) {
  3021. case_ast_node(pe, ParenExpr, cond);
  3022. return lb_build_cond(p, pe->expr, true_block, false_block);
  3023. case_end;
  3024. case_ast_node(ue, UnaryExpr, cond);
  3025. if (ue->op.kind == Token_Not) {
  3026. return lb_build_cond(p, ue->expr, false_block, true_block);
  3027. }
  3028. case_end;
  3029. case_ast_node(be, BinaryExpr, cond);
  3030. if (be->op.kind == Token_CmpAnd) {
  3031. lbBlock *block = lb_create_block(p, "cmp.and");
  3032. lb_build_cond(p, be->left, block, false_block);
  3033. lb_start_block(p, block);
  3034. return lb_build_cond(p, be->right, true_block, false_block);
  3035. } else if (be->op.kind == Token_CmpOr) {
  3036. lbBlock *block = lb_create_block(p, "cmp.or");
  3037. lb_build_cond(p, be->left, true_block, block);
  3038. lb_start_block(p, block);
  3039. return lb_build_cond(p, be->right, true_block, false_block);
  3040. }
  3041. case_end;
  3042. }
  3043. lbValue v = {};
  3044. if (lb_is_expr_untyped_const(cond)) {
  3045. v = lb_expr_untyped_const_to_typed(p->module, cond, t_llvm_bool);
  3046. } else {
  3047. v = lb_build_expr(p, cond);
  3048. }
  3049. v = lb_emit_conv(p, v, t_llvm_bool);
  3050. lb_emit_if(p, v, true_block, false_block);
  3051. return v;
  3052. }
  3053. void lb_mem_zero_ptr_internal(lbProcedure *p, LLVMValueRef ptr, LLVMValueRef len, unsigned alignment) {
  3054. bool is_inlinable = false;
  3055. i64 const_len = 0;
  3056. if (LLVMIsConstant(len)) {
  3057. const_len = cast(i64)LLVMConstIntGetSExtValue(len);
  3058. // TODO(bill): Determine when it is better to do the `*.inline` versions
  3059. if (const_len <= 4*build_context.word_size) {
  3060. is_inlinable = true;
  3061. }
  3062. }
  3063. char const *name = "llvm.memset";
  3064. if (is_inlinable) {
  3065. name = "llvm.memset.inline";
  3066. }
  3067. LLVMTypeRef types[2] = {
  3068. lb_type(p->module, t_rawptr),
  3069. lb_type(p->module, t_int)
  3070. };
  3071. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  3072. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s.%s", name, LLVMPrintTypeToString(types[0]), LLVMPrintTypeToString(types[1]));
  3073. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  3074. LLVMValueRef args[4] = {};
  3075. args[0] = LLVMBuildPointerCast(p->builder, ptr, types[0], "");
  3076. args[1] = LLVMConstInt(LLVMInt8TypeInContext(p->module->ctx), 0, false);
  3077. args[2] = LLVMBuildIntCast2(p->builder, len, types[1], /*signed*/false, "");
  3078. args[3] = LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, false); // is_volatile parameter
  3079. LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  3080. }
  3081. void lb_mem_zero_ptr(lbProcedure *p, LLVMValueRef ptr, Type *type, unsigned alignment) {
  3082. LLVMTypeRef llvm_type = lb_type(p->module, type);
  3083. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  3084. switch (kind) {
  3085. case LLVMStructTypeKind:
  3086. case LLVMArrayTypeKind:
  3087. {
  3088. // NOTE(bill): Enforce zeroing through memset to make sure padding is zeroed too
  3089. i32 sz = cast(i32)type_size_of(type);
  3090. lb_mem_zero_ptr_internal(p, ptr, lb_const_int(p->module, t_int, sz).value, alignment);
  3091. }
  3092. break;
  3093. default:
  3094. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  3095. break;
  3096. }
  3097. }
  3098. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index, bool force_no_init) {
  3099. GB_ASSERT(p->decl_block != p->curr_block);
  3100. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  3101. char const *name = "";
  3102. if (e != nullptr) {
  3103. // name = alloc_cstring(permanent_allocator(), e->token.string);
  3104. }
  3105. LLVMTypeRef llvm_type = lb_type(p->module, type);
  3106. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  3107. // unsigned alignment = 16; // TODO(bill): Make this configurable
  3108. unsigned alignment = cast(unsigned)lb_alignof(llvm_type);
  3109. LLVMSetAlignment(ptr, alignment);
  3110. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  3111. if (!zero_init && !force_no_init) {
  3112. // If there is any padding of any kind, just zero init regardless of zero_init parameter
  3113. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  3114. if (kind == LLVMStructTypeKind) {
  3115. i64 sz = type_size_of(type);
  3116. if (type_size_of_struct_pretend_is_packed(type) != sz) {
  3117. zero_init = true;
  3118. }
  3119. } else if (kind == LLVMArrayTypeKind) {
  3120. zero_init = true;
  3121. }
  3122. }
  3123. if (zero_init) {
  3124. lb_mem_zero_ptr(p, ptr, type, alignment);
  3125. }
  3126. lbValue val = {};
  3127. val.value = ptr;
  3128. val.type = alloc_type_pointer(type);
  3129. if (e != nullptr) {
  3130. lb_add_entity(p->module, e, val);
  3131. lb_add_debug_local_variable(p, ptr, type, e->token);
  3132. }
  3133. return lb_addr(val);
  3134. }
  3135. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  3136. return lb_add_local(p, type, nullptr, zero_init);
  3137. }
  3138. lbAddr lb_add_local_generated_temp(lbProcedure *p, Type *type, i64 min_alignment) {
  3139. lbAddr res = lb_add_local(p, type, nullptr, false, 0, true);
  3140. lb_try_update_alignment(res.addr, cast(unsigned)min_alignment);
  3141. return res;
  3142. }
  3143. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  3144. GB_ASSERT(pd->body != nullptr);
  3145. lbModule *m = p->module;
  3146. auto *min_dep_set = &m->info->minimum_dependency_set;
  3147. if (ptr_set_exists(min_dep_set, e) == false) {
  3148. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  3149. return;
  3150. }
  3151. // NOTE(bill): Generate a new name
  3152. // parent.name-guid
  3153. String original_name = e->token.string;
  3154. String pd_name = original_name;
  3155. if (e->Procedure.link_name.len > 0) {
  3156. pd_name = e->Procedure.link_name;
  3157. }
  3158. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  3159. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  3160. i32 guid = cast(i32)p->children.count;
  3161. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  3162. String name = make_string(cast(u8 *)name_text, name_len-1);
  3163. e->Procedure.link_name = name;
  3164. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  3165. e->code_gen_procedure = nested_proc;
  3166. lbValue value = {};
  3167. value.value = nested_proc->value;
  3168. value.type = nested_proc->type;
  3169. lb_add_entity(m, e, value);
  3170. array_add(&p->children, nested_proc);
  3171. array_add(&m->procedures_to_generate, nested_proc);
  3172. }
  3173. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  3174. if (e == nullptr) {
  3175. return;
  3176. }
  3177. GB_ASSERT(e->kind == Entity_LibraryName);
  3178. GB_ASSERT(e->flags & EntityFlag_Used);
  3179. for_array(i, e->LibraryName.paths) {
  3180. String library_path = e->LibraryName.paths[i];
  3181. if (library_path.len == 0) {
  3182. continue;
  3183. }
  3184. bool ok = true;
  3185. for_array(path_index, m->foreign_library_paths) {
  3186. String path = m->foreign_library_paths[path_index];
  3187. #if defined(GB_SYSTEM_WINDOWS)
  3188. if (str_eq_ignore_case(path, library_path)) {
  3189. #else
  3190. if (str_eq(path, library_path)) {
  3191. #endif
  3192. ok = false;
  3193. break;
  3194. }
  3195. }
  3196. if (ok) {
  3197. array_add(&m->foreign_library_paths, library_path);
  3198. }
  3199. }
  3200. }
  3201. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  3202. if (vd == nullptr || vd->is_mutable) {
  3203. return;
  3204. }
  3205. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  3206. static i32 global_guid = 0;
  3207. for_array(i, vd->names) {
  3208. Ast *ident = vd->names[i];
  3209. GB_ASSERT(ident->kind == Ast_Ident);
  3210. Entity *e = entity_of_node(ident);
  3211. GB_ASSERT(e != nullptr);
  3212. if (e->kind != Entity_TypeName) {
  3213. continue;
  3214. }
  3215. bool polymorphic_struct = false;
  3216. if (e->type != nullptr && e->kind == Entity_TypeName) {
  3217. Type *bt = base_type(e->type);
  3218. if (bt->kind == Type_Struct) {
  3219. polymorphic_struct = bt->Struct.is_polymorphic;
  3220. }
  3221. }
  3222. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  3223. continue;
  3224. }
  3225. if (e->TypeName.ir_mangled_name.len != 0) {
  3226. // NOTE(bill): Already set
  3227. continue;
  3228. }
  3229. lb_set_nested_type_name_ir_mangled_name(e, p);
  3230. }
  3231. for_array(i, vd->names) {
  3232. Ast *ident = vd->names[i];
  3233. GB_ASSERT(ident->kind == Ast_Ident);
  3234. Entity *e = entity_of_node(ident);
  3235. GB_ASSERT(e != nullptr);
  3236. if (e->kind != Entity_Procedure) {
  3237. continue;
  3238. }
  3239. GB_ASSERT (vd->values[i] != nullptr);
  3240. Ast *value = unparen_expr(vd->values[i]);
  3241. if (value->kind != Ast_ProcLit) {
  3242. continue; // It's an alias
  3243. }
  3244. CheckerInfo *info = p->module->info;
  3245. DeclInfo *decl = decl_info_of_entity(e);
  3246. ast_node(pl, ProcLit, decl->proc_lit);
  3247. if (pl->body != nullptr) {
  3248. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  3249. if (found) {
  3250. auto procs = *found;
  3251. for_array(i, procs) {
  3252. Entity *e = procs[i];
  3253. if (!ptr_set_exists(min_dep_set, e)) {
  3254. continue;
  3255. }
  3256. DeclInfo *d = decl_info_of_entity(e);
  3257. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  3258. }
  3259. } else {
  3260. lb_build_nested_proc(p, pl, e);
  3261. }
  3262. } else {
  3263. // FFI - Foreign function interace
  3264. String original_name = e->token.string;
  3265. String name = original_name;
  3266. if (e->Procedure.is_foreign) {
  3267. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  3268. }
  3269. if (e->Procedure.link_name.len > 0) {
  3270. name = e->Procedure.link_name;
  3271. }
  3272. lbValue *prev_value = string_map_get(&p->module->members, name);
  3273. if (prev_value != nullptr) {
  3274. // NOTE(bill): Don't do mutliple declarations in the IR
  3275. return;
  3276. }
  3277. e->Procedure.link_name = name;
  3278. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  3279. lbValue value = {};
  3280. value.value = nested_proc->value;
  3281. value.type = nested_proc->type;
  3282. array_add(&p->module->procedures_to_generate, nested_proc);
  3283. array_add(&p->children, nested_proc);
  3284. string_map_set(&p->module->members, name, value);
  3285. }
  3286. }
  3287. }
  3288. void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  3289. for_array(i, stmts) {
  3290. Ast *stmt = stmts[i];
  3291. switch (stmt->kind) {
  3292. case_ast_node(vd, ValueDecl, stmt);
  3293. lb_build_constant_value_decl(p, vd);
  3294. case_end;
  3295. case_ast_node(fb, ForeignBlockDecl, stmt);
  3296. ast_node(block, BlockStmt, fb->body);
  3297. lb_build_stmt_list(p, block->stmts);
  3298. case_end;
  3299. }
  3300. }
  3301. for_array(i, stmts) {
  3302. lb_build_stmt(p, stmts[i]);
  3303. }
  3304. }
  3305. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  3306. GB_ASSERT(ident->kind == Ast_Ident);
  3307. Entity *e = entity_of_node(ident);
  3308. GB_ASSERT(e->kind == Entity_Label);
  3309. for_array(i, p->branch_blocks) {
  3310. lbBranchBlocks *b = &p->branch_blocks[i];
  3311. if (b->label == e->Label.node) {
  3312. return *b;
  3313. }
  3314. }
  3315. GB_PANIC("Unreachable");
  3316. lbBranchBlocks empty = {};
  3317. return empty;
  3318. }
  3319. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  3320. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  3321. tl->prev = p->target_list;
  3322. tl->break_ = break_;
  3323. tl->continue_ = continue_;
  3324. tl->fallthrough_ = fallthrough_;
  3325. p->target_list = tl;
  3326. if (label != nullptr) { // Set label blocks
  3327. GB_ASSERT(label->kind == Ast_Label);
  3328. for_array(i, p->branch_blocks) {
  3329. lbBranchBlocks *b = &p->branch_blocks[i];
  3330. GB_ASSERT(b->label != nullptr && label != nullptr);
  3331. GB_ASSERT(b->label->kind == Ast_Label);
  3332. if (b->label == label) {
  3333. b->break_ = break_;
  3334. b->continue_ = continue_;
  3335. return tl;
  3336. }
  3337. }
  3338. GB_PANIC("Unreachable");
  3339. }
  3340. return tl;
  3341. }
  3342. void lb_pop_target_list(lbProcedure *p) {
  3343. p->target_list = p->target_list->prev;
  3344. }
  3345. void lb_open_scope(lbProcedure *p, Scope *s) {
  3346. lbModule *m = p->module;
  3347. if (m->debug_builder) {
  3348. LLVMMetadataRef curr_metadata = lb_get_llvm_metadata(m, s);
  3349. if (s != nullptr && s->node != nullptr && curr_metadata == nullptr) {
  3350. Token token = ast_token(s->node);
  3351. unsigned line = cast(unsigned)token.pos.line;
  3352. unsigned column = cast(unsigned)token.pos.column;
  3353. LLVMMetadataRef file = nullptr;
  3354. if (s->node->file != nullptr) {
  3355. file = lb_get_llvm_metadata(m, s->node->file);
  3356. }
  3357. LLVMMetadataRef scope = nullptr;
  3358. if (p->scope_stack.count > 0) {
  3359. scope = lb_get_llvm_metadata(m, p->scope_stack[p->scope_stack.count-1]);
  3360. }
  3361. if (scope == nullptr) {
  3362. scope = lb_get_llvm_metadata(m, p);
  3363. }
  3364. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  3365. if (m->debug_builder) {
  3366. LLVMMetadataRef res = LLVMDIBuilderCreateLexicalBlock(m->debug_builder, scope,
  3367. file, line, column
  3368. );
  3369. lb_set_llvm_metadata(m, s, res);
  3370. }
  3371. }
  3372. }
  3373. p->scope_index += 1;
  3374. array_add(&p->scope_stack, s);
  3375. }
  3376. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  3377. lb_emit_defer_stmts(p, kind, block);
  3378. GB_ASSERT(p->scope_index > 0);
  3379. // NOTE(bill): Remove `context`s made in that scope
  3380. while (p->context_stack.count > 0) {
  3381. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  3382. if (ctx->scope_index >= p->scope_index) {
  3383. array_pop(&p->context_stack);
  3384. } else {
  3385. break;
  3386. }
  3387. }
  3388. p->scope_index -= 1;
  3389. array_pop(&p->scope_stack);
  3390. }
  3391. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  3392. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  3393. GB_ASSERT(is_type_boolean(tv.type));
  3394. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  3395. if (tv.value.value_bool) {
  3396. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  3397. } else if (ws->else_stmt) {
  3398. switch (ws->else_stmt->kind) {
  3399. case Ast_BlockStmt:
  3400. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  3401. break;
  3402. case Ast_WhenStmt:
  3403. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  3404. break;
  3405. default:
  3406. GB_PANIC("Invalid 'else' statement in 'when' statement");
  3407. break;
  3408. }
  3409. }
  3410. }
  3411. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  3412. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3413. lbModule *m = p->module;
  3414. lbValue count = {};
  3415. Type *expr_type = base_type(type_deref(expr.type));
  3416. switch (expr_type->kind) {
  3417. case Type_Array:
  3418. count = lb_const_int(m, t_int, expr_type->Array.count);
  3419. break;
  3420. }
  3421. lbValue val = {};
  3422. lbValue idx = {};
  3423. lbBlock *loop = nullptr;
  3424. lbBlock *done = nullptr;
  3425. lbBlock *body = nullptr;
  3426. lbAddr index = lb_add_local_generated(p, t_int, false);
  3427. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  3428. loop = lb_create_block(p, "for.index.loop");
  3429. lb_emit_jump(p, loop);
  3430. lb_start_block(p, loop);
  3431. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  3432. lb_addr_store(p, index, incr);
  3433. body = lb_create_block(p, "for.index.body");
  3434. done = lb_create_block(p, "for.index.done");
  3435. if (count.value == nullptr) {
  3436. GB_ASSERT(count_ptr.value != nullptr);
  3437. count = lb_emit_load(p, count_ptr);
  3438. }
  3439. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3440. lb_emit_if(p, cond, body, done);
  3441. lb_start_block(p, body);
  3442. idx = lb_addr_load(p, index);
  3443. switch (expr_type->kind) {
  3444. case Type_Array: {
  3445. if (val_type != nullptr) {
  3446. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3447. }
  3448. break;
  3449. }
  3450. case Type_EnumeratedArray: {
  3451. if (val_type != nullptr) {
  3452. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3453. // NOTE(bill): Override the idx value for the enumeration
  3454. Type *index_type = expr_type->EnumeratedArray.index;
  3455. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  3456. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  3457. }
  3458. }
  3459. break;
  3460. }
  3461. case Type_Slice: {
  3462. if (val_type != nullptr) {
  3463. lbValue elem = lb_slice_elem(p, expr);
  3464. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3465. }
  3466. break;
  3467. }
  3468. case Type_DynamicArray: {
  3469. if (val_type != nullptr) {
  3470. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  3471. elem = lb_emit_load(p, elem);
  3472. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3473. }
  3474. break;
  3475. }
  3476. case Type_Map: {
  3477. lbValue entries = lb_map_entries_ptr(p, expr);
  3478. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  3479. elem = lb_emit_load(p, elem);
  3480. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  3481. idx = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  3482. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 3));
  3483. break;
  3484. }
  3485. case Type_Struct: {
  3486. GB_ASSERT(is_type_soa_struct(expr_type));
  3487. break;
  3488. }
  3489. default:
  3490. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  3491. break;
  3492. }
  3493. if (val_) *val_ = val;
  3494. if (idx_) *idx_ = idx;
  3495. if (loop_) *loop_ = loop;
  3496. if (done_) *done_ = done;
  3497. }
  3498. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  3499. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3500. lbModule *m = p->module;
  3501. lbValue count = lb_const_int(m, t_int, 0);
  3502. Type *expr_type = base_type(expr.type);
  3503. switch (expr_type->kind) {
  3504. case Type_Basic:
  3505. count = lb_string_len(p, expr);
  3506. break;
  3507. default:
  3508. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  3509. break;
  3510. }
  3511. lbValue val = {};
  3512. lbValue idx = {};
  3513. lbBlock *loop = nullptr;
  3514. lbBlock *done = nullptr;
  3515. lbBlock *body = nullptr;
  3516. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3517. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3518. loop = lb_create_block(p, "for.string.loop");
  3519. lb_emit_jump(p, loop);
  3520. lb_start_block(p, loop);
  3521. body = lb_create_block(p, "for.string.body");
  3522. done = lb_create_block(p, "for.string.done");
  3523. lbValue offset = lb_addr_load(p, offset_);
  3524. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  3525. lb_emit_if(p, cond, body, done);
  3526. lb_start_block(p, body);
  3527. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  3528. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  3529. auto args = array_make<lbValue>(permanent_allocator(), 1);
  3530. args[0] = lb_emit_string(p, str_elem, str_len);
  3531. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  3532. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  3533. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  3534. idx = offset;
  3535. if (val_type != nullptr) {
  3536. val = lb_emit_struct_ev(p, rune_and_len, 0);
  3537. }
  3538. if (val_) *val_ = val;
  3539. if (idx_) *idx_ = idx;
  3540. if (loop_) *loop_ = loop;
  3541. if (done_) *done_ = done;
  3542. }
  3543. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node,
  3544. AstRangeStmt *rs, Scope *scope) {
  3545. bool ADD_EXTRA_WRAPPING_CHECK = true;
  3546. lbModule *m = p->module;
  3547. lb_open_scope(p, scope);
  3548. Type *val0_type = nullptr;
  3549. Type *val1_type = nullptr;
  3550. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3551. val0_type = type_of_expr(rs->vals[0]);
  3552. }
  3553. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3554. val1_type = type_of_expr(rs->vals[1]);
  3555. }
  3556. if (val0_type != nullptr) {
  3557. Entity *e = entity_of_node(rs->vals[0]);
  3558. lb_add_local(p, e->type, e, true);
  3559. }
  3560. if (val1_type != nullptr) {
  3561. Entity *e = entity_of_node(rs->vals[1]);
  3562. lb_add_local(p, e->type, e, true);
  3563. }
  3564. TokenKind op = Token_Lt;
  3565. switch (node->op.kind) {
  3566. case Token_Ellipsis: op = Token_LtEq; break;
  3567. case Token_RangeFull: op = Token_LtEq; break;
  3568. case Token_RangeHalf: op = Token_Lt; break;
  3569. default: GB_PANIC("Invalid interval operator"); break;
  3570. }
  3571. lbValue lower = lb_build_expr(p, node->left);
  3572. lbValue upper = {}; // initialized each time in the loop
  3573. lbAddr value = lb_add_local_generated(p, val0_type ? val0_type : lower.type, false);
  3574. lb_addr_store(p, value, lower);
  3575. lbAddr index = lb_add_local_generated(p, t_int, false);
  3576. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  3577. lbBlock *loop = lb_create_block(p, "for.interval.loop");
  3578. lbBlock *body = lb_create_block(p, "for.interval.body");
  3579. lbBlock *done = lb_create_block(p, "for.interval.done");
  3580. lb_emit_jump(p, loop);
  3581. lb_start_block(p, loop);
  3582. upper = lb_build_expr(p, node->right);
  3583. lbValue curr_value = lb_addr_load(p, value);
  3584. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  3585. lb_emit_if(p, cond, body, done);
  3586. lb_start_block(p, body);
  3587. lbValue val = lb_addr_load(p, value);
  3588. lbValue idx = lb_addr_load(p, index);
  3589. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], val);
  3590. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], idx);
  3591. {
  3592. // NOTE: this check block will most likely be optimized out, and is here
  3593. // to make this code easier to read
  3594. lbBlock *check = nullptr;
  3595. lbBlock *post = lb_create_block(p, "for.interval.post");
  3596. lbBlock *continue_block = post;
  3597. if (ADD_EXTRA_WRAPPING_CHECK &&
  3598. op == Token_LtEq) {
  3599. check = lb_create_block(p, "for.interval.check");
  3600. continue_block = check;
  3601. }
  3602. lb_push_target_list(p, rs->label, done, continue_block, nullptr);
  3603. lb_build_stmt(p, rs->body);
  3604. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3605. lb_pop_target_list(p);
  3606. if (check != nullptr) {
  3607. lb_emit_jump(p, check);
  3608. lb_start_block(p, check);
  3609. lbValue check_cond = lb_emit_comp(p, Token_NotEq, curr_value, upper);
  3610. lb_emit_if(p, check_cond, post, done);
  3611. } else {
  3612. lb_emit_jump(p, post);
  3613. }
  3614. lb_start_block(p, post);
  3615. lb_emit_increment(p, value.addr);
  3616. lb_emit_increment(p, index.addr);
  3617. lb_emit_jump(p, loop);
  3618. }
  3619. lb_start_block(p, done);
  3620. }
  3621. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3622. lbModule *m = p->module;
  3623. Type *t = enum_type;
  3624. GB_ASSERT(is_type_enum(t));
  3625. Type *enum_ptr = alloc_type_pointer(t);
  3626. t = base_type(t);
  3627. Type *core_elem = core_type(t);
  3628. GB_ASSERT(t->kind == Type_Enum);
  3629. i64 enum_count = t->Enum.fields.count;
  3630. lbValue max_count = lb_const_int(m, t_int, enum_count);
  3631. lbValue ti = lb_type_info(m, t);
  3632. lbValue variant = lb_emit_struct_ep(p, ti, 4);
  3633. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  3634. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  3635. lbValue values_data = lb_slice_elem(p, values);
  3636. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3637. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3638. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  3639. lb_emit_jump(p, loop);
  3640. lb_start_block(p, loop);
  3641. lbBlock *body = lb_create_block(p, "for.enum.body");
  3642. lbBlock *done = lb_create_block(p, "for.enum.done");
  3643. lbValue offset = lb_addr_load(p, offset_);
  3644. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  3645. lb_emit_if(p, cond, body, done);
  3646. lb_start_block(p, body);
  3647. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  3648. lb_emit_increment(p, offset_.addr);
  3649. lbValue val = {};
  3650. if (val_type != nullptr) {
  3651. GB_ASSERT(are_types_identical(enum_type, val_type));
  3652. if (is_type_integer(core_elem)) {
  3653. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  3654. val = lb_emit_conv(p, i, t);
  3655. } else {
  3656. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  3657. }
  3658. }
  3659. if (val_) *val_ = val;
  3660. if (idx_) *idx_ = offset;
  3661. if (loop_) *loop_ = loop;
  3662. if (done_) *done_ = done;
  3663. }
  3664. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  3665. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  3666. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  3667. lb_emit_jump(p, loop);
  3668. lb_start_block(p, loop);
  3669. lbBlock *body = lb_create_block(p, "for.tuple.body");
  3670. lbBlock *done = lb_create_block(p, "for.tuple.done");
  3671. lbValue tuple_value = lb_build_expr(p, expr);
  3672. Type *tuple = tuple_value.type;
  3673. GB_ASSERT(tuple->kind == Type_Tuple);
  3674. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  3675. i32 cond_index = tuple_count-1;
  3676. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  3677. lb_emit_if(p, cond, body, done);
  3678. lb_start_block(p, body);
  3679. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  3680. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  3681. if (loop_) *loop_ = loop;
  3682. if (done_) *done_ = done;
  3683. }
  3684. void lb_build_range_stmt_struct_soa(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3685. Ast *expr = unparen_expr(rs->expr);
  3686. TypeAndValue tav = type_and_value_of_expr(expr);
  3687. lbBlock *loop = nullptr;
  3688. lbBlock *body = nullptr;
  3689. lbBlock *done = nullptr;
  3690. lb_open_scope(p, scope);
  3691. Type *val_types[2] = {};
  3692. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3693. val_types[0] = type_of_expr(rs->vals[0]);
  3694. }
  3695. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3696. val_types[1] = type_of_expr(rs->vals[1]);
  3697. }
  3698. lbAddr array = lb_build_addr(p, expr);
  3699. if (is_type_pointer(type_deref(lb_addr_type(array)))) {
  3700. array = lb_addr(lb_addr_load(p, array));
  3701. }
  3702. lbValue count = lb_soa_struct_len(p, lb_addr_load(p, array));
  3703. lbAddr index = lb_add_local_generated(p, t_int, false);
  3704. lb_addr_store(p, index, lb_const_int(p->module, t_int, cast(u64)-1));
  3705. loop = lb_create_block(p, "for.soa.loop");
  3706. lb_emit_jump(p, loop);
  3707. lb_start_block(p, loop);
  3708. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(p->module, t_int, 1), t_int);
  3709. lb_addr_store(p, index, incr);
  3710. body = lb_create_block(p, "for.soa.body");
  3711. done = lb_create_block(p, "for.soa.done");
  3712. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3713. lb_emit_if(p, cond, body, done);
  3714. lb_start_block(p, body);
  3715. if (val_types[0]) {
  3716. Entity *e = entity_of_node(rs->vals[0]);
  3717. if (e != nullptr) {
  3718. lbAddr soa_val = lb_addr_soa_variable(array.addr, lb_addr_load(p, index), nullptr);
  3719. map_set(&p->module->soa_values, hash_entity(e), soa_val);
  3720. }
  3721. }
  3722. if (val_types[1]) {
  3723. lb_store_range_stmt_val(p, rs->vals[1], lb_addr_load(p, index));
  3724. }
  3725. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3726. lb_build_stmt(p, rs->body);
  3727. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3728. lb_pop_target_list(p);
  3729. lb_emit_jump(p, loop);
  3730. lb_start_block(p, done);
  3731. }
  3732. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3733. Ast *expr = unparen_expr(rs->expr);
  3734. if (is_ast_range(expr)) {
  3735. lb_build_range_interval(p, &expr->BinaryExpr, rs, scope);
  3736. return;
  3737. }
  3738. Type *expr_type = type_of_expr(expr);
  3739. if (expr_type != nullptr) {
  3740. Type *et = base_type(type_deref(expr_type));
  3741. if (is_type_soa_struct(et)) {
  3742. lb_build_range_stmt_struct_soa(p, rs, scope);
  3743. return;
  3744. }
  3745. }
  3746. lb_open_scope(p, scope);
  3747. Type *val0_type = nullptr;
  3748. Type *val1_type = nullptr;
  3749. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3750. val0_type = type_of_expr(rs->vals[0]);
  3751. }
  3752. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3753. val1_type = type_of_expr(rs->vals[1]);
  3754. }
  3755. if (val0_type != nullptr) {
  3756. Entity *e = entity_of_node(rs->vals[0]);
  3757. lb_add_local(p, e->type, e, true);
  3758. }
  3759. if (val1_type != nullptr) {
  3760. Entity *e = entity_of_node(rs->vals[1]);
  3761. lb_add_local(p, e->type, e, true);
  3762. }
  3763. lbValue val = {};
  3764. lbValue key = {};
  3765. lbBlock *loop = nullptr;
  3766. lbBlock *done = nullptr;
  3767. bool is_map = false;
  3768. TypeAndValue tav = type_and_value_of_expr(expr);
  3769. if (tav.mode == Addressing_Type) {
  3770. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  3771. } else {
  3772. Type *expr_type = type_of_expr(expr);
  3773. Type *et = base_type(type_deref(expr_type));
  3774. switch (et->kind) {
  3775. case Type_Map: {
  3776. is_map = true;
  3777. lbValue map = lb_build_addr_ptr(p, expr);
  3778. if (is_type_pointer(type_deref(map.type))) {
  3779. map = lb_emit_load(p, map);
  3780. }
  3781. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  3782. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  3783. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  3784. break;
  3785. }
  3786. case Type_Array: {
  3787. lbValue array = lb_build_addr_ptr(p, expr);
  3788. if (is_type_pointer(type_deref(array.type))) {
  3789. array = lb_emit_load(p, array);
  3790. }
  3791. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3792. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  3793. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3794. break;
  3795. }
  3796. case Type_EnumeratedArray: {
  3797. lbValue array = lb_build_addr_ptr(p, expr);
  3798. if (is_type_pointer(type_deref(array.type))) {
  3799. array = lb_emit_load(p, array);
  3800. }
  3801. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3802. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  3803. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3804. break;
  3805. }
  3806. case Type_DynamicArray: {
  3807. lbValue count_ptr = {};
  3808. lbValue array = lb_build_addr_ptr(p, expr);
  3809. if (is_type_pointer(type_deref(array.type))) {
  3810. array = lb_emit_load(p, array);
  3811. }
  3812. count_ptr = lb_emit_struct_ep(p, array, 1);
  3813. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  3814. break;
  3815. }
  3816. case Type_Slice: {
  3817. lbValue count_ptr = {};
  3818. lbValue slice = lb_build_expr(p, expr);
  3819. if (is_type_pointer(slice.type)) {
  3820. count_ptr = lb_emit_struct_ep(p, slice, 1);
  3821. slice = lb_emit_load(p, slice);
  3822. } else {
  3823. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  3824. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  3825. }
  3826. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  3827. break;
  3828. }
  3829. case Type_Basic: {
  3830. lbValue string = lb_build_expr(p, expr);
  3831. if (is_type_pointer(string.type)) {
  3832. string = lb_emit_load(p, string);
  3833. }
  3834. if (is_type_untyped(expr_type)) {
  3835. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  3836. lb_addr_store(p, s, string);
  3837. string = lb_addr_load(p, s);
  3838. }
  3839. Type *t = base_type(string.type);
  3840. GB_ASSERT(!is_type_cstring(t));
  3841. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  3842. break;
  3843. }
  3844. case Type_Tuple:
  3845. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  3846. break;
  3847. default:
  3848. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  3849. break;
  3850. }
  3851. }
  3852. if (is_map) {
  3853. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], key);
  3854. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], val);
  3855. } else {
  3856. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], val);
  3857. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], key);
  3858. }
  3859. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3860. lb_build_stmt(p, rs->body);
  3861. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3862. lb_pop_target_list(p);
  3863. lb_emit_jump(p, loop);
  3864. lb_start_block(p, done);
  3865. }
  3866. void lb_build_unroll_range_stmt(lbProcedure *p, AstUnrollRangeStmt *rs, Scope *scope) {
  3867. lbModule *m = p->module;
  3868. lb_open_scope(p, scope); // Open scope here
  3869. Type *val0_type = nullptr;
  3870. Type *val1_type = nullptr;
  3871. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  3872. val0_type = type_of_expr(rs->val0);
  3873. }
  3874. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  3875. val1_type = type_of_expr(rs->val1);
  3876. }
  3877. if (val0_type != nullptr) {
  3878. Entity *e = entity_of_node(rs->val0);
  3879. lb_add_local(p, e->type, e, true);
  3880. }
  3881. if (val1_type != nullptr) {
  3882. Entity *e = entity_of_node(rs->val1);
  3883. lb_add_local(p, e->type, e, true);
  3884. }
  3885. lbValue val = {};
  3886. lbValue key = {};
  3887. lbBlock *loop = nullptr;
  3888. lbBlock *done = nullptr;
  3889. Ast *expr = unparen_expr(rs->expr);
  3890. TypeAndValue tav = type_and_value_of_expr(expr);
  3891. if (is_ast_range(expr)) {
  3892. lbAddr val0_addr = {};
  3893. lbAddr val1_addr = {};
  3894. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3895. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3896. TokenKind op = expr->BinaryExpr.op.kind;
  3897. Ast *start_expr = expr->BinaryExpr.left;
  3898. Ast *end_expr = expr->BinaryExpr.right;
  3899. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  3900. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  3901. ExactValue start = start_expr->tav.value;
  3902. ExactValue end = end_expr->tav.value;
  3903. if (op != Token_RangeHalf) { // .. [start, end] (or ..=)
  3904. ExactValue index = exact_value_i64(0);
  3905. for (ExactValue val = start;
  3906. compare_exact_values(Token_LtEq, val, end);
  3907. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3908. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3909. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3910. lb_build_stmt(p, rs->body);
  3911. }
  3912. } else { // ..< [start, end)
  3913. ExactValue index = exact_value_i64(0);
  3914. for (ExactValue val = start;
  3915. compare_exact_values(Token_Lt, val, end);
  3916. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3917. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3918. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3919. lb_build_stmt(p, rs->body);
  3920. }
  3921. }
  3922. } else if (tav.mode == Addressing_Type) {
  3923. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  3924. Type *et = type_deref(tav.type);
  3925. Type *bet = base_type(et);
  3926. lbAddr val0_addr = {};
  3927. lbAddr val1_addr = {};
  3928. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3929. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3930. for_array(i, bet->Enum.fields) {
  3931. Entity *field = bet->Enum.fields[i];
  3932. GB_ASSERT(field->kind == Entity_Constant);
  3933. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  3934. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3935. lb_build_stmt(p, rs->body);
  3936. }
  3937. } else {
  3938. lbAddr val0_addr = {};
  3939. lbAddr val1_addr = {};
  3940. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3941. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3942. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  3943. Type *t = base_type(expr->tav.type);
  3944. switch (t->kind) {
  3945. case Type_Basic:
  3946. GB_ASSERT(is_type_string(t));
  3947. {
  3948. ExactValue value = expr->tav.value;
  3949. GB_ASSERT(value.kind == ExactValue_String);
  3950. String str = value.value_string;
  3951. Rune codepoint = 0;
  3952. isize offset = 0;
  3953. do {
  3954. isize width = utf8_decode(str.text+offset, str.len-offset, &codepoint);
  3955. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  3956. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  3957. lb_build_stmt(p, rs->body);
  3958. offset += width;
  3959. } while (offset < str.len);
  3960. }
  3961. break;
  3962. case Type_Array:
  3963. if (t->Array.count > 0) {
  3964. lbValue val = lb_build_expr(p, expr);
  3965. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3966. for (i64 i = 0; i < t->Array.count; i++) {
  3967. if (val0_type) {
  3968. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3969. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3970. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3971. }
  3972. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3973. lb_build_stmt(p, rs->body);
  3974. }
  3975. }
  3976. break;
  3977. case Type_EnumeratedArray:
  3978. if (t->EnumeratedArray.count > 0) {
  3979. lbValue val = lb_build_expr(p, expr);
  3980. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3981. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  3982. if (val0_type) {
  3983. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3984. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3985. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3986. }
  3987. if (val1_type) {
  3988. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  3989. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  3990. }
  3991. lb_build_stmt(p, rs->body);
  3992. }
  3993. }
  3994. break;
  3995. default:
  3996. GB_PANIC("Invalid '#unroll for' type");
  3997. break;
  3998. }
  3999. }
  4000. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4001. }
  4002. bool lb_switch_stmt_can_be_trivial_jump_table(AstSwitchStmt *ss, bool *default_found_) {
  4003. if (ss->tag == nullptr) {
  4004. return false;
  4005. }
  4006. bool is_typeid = false;
  4007. TypeAndValue tv = type_and_value_of_expr(ss->tag);
  4008. if (is_type_integer(core_type(tv.type))) {
  4009. // okay
  4010. } else if (is_type_typeid(tv.type)) {
  4011. // okay
  4012. is_typeid = true;
  4013. } else {
  4014. return false;
  4015. }
  4016. ast_node(body, BlockStmt, ss->body);
  4017. for_array(i, body->stmts) {
  4018. Ast *clause = body->stmts[i];
  4019. ast_node(cc, CaseClause, clause);
  4020. if (cc->list.count == 0) {
  4021. if (default_found_) *default_found_ = true;
  4022. continue;
  4023. }
  4024. for_array(j, cc->list) {
  4025. Ast *expr = unparen_expr(cc->list[j]);
  4026. if (is_ast_range(expr)) {
  4027. return false;
  4028. }
  4029. if (expr->tav.mode == Addressing_Type) {
  4030. GB_ASSERT(is_typeid);
  4031. continue;
  4032. }
  4033. tv = type_and_value_of_expr(expr);
  4034. if (tv.mode != Addressing_Constant) {
  4035. return false;
  4036. }
  4037. if (!is_type_integer(core_type(tv.type))) {
  4038. return false;
  4039. }
  4040. }
  4041. }
  4042. return true;
  4043. }
  4044. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss, Scope *scope) {
  4045. lb_open_scope(p, scope);
  4046. if (ss->init != nullptr) {
  4047. lb_build_stmt(p, ss->init);
  4048. }
  4049. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  4050. if (ss->tag != nullptr) {
  4051. tag = lb_build_expr(p, ss->tag);
  4052. }
  4053. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  4054. ast_node(body, BlockStmt, ss->body);
  4055. isize case_count = body->stmts.count;
  4056. Slice<Ast *> default_stmts = {};
  4057. lbBlock *default_fall = nullptr;
  4058. lbBlock *default_block = nullptr;
  4059. lbBlock *fall = nullptr;
  4060. bool default_found = false;
  4061. bool is_trivial = lb_switch_stmt_can_be_trivial_jump_table(ss, &default_found);
  4062. auto body_blocks = slice_make<lbBlock *>(permanent_allocator(), body->stmts.count);
  4063. for_array(i, body->stmts) {
  4064. Ast *clause = body->stmts[i];
  4065. ast_node(cc, CaseClause, clause);
  4066. body_blocks[i] = lb_create_block(p, cc->list.count == 0 ? "switch.default.body" : "switch.case.body");
  4067. if (cc->list.count == 0) {
  4068. default_block = body_blocks[i];
  4069. }
  4070. }
  4071. LLVMValueRef switch_instr = nullptr;
  4072. if (is_trivial) {
  4073. isize num_cases = 0;
  4074. for_array(i, body->stmts) {
  4075. Ast *clause = body->stmts[i];
  4076. ast_node(cc, CaseClause, clause);
  4077. num_cases += cc->list.count;
  4078. }
  4079. LLVMBasicBlockRef end_block = done->block;
  4080. if (default_block) {
  4081. end_block = default_block->block;
  4082. }
  4083. switch_instr = LLVMBuildSwitch(p->builder, tag.value, end_block, cast(unsigned)num_cases);
  4084. }
  4085. for_array(i, body->stmts) {
  4086. Ast *clause = body->stmts[i];
  4087. ast_node(cc, CaseClause, clause);
  4088. lbBlock *body = body_blocks[i];
  4089. fall = done;
  4090. if (i+1 < case_count) {
  4091. fall = body_blocks[i+1];
  4092. }
  4093. if (cc->list.count == 0) {
  4094. // default case
  4095. default_stmts = cc->stmts;
  4096. default_fall = fall;
  4097. if (switch_instr == nullptr) {
  4098. default_block = body;
  4099. } else {
  4100. GB_ASSERT(default_block != nullptr);
  4101. }
  4102. continue;
  4103. }
  4104. lbBlock *next_cond = nullptr;
  4105. for_array(j, cc->list) {
  4106. Ast *expr = unparen_expr(cc->list[j]);
  4107. if (switch_instr != nullptr) {
  4108. lbValue on_val = {};
  4109. if (expr->tav.mode == Addressing_Type) {
  4110. GB_ASSERT(is_type_typeid(tag.type));
  4111. lbValue e = lb_typeid(p->module, expr->tav.type);
  4112. on_val = lb_emit_conv(p, e, tag.type);
  4113. } else {
  4114. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  4115. GB_ASSERT(!is_ast_range(expr));
  4116. on_val = lb_build_expr(p, expr);
  4117. on_val = lb_emit_conv(p, on_val, tag.type);
  4118. }
  4119. GB_ASSERT(LLVMIsConstant(on_val.value));
  4120. LLVMAddCase(switch_instr, on_val.value, body->block);
  4121. continue;
  4122. }
  4123. next_cond = lb_create_block(p, "switch.case.next");
  4124. lbValue cond = {};
  4125. if (is_ast_range(expr)) {
  4126. ast_node(ie, BinaryExpr, expr);
  4127. TokenKind op = Token_Invalid;
  4128. switch (ie->op.kind) {
  4129. case Token_Ellipsis: op = Token_LtEq; break;
  4130. case Token_RangeFull: op = Token_LtEq; break;
  4131. case Token_RangeHalf: op = Token_Lt; break;
  4132. default: GB_PANIC("Invalid interval operator"); break;
  4133. }
  4134. lbValue lhs = lb_build_expr(p, ie->left);
  4135. lbValue rhs = lb_build_expr(p, ie->right);
  4136. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  4137. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  4138. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  4139. } else {
  4140. if (expr->tav.mode == Addressing_Type) {
  4141. GB_ASSERT(is_type_typeid(tag.type));
  4142. lbValue e = lb_typeid(p->module, expr->tav.type);
  4143. e = lb_emit_conv(p, e, tag.type);
  4144. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  4145. } else {
  4146. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  4147. }
  4148. }
  4149. lb_emit_if(p, cond, body, next_cond);
  4150. lb_start_block(p, next_cond);
  4151. }
  4152. lb_start_block(p, body);
  4153. lb_push_target_list(p, ss->label, done, nullptr, fall);
  4154. lb_open_scope(p, body->scope);
  4155. lb_build_stmt_list(p, cc->stmts);
  4156. lb_close_scope(p, lbDeferExit_Default, body);
  4157. lb_pop_target_list(p);
  4158. lb_emit_jump(p, done);
  4159. if (switch_instr == nullptr) {
  4160. lb_start_block(p, next_cond);
  4161. }
  4162. }
  4163. if (default_block != nullptr) {
  4164. if (switch_instr == nullptr) {
  4165. lb_emit_jump(p, default_block);
  4166. }
  4167. lb_start_block(p, default_block);
  4168. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  4169. lb_open_scope(p, default_block->scope);
  4170. lb_build_stmt_list(p, default_stmts);
  4171. lb_close_scope(p, lbDeferExit_Default, default_block);
  4172. lb_pop_target_list(p);
  4173. }
  4174. lb_emit_jump(p, done);
  4175. lb_close_scope(p, lbDeferExit_Default, done);
  4176. lb_start_block(p, done);
  4177. }
  4178. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  4179. Entity *e = implicit_entity_of_node(clause);
  4180. GB_ASSERT(e != nullptr);
  4181. if (e->flags & EntityFlag_Value) {
  4182. // by value
  4183. GB_ASSERT(are_types_identical(e->type, value.type));
  4184. lbAddr x = lb_add_local(p, e->type, e, false);
  4185. lb_addr_store(p, x, value);
  4186. } else {
  4187. // by reference
  4188. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  4189. lb_add_entity(p->module, e, value);
  4190. }
  4191. }
  4192. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  4193. Entity *e = entity_of_node(stmt_val);
  4194. if (e == nullptr) {
  4195. return {};
  4196. }
  4197. if ((e->flags & EntityFlag_Value) == 0) {
  4198. if (LLVMIsALoadInst(value.value)) {
  4199. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  4200. lb_add_entity(p->module, e, ptr);
  4201. return lb_addr(ptr);
  4202. }
  4203. }
  4204. // by value
  4205. lbAddr addr = lb_add_local(p, e->type, e, false);
  4206. lb_addr_store(p, addr, value);
  4207. return addr;
  4208. }
  4209. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  4210. ast_node(cc, CaseClause, clause);
  4211. lb_push_target_list(p, label, done, nullptr, nullptr);
  4212. lb_open_scope(p, body->scope);
  4213. lb_build_stmt_list(p, cc->stmts);
  4214. lb_close_scope(p, lbDeferExit_Default, body);
  4215. lb_pop_target_list(p);
  4216. lb_emit_jump(p, done);
  4217. }
  4218. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  4219. lbModule *m = p->module;
  4220. ast_node(as, AssignStmt, ss->tag);
  4221. GB_ASSERT(as->lhs.count == 1);
  4222. GB_ASSERT(as->rhs.count == 1);
  4223. lbValue parent = lb_build_expr(p, as->rhs[0]);
  4224. bool is_parent_ptr = is_type_pointer(parent.type);
  4225. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  4226. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  4227. lbValue parent_value = parent;
  4228. lbValue parent_ptr = parent;
  4229. if (!is_parent_ptr) {
  4230. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  4231. }
  4232. lbValue tag = {};
  4233. lbValue union_data = {};
  4234. if (switch_kind == TypeSwitch_Union) {
  4235. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  4236. if (is_type_union_maybe_pointer(type_deref(parent_ptr.type))) {
  4237. tag = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, union_data), t_int);
  4238. } else {
  4239. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  4240. tag = lb_emit_load(p, tag_ptr);
  4241. }
  4242. } else if (switch_kind == TypeSwitch_Any) {
  4243. tag = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  4244. } else {
  4245. GB_PANIC("Unknown switch kind");
  4246. }
  4247. ast_node(body, BlockStmt, ss->body);
  4248. lbBlock *done = lb_create_block(p, "typeswitch.done");
  4249. lbBlock *else_block = done;
  4250. lbBlock *default_block = nullptr;
  4251. isize num_cases = 0;
  4252. for_array(i, body->stmts) {
  4253. Ast *clause = body->stmts[i];
  4254. ast_node(cc, CaseClause, clause);
  4255. num_cases += cc->list.count;
  4256. if (cc->list.count == 0) {
  4257. GB_ASSERT(default_block == nullptr);
  4258. default_block = lb_create_block(p, "typeswitch.default.body");
  4259. else_block = default_block;
  4260. }
  4261. }
  4262. GB_ASSERT(tag.value != nullptr);
  4263. LLVMValueRef switch_instr = LLVMBuildSwitch(p->builder, tag.value, else_block->block, cast(unsigned)num_cases);
  4264. for_array(i, body->stmts) {
  4265. Ast *clause = body->stmts[i];
  4266. ast_node(cc, CaseClause, clause);
  4267. if (cc->list.count == 0) {
  4268. lb_start_block(p, default_block);
  4269. lb_store_type_case_implicit(p, clause, parent_value);
  4270. lb_type_case_body(p, ss->label, clause, p->curr_block, done);
  4271. continue;
  4272. }
  4273. lbBlock *body = lb_create_block(p, "typeswitch.body");
  4274. Type *case_type = nullptr;
  4275. for_array(type_index, cc->list) {
  4276. case_type = type_of_expr(cc->list[type_index]);
  4277. lbValue on_val = {};
  4278. if (switch_kind == TypeSwitch_Union) {
  4279. Type *ut = base_type(type_deref(parent.type));
  4280. on_val = lb_const_union_tag(m, ut, case_type);
  4281. } else if (switch_kind == TypeSwitch_Any) {
  4282. on_val = lb_typeid(m, case_type);
  4283. }
  4284. GB_ASSERT(on_val.value != nullptr);
  4285. LLVMAddCase(switch_instr, on_val.value, body->block);
  4286. }
  4287. Entity *case_entity = implicit_entity_of_node(clause);
  4288. lbValue value = parent_value;
  4289. lb_start_block(p, body);
  4290. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  4291. if (cc->list.count == 1) {
  4292. lbValue data = {};
  4293. if (switch_kind == TypeSwitch_Union) {
  4294. data = union_data;
  4295. } else if (switch_kind == TypeSwitch_Any) {
  4296. data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  4297. }
  4298. Type *ct = case_entity->type;
  4299. Type *ct_ptr = alloc_type_pointer(ct);
  4300. value = lb_emit_conv(p, data, ct_ptr);
  4301. if (!by_reference) {
  4302. value = lb_emit_load(p, value);
  4303. }
  4304. }
  4305. lb_store_type_case_implicit(p, clause, value);
  4306. lb_type_case_body(p, ss->label, clause, body, done);
  4307. }
  4308. lb_emit_jump(p, done);
  4309. lb_start_block(p, done);
  4310. }
  4311. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  4312. lbModule *m = p->module;
  4313. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  4314. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  4315. type = default_type(type);
  4316. lbValue short_circuit = {};
  4317. if (op == Token_CmpAnd) {
  4318. lb_build_cond(p, left, rhs, done);
  4319. short_circuit = lb_const_bool(m, type, false);
  4320. } else if (op == Token_CmpOr) {
  4321. lb_build_cond(p, left, done, rhs);
  4322. short_circuit = lb_const_bool(m, type, true);
  4323. }
  4324. if (rhs->preds.count == 0) {
  4325. lb_start_block(p, done);
  4326. return short_circuit;
  4327. }
  4328. if (done->preds.count == 0) {
  4329. lb_start_block(p, rhs);
  4330. if (lb_is_expr_untyped_const(right)) {
  4331. return lb_expr_untyped_const_to_typed(m, right, type);
  4332. }
  4333. return lb_build_expr(p, right);
  4334. }
  4335. Array<LLVMValueRef> incoming_values = {};
  4336. Array<LLVMBasicBlockRef> incoming_blocks = {};
  4337. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  4338. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  4339. for_array(i, done->preds) {
  4340. incoming_values[i] = short_circuit.value;
  4341. incoming_blocks[i] = done->preds[i]->block;
  4342. }
  4343. lb_start_block(p, rhs);
  4344. lbValue edge = {};
  4345. if (lb_is_expr_untyped_const(right)) {
  4346. edge = lb_expr_untyped_const_to_typed(m, right, type);
  4347. } else {
  4348. edge = lb_build_expr(p, right);
  4349. }
  4350. incoming_values[done->preds.count] = edge.value;
  4351. incoming_blocks[done->preds.count] = p->curr_block->block;
  4352. lb_emit_jump(p, done);
  4353. lb_start_block(p, done);
  4354. lbValue res = {};
  4355. res.type = type;
  4356. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  4357. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  4358. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  4359. return res;
  4360. }
  4361. lbCopyElisionHint lb_set_copy_elision_hint(lbProcedure *p, lbAddr const &addr, Ast *ast) {
  4362. lbCopyElisionHint prev = p->copy_elision_hint;
  4363. p->copy_elision_hint.used = false;
  4364. p->copy_elision_hint.ptr = {};
  4365. p->copy_elision_hint.ast = nullptr;
  4366. #if 0
  4367. if (addr.kind == lbAddr_Default && addr.addr.value != nullptr) {
  4368. p->copy_elision_hint.ptr = lb_addr_get_ptr(p, addr);
  4369. p->copy_elision_hint.ast = unparen_expr(ast);
  4370. }
  4371. #endif
  4372. return prev;
  4373. }
  4374. void lb_reset_copy_elision_hint(lbProcedure *p, lbCopyElisionHint prev_hint) {
  4375. p->copy_elision_hint = prev_hint;
  4376. }
  4377. lbValue lb_consume_copy_elision_hint(lbProcedure *p) {
  4378. lbValue return_ptr = p->copy_elision_hint.ptr;
  4379. p->copy_elision_hint.used = true;
  4380. p->copy_elision_hint.ptr = {};
  4381. p->copy_elision_hint.ast = nullptr;
  4382. return return_ptr;
  4383. }
  4384. void lb_build_static_variables(lbProcedure *p, AstValueDecl *vd) {
  4385. for_array(i, vd->names) {
  4386. lbValue value = {};
  4387. if (vd->values.count > 0) {
  4388. GB_ASSERT(vd->names.count == vd->values.count);
  4389. Ast *ast_value = vd->values[i];
  4390. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  4391. ast_value->tav.mode == Addressing_Invalid);
  4392. bool allow_local = false;
  4393. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  4394. }
  4395. Ast *ident = vd->names[i];
  4396. GB_ASSERT(!is_blank_ident(ident));
  4397. Entity *e = entity_of_node(ident);
  4398. GB_ASSERT(e->flags & EntityFlag_Static);
  4399. String name = e->token.string;
  4400. String mangled_name = {};
  4401. {
  4402. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  4403. str = gb_string_appendc(str, "-");
  4404. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  4405. mangled_name.text = cast(u8 *)str;
  4406. mangled_name.len = gb_string_length(str);
  4407. }
  4408. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  4409. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  4410. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  4411. if (value.value != nullptr) {
  4412. LLVMSetInitializer(global, value.value);
  4413. } else {
  4414. }
  4415. if (e->Variable.thread_local_model != "") {
  4416. LLVMSetThreadLocal(global, true);
  4417. String m = e->Variable.thread_local_model;
  4418. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  4419. if (m == "default") {
  4420. mode = LLVMGeneralDynamicTLSModel;
  4421. } else if (m == "localdynamic") {
  4422. mode = LLVMLocalDynamicTLSModel;
  4423. } else if (m == "initialexec") {
  4424. mode = LLVMInitialExecTLSModel;
  4425. } else if (m == "localexec") {
  4426. mode = LLVMLocalExecTLSModel;
  4427. } else {
  4428. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  4429. }
  4430. LLVMSetThreadLocalMode(global, mode);
  4431. } else {
  4432. LLVMSetLinkage(global, LLVMInternalLinkage);
  4433. }
  4434. lbValue global_val = {global, alloc_type_pointer(e->type)};
  4435. lb_add_entity(p->module, e, global_val);
  4436. lb_add_member(p->module, mangled_name, global_val);
  4437. }
  4438. }
  4439. void lb_build_assignment(lbProcedure *p, Array<lbAddr> &lvals, Slice<Ast *> const &values) {
  4440. if (values.count == 0) {
  4441. return;
  4442. }
  4443. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  4444. for_array(i, values) {
  4445. Ast *rhs = values[i];
  4446. if (is_type_tuple(type_of_expr(rhs))) {
  4447. lbValue init = lb_build_expr(p, rhs);
  4448. Type *t = init.type;
  4449. GB_ASSERT(t->kind == Type_Tuple);
  4450. for_array(i, t->Tuple.variables) {
  4451. Entity *e = t->Tuple.variables[i];
  4452. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  4453. array_add(&inits, v);
  4454. }
  4455. } else {
  4456. auto prev_hint = lb_set_copy_elision_hint(p, lvals[inits.count], rhs);
  4457. lbValue init = lb_build_expr(p, rhs);
  4458. if (p->copy_elision_hint.used) {
  4459. lvals[inits.count] = {}; // zero lval
  4460. }
  4461. lb_reset_copy_elision_hint(p, prev_hint);
  4462. array_add(&inits, init);
  4463. }
  4464. }
  4465. GB_ASSERT(lvals.count == inits.count);
  4466. for_array(i, inits) {
  4467. lbAddr lval = lvals[i];
  4468. lbValue init = inits[i];
  4469. lb_addr_store(p, lval, init);
  4470. }
  4471. }
  4472. void lb_build_return_stmt_internal(lbProcedure *p, lbValue const &res) {
  4473. lbFunctionType *ft = lb_get_function_type(p->module, p, p->type);
  4474. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  4475. if (return_by_pointer) {
  4476. if (res.value != nullptr) {
  4477. LLVMBuildStore(p->builder, res.value, p->return_ptr.addr.value);
  4478. } else {
  4479. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  4480. }
  4481. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4482. LLVMBuildRetVoid(p->builder);
  4483. } else {
  4484. LLVMValueRef ret_val = res.value;
  4485. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  4486. if (p->abi_function_type->ret.cast_type != nullptr) {
  4487. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  4488. }
  4489. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4490. LLVMBuildRet(p->builder, ret_val);
  4491. }
  4492. }
  4493. void lb_build_return_stmt(lbProcedure *p, Slice<Ast *> const &return_results) {
  4494. lb_ensure_abi_function_type(p->module, p);
  4495. lbValue res = {};
  4496. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  4497. isize return_count = p->type->Proc.result_count;
  4498. isize res_count = return_results.count;
  4499. lbFunctionType *ft = lb_get_function_type(p->module, p, p->type);
  4500. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  4501. if (return_count == 0) {
  4502. // No return values
  4503. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4504. LLVMBuildRetVoid(p->builder);
  4505. return;
  4506. } else if (return_count == 1) {
  4507. Entity *e = tuple->variables[0];
  4508. if (res_count == 0) {
  4509. lbValue found = map_must_get(&p->module->values, hash_entity(e));
  4510. res = lb_emit_load(p, found);
  4511. } else {
  4512. res = lb_build_expr(p, return_results[0]);
  4513. res = lb_emit_conv(p, res, e->type);
  4514. }
  4515. if (p->type->Proc.has_named_results) {
  4516. // NOTE(bill): store the named values before returning
  4517. if (e->token.string != "") {
  4518. lbValue found = map_must_get(&p->module->values, hash_entity(e));
  4519. lb_emit_store(p, found, lb_emit_conv(p, res, e->type));
  4520. }
  4521. }
  4522. } else {
  4523. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  4524. if (res_count != 0) {
  4525. for (isize res_index = 0; res_index < res_count; res_index++) {
  4526. lbValue res = lb_build_expr(p, return_results[res_index]);
  4527. Type *t = res.type;
  4528. if (t->kind == Type_Tuple) {
  4529. for_array(i, t->Tuple.variables) {
  4530. Entity *e = t->Tuple.variables[i];
  4531. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  4532. array_add(&results, v);
  4533. }
  4534. } else {
  4535. array_add(&results, res);
  4536. }
  4537. }
  4538. } else {
  4539. for (isize res_index = 0; res_index < return_count; res_index++) {
  4540. Entity *e = tuple->variables[res_index];
  4541. lbValue found = map_must_get(&p->module->values, hash_entity(e));
  4542. lbValue res = lb_emit_load(p, found);
  4543. array_add(&results, res);
  4544. }
  4545. }
  4546. GB_ASSERT(results.count == return_count);
  4547. if (p->type->Proc.has_named_results) {
  4548. auto named_results = slice_make<lbValue>(temporary_allocator(), results.count);
  4549. auto values = slice_make<lbValue>(temporary_allocator(), results.count);
  4550. // NOTE(bill): store the named values before returning
  4551. for_array(i, p->type->Proc.results->Tuple.variables) {
  4552. Entity *e = p->type->Proc.results->Tuple.variables[i];
  4553. if (e->kind != Entity_Variable) {
  4554. continue;
  4555. }
  4556. if (e->token.string == "") {
  4557. continue;
  4558. }
  4559. named_results[i] = map_must_get(&p->module->values, hash_entity(e));
  4560. values[i] = lb_emit_conv(p, results[i], e->type);
  4561. }
  4562. for_array(i, named_results) {
  4563. lb_emit_store(p, named_results[i], values[i]);
  4564. }
  4565. }
  4566. Type *ret_type = p->type->Proc.results;
  4567. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4568. if (return_by_pointer) {
  4569. res = p->return_ptr.addr;
  4570. } else {
  4571. res = lb_add_local_generated(p, ret_type, false).addr;
  4572. }
  4573. auto result_values = slice_make<lbValue>(temporary_allocator(), results.count);
  4574. auto result_eps = slice_make<lbValue>(temporary_allocator(), results.count);
  4575. for_array(i, results) {
  4576. result_values[i] = lb_emit_conv(p, results[i], tuple->variables[i]->type);
  4577. }
  4578. for_array(i, results) {
  4579. result_eps[i] = lb_emit_struct_ep(p, res, cast(i32)i);
  4580. }
  4581. for_array(i, result_values) {
  4582. lb_emit_store(p, result_eps[i], result_values[i]);
  4583. }
  4584. if (return_by_pointer) {
  4585. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4586. LLVMBuildRetVoid(p->builder);
  4587. return;
  4588. }
  4589. res = lb_emit_load(p, res);
  4590. }
  4591. lb_build_return_stmt_internal(p, res);
  4592. }
  4593. void lb_build_if_stmt(lbProcedure *p, Ast *node) {
  4594. ast_node(is, IfStmt, node);
  4595. lb_open_scope(p, node->scope); // Scope #1
  4596. defer (lb_close_scope(p, lbDeferExit_Default, nullptr));
  4597. if (is->init != nullptr) {
  4598. // TODO(bill): Should this have a separate block to begin with?
  4599. #if 1
  4600. lbBlock *init = lb_create_block(p, "if.init");
  4601. lb_emit_jump(p, init);
  4602. lb_start_block(p, init);
  4603. #endif
  4604. lb_build_stmt(p, is->init);
  4605. }
  4606. lbBlock *then = lb_create_block(p, "if.then");
  4607. lbBlock *done = lb_create_block(p, "if.done");
  4608. lbBlock *else_ = done;
  4609. if (is->else_stmt != nullptr) {
  4610. else_ = lb_create_block(p, "if.else");
  4611. }
  4612. lbValue cond = lb_build_cond(p, is->cond, then, else_);
  4613. if (is->label != nullptr) {
  4614. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  4615. tl->is_block = true;
  4616. }
  4617. if (LLVMIsConstant(cond.value)) {
  4618. // NOTE(bill): Do a compile time short circuit for when the condition is constantly known.
  4619. // This done manually rather than relying on the SSA passes because sometimes the SSA passes
  4620. // miss some even if they are constantly known, especially with few optimization passes.
  4621. bool const_cond = LLVMConstIntGetZExtValue(cond.value) != 0;
  4622. LLVMValueRef if_instr = LLVMGetLastInstruction(p->curr_block->block);
  4623. GB_ASSERT(LLVMGetInstructionOpcode(if_instr) == LLVMBr);
  4624. GB_ASSERT(LLVMIsConditional(if_instr));
  4625. LLVMInstructionEraseFromParent(if_instr);
  4626. if (const_cond) {
  4627. lb_emit_jump(p, then);
  4628. lb_start_block(p, then);
  4629. lb_build_stmt(p, is->body);
  4630. lb_emit_jump(p, done);
  4631. } else {
  4632. if (is->else_stmt != nullptr) {
  4633. lb_emit_jump(p, else_);
  4634. lb_start_block(p, else_);
  4635. lb_open_scope(p, is->else_stmt->scope);
  4636. lb_build_stmt(p, is->else_stmt);
  4637. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4638. }
  4639. lb_emit_jump(p, done);
  4640. }
  4641. } else {
  4642. lb_start_block(p, then);
  4643. lb_build_stmt(p, is->body);
  4644. lb_emit_jump(p, done);
  4645. if (is->else_stmt != nullptr) {
  4646. lb_start_block(p, else_);
  4647. lb_open_scope(p, is->else_stmt->scope);
  4648. lb_build_stmt(p, is->else_stmt);
  4649. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4650. lb_emit_jump(p, done);
  4651. }
  4652. }
  4653. if (is->label != nullptr) {
  4654. lb_pop_target_list(p);
  4655. }
  4656. lb_start_block(p, done);
  4657. }
  4658. void lb_build_for_stmt(lbProcedure *p, Ast *node) {
  4659. ast_node(fs, ForStmt, node);
  4660. lb_open_scope(p, node->scope); // Open Scope here
  4661. if (fs->init != nullptr) {
  4662. #if 1
  4663. lbBlock *init = lb_create_block(p, "for.init");
  4664. lb_emit_jump(p, init);
  4665. lb_start_block(p, init);
  4666. #endif
  4667. lb_build_stmt(p, fs->init);
  4668. }
  4669. lbBlock *body = lb_create_block(p, "for.body");
  4670. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  4671. lbBlock *loop = body;
  4672. if (fs->cond != nullptr) {
  4673. loop = lb_create_block(p, "for.loop");
  4674. }
  4675. lbBlock *post = loop;
  4676. if (fs->post != nullptr) {
  4677. post = lb_create_block(p, "for.post");
  4678. }
  4679. lb_emit_jump(p, loop);
  4680. lb_start_block(p, loop);
  4681. if (loop != body) {
  4682. lb_build_cond(p, fs->cond, body, done);
  4683. lb_start_block(p, body);
  4684. }
  4685. lb_push_target_list(p, fs->label, done, post, nullptr);
  4686. lb_build_stmt(p, fs->body);
  4687. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4688. lb_pop_target_list(p);
  4689. lb_emit_jump(p, post);
  4690. if (fs->post != nullptr) {
  4691. lb_start_block(p, post);
  4692. lb_build_stmt(p, fs->post);
  4693. lb_emit_jump(p, loop);
  4694. }
  4695. lb_start_block(p, done);
  4696. }
  4697. void lb_build_assign_stmt_array(lbProcedure *p, TokenKind op, lbAddr const &lhs, lbValue const &value) {
  4698. Type *lhs_type = lb_addr_type(lhs);
  4699. Type *rhs_type = value.type;
  4700. Type *array_type = base_type(lhs_type);
  4701. GB_ASSERT(is_type_array_like(array_type));
  4702. i64 count = get_array_type_count(array_type);
  4703. Type *elem_type = base_array_type(array_type);
  4704. lbValue rhs = lb_emit_conv(p, value, lhs_type);
  4705. bool inline_array_arith = type_size_of(array_type) <= build_context.max_align;
  4706. if (lhs.kind == lbAddr_Swizzle) {
  4707. GB_ASSERT(is_type_array(lhs_type));
  4708. struct ValueAndIndex {
  4709. lbValue value;
  4710. u8 index;
  4711. };
  4712. bool indices_handled[4] = {};
  4713. i32 indices[4] = {};
  4714. i32 index_count = 0;
  4715. for (u8 i = 0; i < lhs.swizzle.count; i++) {
  4716. u8 index = lhs.swizzle.indices[i];
  4717. if (indices_handled[index]) {
  4718. continue;
  4719. }
  4720. indices[index_count++] = index;
  4721. }
  4722. gb_sort_array(indices, index_count, gb_i32_cmp(0));
  4723. lbValue lhs_ptrs[4] = {};
  4724. lbValue x_loads[4] = {};
  4725. lbValue y_loads[4] = {};
  4726. lbValue ops[4] = {};
  4727. for (i32 i = 0; i < index_count; i++) {
  4728. lhs_ptrs[i] = lb_emit_array_epi(p, lhs.addr, indices[i]);
  4729. }
  4730. for (i32 i = 0; i < index_count; i++) {
  4731. x_loads[i] = lb_emit_load(p, lhs_ptrs[i]);
  4732. }
  4733. for (i32 i = 0; i < index_count; i++) {
  4734. y_loads[i].value = LLVMBuildExtractValue(p->builder, rhs.value, i, "");
  4735. y_loads[i].type = elem_type;
  4736. }
  4737. for (i32 i = 0; i < index_count; i++) {
  4738. ops[i] = lb_emit_arith(p, op, x_loads[i], y_loads[i], elem_type);
  4739. }
  4740. for (i32 i = 0; i < index_count; i++) {
  4741. lb_emit_store(p, lhs_ptrs[i], ops[i]);
  4742. }
  4743. return;
  4744. }
  4745. lbValue x = lb_addr_get_ptr(p, lhs);
  4746. if (inline_array_arith) {
  4747. #if 1
  4748. #if 1
  4749. unsigned n = cast(unsigned)count;
  4750. auto lhs_ptrs = slice_make<lbValue>(temporary_allocator(), n);
  4751. auto x_loads = slice_make<lbValue>(temporary_allocator(), n);
  4752. auto y_loads = slice_make<lbValue>(temporary_allocator(), n);
  4753. auto ops = slice_make<lbValue>(temporary_allocator(), n);
  4754. for (unsigned i = 0; i < n; i++) {
  4755. lhs_ptrs[i] = lb_emit_array_epi(p, x, i);
  4756. }
  4757. for (unsigned i = 0; i < n; i++) {
  4758. x_loads[i] = lb_emit_load(p, lhs_ptrs[i]);
  4759. }
  4760. for (unsigned i = 0; i < n; i++) {
  4761. y_loads[i].value = LLVMBuildExtractValue(p->builder, rhs.value, i, "");
  4762. y_loads[i].type = elem_type;
  4763. }
  4764. for (unsigned i = 0; i < n; i++) {
  4765. ops[i] = lb_emit_arith(p, op, x_loads[i], y_loads[i], elem_type);
  4766. }
  4767. for (unsigned i = 0; i < n; i++) {
  4768. lb_emit_store(p, lhs_ptrs[i], ops[i]);
  4769. }
  4770. #else
  4771. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  4772. unsigned n = cast(unsigned)count;
  4773. auto lhs_ptrs = slice_make<lbValue>(temporary_allocator(), n);
  4774. auto rhs_ptrs = slice_make<lbValue>(temporary_allocator(), n);
  4775. auto x_loads = slice_make<lbValue>(temporary_allocator(), n);
  4776. auto y_loads = slice_make<lbValue>(temporary_allocator(), n);
  4777. auto ops = slice_make<lbValue>(temporary_allocator(), n);
  4778. for (unsigned i = 0; i < n; i++) {
  4779. lhs_ptrs[i] = lb_emit_array_epi(p, x, i);
  4780. }
  4781. for (unsigned i = 0; i < n; i++) {
  4782. rhs_ptrs[i] = lb_emit_array_epi(p, y, i);
  4783. }
  4784. for (unsigned i = 0; i < n; i++) {
  4785. x_loads[i] = lb_emit_load(p, lhs_ptrs[i]);
  4786. }
  4787. for (unsigned i = 0; i < n; i++) {
  4788. y_loads[i] = lb_emit_load(p, rhs_ptrs[i]);
  4789. }
  4790. for (unsigned i = 0; i < n; i++) {
  4791. ops[i] = lb_emit_arith(p, op, x_loads[i], y_loads[i], elem_type);
  4792. }
  4793. for (unsigned i = 0; i < n; i++) {
  4794. lb_emit_store(p, lhs_ptrs[i], ops[i]);
  4795. }
  4796. #endif
  4797. #else
  4798. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  4799. for (i64 i = 0; i < count; i++) {
  4800. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  4801. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  4802. lbValue a = lb_emit_load(p, a_ptr);
  4803. lbValue b = lb_emit_load(p, b_ptr);
  4804. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4805. lb_emit_store(p, a_ptr, c);
  4806. }
  4807. #endif
  4808. } else {
  4809. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  4810. auto loop_data = lb_loop_start(p, cast(isize)count, t_i32);
  4811. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  4812. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  4813. lbValue a = lb_emit_load(p, a_ptr);
  4814. lbValue b = lb_emit_load(p, b_ptr);
  4815. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4816. lb_emit_store(p, a_ptr, c);
  4817. lb_loop_end(p, loop_data);
  4818. }
  4819. }
  4820. void lb_build_assign_stmt(lbProcedure *p, AstAssignStmt *as) {
  4821. if (as->op.kind == Token_Eq) {
  4822. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  4823. for_array(i, as->lhs) {
  4824. Ast *lhs = as->lhs[i];
  4825. lbAddr lval = {};
  4826. if (!is_blank_ident(lhs)) {
  4827. lval = lb_build_addr(p, lhs);
  4828. }
  4829. array_add(&lvals, lval);
  4830. }
  4831. lb_build_assignment(p, lvals, as->rhs);
  4832. return;
  4833. }
  4834. GB_ASSERT(as->lhs.count == 1);
  4835. GB_ASSERT(as->rhs.count == 1);
  4836. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  4837. // +=, -=, etc
  4838. i32 op_ = cast(i32)as->op.kind;
  4839. op_ += Token_Add - Token_AddEq; // Convert += to +
  4840. TokenKind op = cast(TokenKind)op_;
  4841. if (op == Token_CmpAnd || op == Token_CmpOr) {
  4842. Type *type = as->lhs[0]->tav.type;
  4843. lbValue new_value = lb_emit_logical_binary_expr(p, op, as->lhs[0], as->rhs[0], type);
  4844. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4845. lb_addr_store(p, lhs, new_value);
  4846. } else {
  4847. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4848. lbValue value = lb_build_expr(p, as->rhs[0]);
  4849. Type *lhs_type = lb_addr_type(lhs);
  4850. if (is_type_array(lhs_type)) {
  4851. lb_build_assign_stmt_array(p, op, lhs, value);
  4852. return;
  4853. } else {
  4854. lbValue old_value = lb_addr_load(p, lhs);
  4855. Type *type = old_value.type;
  4856. lbValue change = lb_emit_conv(p, value, type);
  4857. lbValue new_value = lb_emit_arith(p, op, old_value, change, type);
  4858. lb_addr_store(p, lhs, new_value);
  4859. }
  4860. }
  4861. }
  4862. void lb_build_stmt(lbProcedure *p, Ast *node) {
  4863. Ast *prev_stmt = p->curr_stmt;
  4864. defer (p->curr_stmt = prev_stmt);
  4865. p->curr_stmt = node;
  4866. if (p->curr_block != nullptr) {
  4867. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  4868. if (lb_is_instr_terminating(last_instr)) {
  4869. return;
  4870. }
  4871. }
  4872. LLVMMetadataRef prev_debug_location = nullptr;
  4873. if (p->debug_info != nullptr) {
  4874. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  4875. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, node));
  4876. }
  4877. defer (if (prev_debug_location != nullptr) {
  4878. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  4879. });
  4880. u16 prev_state_flags = p->state_flags;
  4881. defer (p->state_flags = prev_state_flags);
  4882. if (node->state_flags != 0) {
  4883. u16 in = node->state_flags;
  4884. u16 out = p->state_flags;
  4885. if (in & StateFlag_bounds_check) {
  4886. out |= StateFlag_bounds_check;
  4887. out &= ~StateFlag_no_bounds_check;
  4888. } else if (in & StateFlag_no_bounds_check) {
  4889. out |= StateFlag_no_bounds_check;
  4890. out &= ~StateFlag_bounds_check;
  4891. }
  4892. p->state_flags = out;
  4893. }
  4894. switch (node->kind) {
  4895. case_ast_node(bs, EmptyStmt, node);
  4896. case_end;
  4897. case_ast_node(us, UsingStmt, node);
  4898. case_end;
  4899. case_ast_node(ws, WhenStmt, node);
  4900. lb_build_when_stmt(p, ws);
  4901. case_end;
  4902. case_ast_node(bs, BlockStmt, node);
  4903. lbBlock *done = nullptr;
  4904. if (bs->label != nullptr) {
  4905. done = lb_create_block(p, "block.done");
  4906. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  4907. tl->is_block = true;
  4908. }
  4909. lb_open_scope(p, node->scope);
  4910. lb_build_stmt_list(p, bs->stmts);
  4911. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4912. if (done != nullptr) {
  4913. lb_emit_jump(p, done);
  4914. lb_start_block(p, done);
  4915. }
  4916. if (bs->label != nullptr) {
  4917. lb_pop_target_list(p);
  4918. }
  4919. case_end;
  4920. case_ast_node(vd, ValueDecl, node);
  4921. if (!vd->is_mutable) {
  4922. return;
  4923. }
  4924. bool is_static = false;
  4925. if (vd->names.count > 0) {
  4926. Entity *e = entity_of_node(vd->names[0]);
  4927. if (e->flags & EntityFlag_Static) {
  4928. // NOTE(bill): If one of the entities is static, they all are
  4929. is_static = true;
  4930. }
  4931. }
  4932. if (is_static) {
  4933. lb_build_static_variables(p, vd);
  4934. return;
  4935. }
  4936. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, vd->names.count);
  4937. for_array(i, vd->names) {
  4938. Ast *name = vd->names[i];
  4939. lbAddr lval = {};
  4940. if (!is_blank_ident(name)) {
  4941. Entity *e = entity_of_node(name);
  4942. bool zero_init = true; // Always do it
  4943. lval = lb_add_local(p, e->type, e, zero_init);
  4944. }
  4945. array_add(&lvals, lval);
  4946. }
  4947. lb_build_assignment(p, lvals, vd->values);
  4948. case_end;
  4949. case_ast_node(as, AssignStmt, node);
  4950. lb_build_assign_stmt(p, as);
  4951. case_end;
  4952. case_ast_node(es, ExprStmt, node);
  4953. lb_build_expr(p, es->expr);
  4954. case_end;
  4955. case_ast_node(ds, DeferStmt, node);
  4956. lb_add_defer_node(p, p->scope_index, ds->stmt);
  4957. case_end;
  4958. case_ast_node(rs, ReturnStmt, node);
  4959. lb_build_return_stmt(p, rs->results);
  4960. case_end;
  4961. case_ast_node(is, IfStmt, node);
  4962. lb_build_if_stmt(p, node);
  4963. case_end;
  4964. case_ast_node(fs, ForStmt, node);
  4965. lb_build_for_stmt(p, node);
  4966. case_end;
  4967. case_ast_node(rs, RangeStmt, node);
  4968. lb_build_range_stmt(p, rs, node->scope);
  4969. case_end;
  4970. case_ast_node(rs, UnrollRangeStmt, node);
  4971. lb_build_unroll_range_stmt(p, rs, node->scope);
  4972. case_end;
  4973. case_ast_node(ss, SwitchStmt, node);
  4974. lb_build_switch_stmt(p, ss, node->scope);
  4975. case_end;
  4976. case_ast_node(ss, TypeSwitchStmt, node);
  4977. lb_build_type_switch_stmt(p, ss);
  4978. case_end;
  4979. case_ast_node(bs, BranchStmt, node);
  4980. lbBlock *block = nullptr;
  4981. if (bs->label != nullptr) {
  4982. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  4983. switch (bs->token.kind) {
  4984. case Token_break: block = bb.break_; break;
  4985. case Token_continue: block = bb.continue_; break;
  4986. case Token_fallthrough:
  4987. GB_PANIC("fallthrough cannot have a label");
  4988. break;
  4989. }
  4990. } else {
  4991. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  4992. if (t->is_block) {
  4993. continue;
  4994. }
  4995. switch (bs->token.kind) {
  4996. case Token_break: block = t->break_; break;
  4997. case Token_continue: block = t->continue_; break;
  4998. case Token_fallthrough: block = t->fallthrough_; break;
  4999. }
  5000. }
  5001. }
  5002. if (block != nullptr) {
  5003. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  5004. }
  5005. lb_emit_jump(p, block);
  5006. case_end;
  5007. }
  5008. }
  5009. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  5010. cond = lb_emit_conv(p, cond, t_llvm_bool);
  5011. lbValue res = {};
  5012. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  5013. res.type = x.type;
  5014. return res;
  5015. }
  5016. lbValue lb_const_nil(lbModule *m, Type *type) {
  5017. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  5018. return lbValue{v, type};
  5019. }
  5020. lbValue lb_const_undef(lbModule *m, Type *type) {
  5021. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  5022. return lbValue{v, type};
  5023. }
  5024. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  5025. lbValue res = {};
  5026. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  5027. res.type = type;
  5028. return res;
  5029. }
  5030. lbValue lb_const_string(lbModule *m, String const &value) {
  5031. return lb_const_value(m, t_string, exact_value_string(value));
  5032. }
  5033. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  5034. lbValue res = {};
  5035. res.value = LLVMConstInt(lb_type(m, type), value, false);
  5036. res.type = type;
  5037. return res;
  5038. }
  5039. LLVMValueRef lb_const_f16(lbModule *m, f32 f, Type *type=t_f16) {
  5040. GB_ASSERT(type_size_of(type) == 2);
  5041. u16 u = f32_to_f16(f);
  5042. if (is_type_different_to_arch_endianness(type)) {
  5043. u = gb_endian_swap16(u);
  5044. }
  5045. LLVMValueRef i = LLVMConstInt(LLVMInt16TypeInContext(m->ctx), u, false);
  5046. return LLVMConstBitCast(i, lb_type(m, type));
  5047. }
  5048. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  5049. GB_ASSERT(type_size_of(type) == 4);
  5050. u32 u = bit_cast<u32>(f);
  5051. if (is_type_different_to_arch_endianness(type)) {
  5052. u = gb_endian_swap32(u);
  5053. }
  5054. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  5055. return LLVMConstBitCast(i, lb_type(m, type));
  5056. }
  5057. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  5058. x = lb_emit_conv(p, x, t);
  5059. y = lb_emit_conv(p, y, t);
  5060. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  5061. }
  5062. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  5063. x = lb_emit_conv(p, x, t);
  5064. y = lb_emit_conv(p, y, t);
  5065. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  5066. }
  5067. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  5068. lbValue z = {};
  5069. z = lb_emit_max(p, t, x, min);
  5070. z = lb_emit_min(p, t, z, max);
  5071. return z;
  5072. }
  5073. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  5074. StringHashKey key = string_hash_string(str);
  5075. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  5076. if (found != nullptr) {
  5077. return *found;
  5078. } else {
  5079. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  5080. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  5081. cast(char const *)str.text,
  5082. cast(unsigned)str.len,
  5083. false);
  5084. isize max_len = 7+8+1;
  5085. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  5086. u32 id = cast(u32)gb_atomic32_fetch_add(&m->gen->global_array_index, 1);
  5087. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  5088. len -= 1;
  5089. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  5090. LLVMSetInitializer(global_data, data);
  5091. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  5092. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  5093. string_map_set(&m->const_strings, key, ptr);
  5094. return ptr;
  5095. }
  5096. }
  5097. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  5098. LLVMValueRef ptr = nullptr;
  5099. if (str.len != 0) {
  5100. ptr = lb_find_or_add_entity_string_ptr(m, str);
  5101. } else {
  5102. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  5103. }
  5104. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  5105. LLVMValueRef values[2] = {ptr, str_len};
  5106. lbValue res = {};
  5107. res.value = llvm_const_named_struct(lb_type(m, t_string), values, 2);
  5108. res.type = t_string;
  5109. return res;
  5110. }
  5111. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  5112. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  5113. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  5114. cast(char const *)str.text,
  5115. cast(unsigned)str.len,
  5116. false);
  5117. char *name = nullptr;
  5118. {
  5119. isize max_len = 7+8+1;
  5120. name = gb_alloc_array(permanent_allocator(), char, max_len);
  5121. u32 id = cast(u32)gb_atomic32_fetch_add(&m->gen->global_array_index, 1);
  5122. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  5123. len -= 1;
  5124. }
  5125. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  5126. LLVMSetInitializer(global_data, data);
  5127. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  5128. LLVMValueRef ptr = nullptr;
  5129. if (str.len != 0) {
  5130. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  5131. } else {
  5132. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  5133. }
  5134. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  5135. LLVMValueRef values[2] = {ptr, len};
  5136. lbValue res = {};
  5137. res.value = llvm_const_named_struct(lb_type(m, t_u8_slice), values, 2);
  5138. res.type = t_u8_slice;
  5139. return res;
  5140. }
  5141. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  5142. isize index = type_info_index(info, type, false);
  5143. if (index >= 0) {
  5144. auto *set = &info->minimum_dependency_type_info_set;
  5145. for_array(i, set->entries) {
  5146. if (set->entries[i].ptr == index) {
  5147. return i+1;
  5148. }
  5149. }
  5150. }
  5151. if (err_on_not_found) {
  5152. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  5153. }
  5154. return -1;
  5155. }
  5156. lbValue lb_typeid(lbModule *m, Type *type) {
  5157. type = default_type(type);
  5158. u64 id = cast(u64)lb_type_info_index(m->info, type);
  5159. GB_ASSERT(id >= 0);
  5160. u64 kind = Typeid_Invalid;
  5161. u64 named = is_type_named(type) && type->kind != Type_Basic;
  5162. u64 special = 0;
  5163. u64 reserved = 0;
  5164. Type *bt = base_type(type);
  5165. TypeKind tk = bt->kind;
  5166. switch (tk) {
  5167. case Type_Basic: {
  5168. u32 flags = bt->Basic.flags;
  5169. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  5170. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  5171. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  5172. if (flags & BasicFlag_Float) kind = Typeid_Float;
  5173. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  5174. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  5175. if (flags & BasicFlag_String) kind = Typeid_String;
  5176. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  5177. } break;
  5178. case Type_Pointer: kind = Typeid_Pointer; break;
  5179. case Type_Array: kind = Typeid_Array; break;
  5180. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  5181. case Type_Slice: kind = Typeid_Slice; break;
  5182. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  5183. case Type_Map: kind = Typeid_Map; break;
  5184. case Type_Struct: kind = Typeid_Struct; break;
  5185. case Type_Enum: kind = Typeid_Enum; break;
  5186. case Type_Union: kind = Typeid_Union; break;
  5187. case Type_Tuple: kind = Typeid_Tuple; break;
  5188. case Type_Proc: kind = Typeid_Procedure; break;
  5189. case Type_BitSet: kind = Typeid_Bit_Set; break;
  5190. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  5191. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  5192. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  5193. }
  5194. if (is_type_cstring(type)) {
  5195. special = 1;
  5196. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  5197. special = 1;
  5198. }
  5199. u64 data = 0;
  5200. if (build_context.word_size == 4) {
  5201. GB_ASSERT(id <= (1u<<24u));
  5202. data |= (id &~ (1u<<24)) << 0u; // index
  5203. data |= (kind &~ (1u<<5)) << 24u; // kind
  5204. data |= (named &~ (1u<<1)) << 29u; // kind
  5205. data |= (special &~ (1u<<1)) << 30u; // kind
  5206. data |= (reserved &~ (1u<<1)) << 31u; // kind
  5207. } else {
  5208. GB_ASSERT(build_context.word_size == 8);
  5209. GB_ASSERT(id <= (1ull<<56u));
  5210. data |= (id &~ (1ull<<56)) << 0ul; // index
  5211. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  5212. data |= (named &~ (1ull<<1)) << 61ull; // kind
  5213. data |= (special &~ (1ull<<1)) << 62ull; // kind
  5214. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  5215. }
  5216. lbValue res = {};
  5217. res.value = LLVMConstInt(lb_type(m, t_typeid), data, false);
  5218. res.type = t_typeid;
  5219. return res;
  5220. }
  5221. lbValue lb_type_info(lbModule *m, Type *type) {
  5222. type = default_type(type);
  5223. isize index = lb_type_info_index(m->info, type);
  5224. GB_ASSERT(index >= 0);
  5225. LLVMTypeRef it = lb_type(m, t_int);
  5226. LLVMValueRef indices[2] = {
  5227. LLVMConstInt(it, 0, false),
  5228. LLVMConstInt(it, index, true),
  5229. };
  5230. lbValue value = {};
  5231. value.value = LLVMConstGEP(lb_global_type_info_data_ptr(m).value, indices, gb_count_of(indices));
  5232. value.type = t_type_info_ptr;
  5233. return value;
  5234. }
  5235. LLVMValueRef lb_build_constant_array_values(lbModule *m, Type *type, Type *elem_type, isize count, LLVMValueRef *values, bool allow_local) {
  5236. bool is_local = allow_local && m->curr_procedure != nullptr;
  5237. bool is_const = true;
  5238. if (is_local) {
  5239. for (isize i = 0; i < count; i++) {
  5240. GB_ASSERT(values[i] != nullptr);
  5241. if (!LLVMIsConstant(values[i])) {
  5242. is_const = false;
  5243. break;
  5244. }
  5245. }
  5246. }
  5247. if (!is_const) {
  5248. lbProcedure *p = m->curr_procedure;
  5249. GB_ASSERT(p != nullptr);
  5250. lbAddr v = lb_add_local_generated(p, type, false);
  5251. lbValue ptr = lb_addr_get_ptr(p, v);
  5252. for (isize i = 0; i < count; i++) {
  5253. lbValue elem = lb_emit_array_epi(p, ptr, i);
  5254. LLVMBuildStore(p->builder, values[i], elem.value);
  5255. }
  5256. return lb_addr_load(p, v).value;
  5257. }
  5258. return llvm_const_array(lb_type(m, elem_type), values, cast(unsigned int)count);
  5259. }
  5260. lbValue lb_find_procedure_value_from_entity(lbModule *m, Entity *e) {
  5261. GB_ASSERT(is_type_proc(e->type));
  5262. e = strip_entity_wrapping(e);
  5263. GB_ASSERT(e != nullptr);
  5264. auto *found = map_get(&m->values, hash_entity(e));
  5265. if (found) {
  5266. return *found;
  5267. }
  5268. bool ignore_body = false;
  5269. if (USE_SEPARTE_MODULES) {
  5270. lbModule *other_module = lb_pkg_module(m->gen, e->pkg);
  5271. ignore_body = other_module != m;
  5272. }
  5273. lbProcedure *missing_proc = lb_create_procedure(m, e, ignore_body);
  5274. found = map_get(&m->values, hash_entity(e));
  5275. if (found) {
  5276. return *found;
  5277. }
  5278. GB_PANIC("Error in: %s, missing procedure %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  5279. return {};
  5280. }
  5281. void lb_set_entity_from_other_modules_linkage_correctly(lbModule *other_module, Entity *e, String const &name) {
  5282. if (other_module == nullptr) {
  5283. return;
  5284. }
  5285. char const *cname = alloc_cstring(temporary_allocator(), name);
  5286. LLVMValueRef other_global = nullptr;
  5287. if (e->kind == Entity_Variable) {
  5288. other_global = LLVMGetNamedGlobal(other_module->mod, cname);
  5289. } else if (e->kind == Entity_Procedure) {
  5290. other_global = LLVMGetNamedFunction(other_module->mod, cname);
  5291. }
  5292. if (other_global) {
  5293. LLVMSetLinkage(other_global, LLVMExternalLinkage);
  5294. }
  5295. }
  5296. lbValue lb_find_value_from_entity(lbModule *m, Entity *e) {
  5297. e = strip_entity_wrapping(e);
  5298. GB_ASSERT(e != nullptr);
  5299. GB_ASSERT(e->token.string != "_");
  5300. if (e->kind == Entity_Procedure) {
  5301. return lb_find_procedure_value_from_entity(m, e);
  5302. }
  5303. auto *found = map_get(&m->values, hash_entity(e));
  5304. if (found) {
  5305. return *found;
  5306. }
  5307. if (USE_SEPARTE_MODULES) {
  5308. lbModule *other_module = lb_pkg_module(m->gen, e->pkg);
  5309. // TODO(bill): correct this logic
  5310. bool is_external = other_module != m;
  5311. if (!is_external) {
  5312. if (e->code_gen_module != nullptr) {
  5313. other_module = e->code_gen_module;
  5314. } else {
  5315. other_module = nullptr;
  5316. }
  5317. is_external = other_module != m;
  5318. }
  5319. if (is_external) {
  5320. String name = lb_get_entity_name(other_module, e);
  5321. lbValue g = {};
  5322. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  5323. g.type = alloc_type_pointer(e->type);
  5324. lb_add_entity(m, e, g);
  5325. lb_add_member(m, name, g);
  5326. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  5327. lb_set_entity_from_other_modules_linkage_correctly(other_module, e, name);
  5328. // LLVMSetLinkage(other_g.value, LLVMExternalLinkage);
  5329. if (e->Variable.thread_local_model != "") {
  5330. LLVMSetThreadLocal(g.value, true);
  5331. String m = e->Variable.thread_local_model;
  5332. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  5333. if (m == "default") {
  5334. mode = LLVMGeneralDynamicTLSModel;
  5335. } else if (m == "localdynamic") {
  5336. mode = LLVMLocalDynamicTLSModel;
  5337. } else if (m == "initialexec") {
  5338. mode = LLVMInitialExecTLSModel;
  5339. } else if (m == "localexec") {
  5340. mode = LLVMLocalExecTLSModel;
  5341. } else {
  5342. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  5343. }
  5344. LLVMSetThreadLocalMode(g.value, mode);
  5345. }
  5346. return g;
  5347. }
  5348. }
  5349. GB_PANIC("\n\tError in: %s, missing value '%.*s'\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  5350. return {};
  5351. }
  5352. LLVMValueRef lb_big_int_to_llvm(lbModule *m, Type *original_type, BigInt const *a) {
  5353. if (big_int_is_zero(a)) {
  5354. return LLVMConstNull(lb_type(m, original_type));
  5355. }
  5356. size_t sz = cast(size_t)type_size_of(original_type);
  5357. u64 rop64[4] = {}; // 2 u64 is the maximum we will ever need, so doubling it will be fine :P
  5358. u8 *rop = cast(u8 *)rop64;
  5359. size_t max_count = 0;
  5360. size_t written = 0;
  5361. size_t size = 1;
  5362. size_t nails = 0;
  5363. mp_endian endian = MP_LITTLE_ENDIAN;
  5364. max_count = mp_pack_count(a, nails, size);
  5365. GB_ASSERT_MSG(sz >= max_count, "max_count: %tu, sz: %tu, written: %tu", max_count, sz, written);
  5366. GB_ASSERT(gb_size_of(rop64) >= sz);
  5367. mp_err err = mp_pack(rop, sz, &written,
  5368. MP_LSB_FIRST,
  5369. size, endian, nails,
  5370. a);
  5371. GB_ASSERT(err == MP_OKAY);
  5372. if (!is_type_endian_little(original_type)) {
  5373. for (size_t i = 0; i < sz/2; i++) {
  5374. u8 tmp = rop[i];
  5375. rop[i] = rop[sz-1-i];
  5376. rop[sz-1-i] = tmp;
  5377. }
  5378. }
  5379. LLVMValueRef value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), cast(unsigned)(sz+7/8), cast(u64 *)rop);
  5380. if (big_int_is_neg(a)) {
  5381. value = LLVMConstNeg(value);
  5382. }
  5383. return value;
  5384. }
  5385. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  5386. LLVMContextRef ctx = m->ctx;
  5387. type = default_type(type);
  5388. Type *original_type = type;
  5389. lbValue res = {};
  5390. res.type = original_type;
  5391. type = core_type(type);
  5392. value = convert_exact_value_for_type(value, type);
  5393. if (value.kind == ExactValue_Typeid) {
  5394. return lb_typeid(m, value.value_typeid);
  5395. }
  5396. if (value.kind == ExactValue_Invalid) {
  5397. return lb_const_nil(m, type);
  5398. }
  5399. if (value.kind == ExactValue_Procedure) {
  5400. Ast *expr = unparen_expr(value.value_procedure);
  5401. if (expr->kind == Ast_ProcLit) {
  5402. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  5403. }
  5404. Entity *e = entity_from_expr(expr);
  5405. return lb_find_procedure_value_from_entity(m, e);
  5406. }
  5407. bool is_local = allow_local && m->curr_procedure != nullptr;
  5408. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  5409. if (is_type_slice(type)) {
  5410. if (value.kind == ExactValue_String) {
  5411. GB_ASSERT(is_type_u8_slice(type));
  5412. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  5413. return res;
  5414. } else {
  5415. ast_node(cl, CompoundLit, value.value_compound);
  5416. isize count = cl->elems.count;
  5417. if (count == 0) {
  5418. return lb_const_nil(m, type);
  5419. }
  5420. count = gb_max(cast(isize)cl->max_count, count);
  5421. Type *elem = base_type(type)->Slice.elem;
  5422. Type *t = alloc_type_array(elem, count);
  5423. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  5424. LLVMValueRef array_data = nullptr;
  5425. if (is_local) {
  5426. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  5427. // its backing data on the stack
  5428. lbProcedure *p = m->curr_procedure;
  5429. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  5430. LLVMTypeRef llvm_type = lb_type(m, t);
  5431. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  5432. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  5433. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  5434. LLVMBuildStore(p->builder, backing_array.value, array_data);
  5435. {
  5436. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  5437. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  5438. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  5439. lbAddr slice = lb_add_local_generated(p, type, false);
  5440. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  5441. return lb_addr_load(p, slice);
  5442. }
  5443. } else {
  5444. isize max_len = 7+8+1;
  5445. char *str = gb_alloc_array(permanent_allocator(), char, max_len);
  5446. u32 id = cast(u32)gb_atomic32_fetch_add(&m->gen->global_array_index, 1);
  5447. isize len = gb_snprintf(str, max_len, "csba$%x", id);
  5448. String name = make_string(cast(u8 *)str, len-1);
  5449. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  5450. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  5451. LLVMSetInitializer(array_data, backing_array.value);
  5452. lbValue g = {};
  5453. g.value = array_data;
  5454. g.type = t;
  5455. lb_add_entity(m, e, g);
  5456. lb_add_member(m, name, g);
  5457. {
  5458. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  5459. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  5460. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  5461. LLVMValueRef values[2] = {ptr, len};
  5462. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  5463. return res;
  5464. }
  5465. }
  5466. }
  5467. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  5468. if (is_type_rune_array(type) && value.kind == ExactValue_String) {
  5469. i64 count = type->Array.count;
  5470. Type *elem = type->Array.elem;
  5471. LLVMTypeRef et = lb_type(m, elem);
  5472. Rune rune;
  5473. isize offset = 0;
  5474. isize width = 1;
  5475. String s = value.value_string;
  5476. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, cast(isize)count);
  5477. for (i64 i = 0; i < count && offset < s.len; i++) {
  5478. width = utf8_decode(s.text+offset, s.len-offset, &rune);
  5479. offset += width;
  5480. elems[i] = LLVMConstInt(et, rune, true);
  5481. }
  5482. GB_ASSERT(offset == s.len);
  5483. res.value = llvm_const_array(et, elems, cast(unsigned)count);
  5484. return res;
  5485. }
  5486. GB_PANIC("This should not have happened!\n");
  5487. LLVMValueRef data = LLVMConstStringInContext(ctx,
  5488. cast(char const *)value.value_string.text,
  5489. cast(unsigned)value.value_string.len,
  5490. false /*DontNullTerminate*/);
  5491. res.value = data;
  5492. return res;
  5493. } else if (is_type_u8_array(type) && value.kind == ExactValue_String) {
  5494. GB_ASSERT(type->Array.count == value.value_string.len);
  5495. LLVMValueRef data = LLVMConstStringInContext(ctx,
  5496. cast(char const *)value.value_string.text,
  5497. cast(unsigned)value.value_string.len,
  5498. true /*DontNullTerminate*/);
  5499. res.value = data;
  5500. return res;
  5501. } else if (is_type_array(type) &&
  5502. value.kind != ExactValue_Invalid &&
  5503. value.kind != ExactValue_String &&
  5504. value.kind != ExactValue_Compound) {
  5505. i64 count = type->Array.count;
  5506. Type *elem = type->Array.elem;
  5507. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  5508. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, cast(isize)count);
  5509. for (i64 i = 0; i < count; i++) {
  5510. elems[i] = single_elem.value;
  5511. }
  5512. res.value = llvm_const_array(lb_type(m, elem), elems, cast(unsigned)count);
  5513. return res;
  5514. }
  5515. switch (value.kind) {
  5516. case ExactValue_Invalid:
  5517. res.value = LLVMConstNull(lb_type(m, original_type));
  5518. return res;
  5519. case ExactValue_Bool:
  5520. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  5521. return res;
  5522. case ExactValue_String:
  5523. {
  5524. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  5525. lbValue res = {};
  5526. res.type = default_type(original_type);
  5527. if (is_type_cstring(res.type)) {
  5528. res.value = ptr;
  5529. } else {
  5530. if (value.value_string.len == 0) {
  5531. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  5532. }
  5533. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  5534. LLVMValueRef values[2] = {ptr, str_len};
  5535. GB_ASSERT(is_type_string(original_type));
  5536. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  5537. }
  5538. return res;
  5539. }
  5540. case ExactValue_Integer:
  5541. if (is_type_pointer(type)) {
  5542. LLVMTypeRef t = lb_type(m, original_type);
  5543. LLVMValueRef i = lb_big_int_to_llvm(m, t_uintptr, &value.value_integer);
  5544. res.value = LLVMConstIntToPtr(i, t);
  5545. } else {
  5546. res.value = lb_big_int_to_llvm(m, original_type, &value.value_integer);
  5547. }
  5548. return res;
  5549. case ExactValue_Float:
  5550. if (is_type_different_to_arch_endianness(type)) {
  5551. u64 u = bit_cast<u64>(value.value_float);
  5552. u = gb_endian_swap64(u);
  5553. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  5554. } else {
  5555. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  5556. }
  5557. return res;
  5558. case ExactValue_Complex:
  5559. {
  5560. LLVMValueRef values[2] = {};
  5561. switch (8*type_size_of(type)) {
  5562. case 32:
  5563. values[0] = lb_const_f16(m, cast(f32)value.value_complex->real);
  5564. values[1] = lb_const_f16(m, cast(f32)value.value_complex->imag);
  5565. break;
  5566. case 64:
  5567. values[0] = lb_const_f32(m, cast(f32)value.value_complex->real);
  5568. values[1] = lb_const_f32(m, cast(f32)value.value_complex->imag);
  5569. break;
  5570. case 128:
  5571. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->real);
  5572. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->imag);
  5573. break;
  5574. }
  5575. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  5576. return res;
  5577. }
  5578. break;
  5579. case ExactValue_Quaternion:
  5580. {
  5581. LLVMValueRef values[4] = {};
  5582. switch (8*type_size_of(type)) {
  5583. case 64:
  5584. // @QuaternionLayout
  5585. values[3] = lb_const_f16(m, cast(f32)value.value_quaternion->real);
  5586. values[0] = lb_const_f16(m, cast(f32)value.value_quaternion->imag);
  5587. values[1] = lb_const_f16(m, cast(f32)value.value_quaternion->jmag);
  5588. values[2] = lb_const_f16(m, cast(f32)value.value_quaternion->kmag);
  5589. break;
  5590. case 128:
  5591. // @QuaternionLayout
  5592. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion->real);
  5593. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion->imag);
  5594. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion->jmag);
  5595. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion->kmag);
  5596. break;
  5597. case 256:
  5598. // @QuaternionLayout
  5599. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->real);
  5600. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->imag);
  5601. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->jmag);
  5602. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->kmag);
  5603. break;
  5604. }
  5605. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 4);
  5606. return res;
  5607. }
  5608. break;
  5609. case ExactValue_Pointer:
  5610. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  5611. return res;
  5612. case ExactValue_Compound:
  5613. if (is_type_slice(type)) {
  5614. return lb_const_value(m, type, value, allow_local);
  5615. } else if (is_type_array(type)) {
  5616. ast_node(cl, CompoundLit, value.value_compound);
  5617. Type *elem_type = type->Array.elem;
  5618. isize elem_count = cl->elems.count;
  5619. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  5620. return lb_const_nil(m, original_type);
  5621. }
  5622. if (cl->elems[0]->kind == Ast_FieldValue) {
  5623. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  5624. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, cast(isize)type->Array.count);
  5625. isize value_index = 0;
  5626. for (i64 i = 0; i < type->Array.count; i++) {
  5627. bool found = false;
  5628. for (isize j = 0; j < elem_count; j++) {
  5629. Ast *elem = cl->elems[j];
  5630. ast_node(fv, FieldValue, elem);
  5631. if (is_ast_range(fv->field)) {
  5632. ast_node(ie, BinaryExpr, fv->field);
  5633. TypeAndValue lo_tav = ie->left->tav;
  5634. TypeAndValue hi_tav = ie->right->tav;
  5635. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  5636. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  5637. TokenKind op = ie->op.kind;
  5638. i64 lo = exact_value_to_i64(lo_tav.value);
  5639. i64 hi = exact_value_to_i64(hi_tav.value);
  5640. if (op != Token_RangeHalf) {
  5641. hi += 1;
  5642. }
  5643. if (lo == i) {
  5644. TypeAndValue tav = fv->value->tav;
  5645. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5646. for (i64 k = lo; k < hi; k++) {
  5647. values[value_index++] = val;
  5648. }
  5649. found = true;
  5650. i += (hi-lo-1);
  5651. break;
  5652. }
  5653. } else {
  5654. TypeAndValue index_tav = fv->field->tav;
  5655. GB_ASSERT(index_tav.mode == Addressing_Constant);
  5656. i64 index = exact_value_to_i64(index_tav.value);
  5657. if (index == i) {
  5658. TypeAndValue tav = fv->value->tav;
  5659. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5660. values[value_index++] = val;
  5661. found = true;
  5662. break;
  5663. }
  5664. }
  5665. }
  5666. if (!found) {
  5667. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  5668. }
  5669. }
  5670. res.value = lb_build_constant_array_values(m, type, elem_type, cast(isize)type->Array.count, values, allow_local);
  5671. return res;
  5672. } else {
  5673. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  5674. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, cast(isize)type->Array.count);
  5675. for (isize i = 0; i < elem_count; i++) {
  5676. TypeAndValue tav = cl->elems[i]->tav;
  5677. GB_ASSERT(tav.mode != Addressing_Invalid);
  5678. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5679. }
  5680. for (isize i = elem_count; i < type->Array.count; i++) {
  5681. values[i] = LLVMConstNull(lb_type(m, elem_type));
  5682. }
  5683. res.value = lb_build_constant_array_values(m, type, elem_type, cast(isize)type->Array.count, values, allow_local);
  5684. return res;
  5685. }
  5686. } else if (is_type_enumerated_array(type)) {
  5687. ast_node(cl, CompoundLit, value.value_compound);
  5688. Type *elem_type = type->EnumeratedArray.elem;
  5689. isize elem_count = cl->elems.count;
  5690. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  5691. return lb_const_nil(m, original_type);
  5692. }
  5693. if (cl->elems[0]->kind == Ast_FieldValue) {
  5694. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  5695. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, cast(isize)type->EnumeratedArray.count);
  5696. isize value_index = 0;
  5697. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  5698. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  5699. for (i64 i = total_lo; i <= total_hi; i++) {
  5700. bool found = false;
  5701. for (isize j = 0; j < elem_count; j++) {
  5702. Ast *elem = cl->elems[j];
  5703. ast_node(fv, FieldValue, elem);
  5704. if (is_ast_range(fv->field)) {
  5705. ast_node(ie, BinaryExpr, fv->field);
  5706. TypeAndValue lo_tav = ie->left->tav;
  5707. TypeAndValue hi_tav = ie->right->tav;
  5708. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  5709. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  5710. TokenKind op = ie->op.kind;
  5711. i64 lo = exact_value_to_i64(lo_tav.value);
  5712. i64 hi = exact_value_to_i64(hi_tav.value);
  5713. if (op != Token_RangeHalf) {
  5714. hi += 1;
  5715. }
  5716. if (lo == i) {
  5717. TypeAndValue tav = fv->value->tav;
  5718. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5719. for (i64 k = lo; k < hi; k++) {
  5720. values[value_index++] = val;
  5721. }
  5722. found = true;
  5723. i += (hi-lo-1);
  5724. break;
  5725. }
  5726. } else {
  5727. TypeAndValue index_tav = fv->field->tav;
  5728. GB_ASSERT(index_tav.mode == Addressing_Constant);
  5729. i64 index = exact_value_to_i64(index_tav.value);
  5730. if (index == i) {
  5731. TypeAndValue tav = fv->value->tav;
  5732. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5733. values[value_index++] = val;
  5734. found = true;
  5735. break;
  5736. }
  5737. }
  5738. }
  5739. if (!found) {
  5740. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  5741. }
  5742. }
  5743. res.value = lb_build_constant_array_values(m, type, elem_type, cast(isize)type->EnumeratedArray.count, values, allow_local);
  5744. return res;
  5745. } else {
  5746. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  5747. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, cast(isize)type->EnumeratedArray.count);
  5748. for (isize i = 0; i < elem_count; i++) {
  5749. TypeAndValue tav = cl->elems[i]->tav;
  5750. GB_ASSERT(tav.mode != Addressing_Invalid);
  5751. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5752. }
  5753. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  5754. values[i] = LLVMConstNull(lb_type(m, elem_type));
  5755. }
  5756. res.value = lb_build_constant_array_values(m, type, elem_type, cast(isize)type->EnumeratedArray.count, values, allow_local);
  5757. return res;
  5758. }
  5759. } else if (is_type_simd_vector(type)) {
  5760. ast_node(cl, CompoundLit, value.value_compound);
  5761. Type *elem_type = type->SimdVector.elem;
  5762. isize elem_count = cl->elems.count;
  5763. if (elem_count == 0) {
  5764. return lb_const_nil(m, original_type);
  5765. }
  5766. GB_ASSERT(elem_type_can_be_constant(elem_type));
  5767. isize total_elem_count = cast(isize)type->SimdVector.count;
  5768. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, total_elem_count);
  5769. for (isize i = 0; i < elem_count; i++) {
  5770. TypeAndValue tav = cl->elems[i]->tav;
  5771. GB_ASSERT(tav.mode != Addressing_Invalid);
  5772. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5773. }
  5774. LLVMTypeRef et = lb_type(m, elem_type);
  5775. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  5776. values[i] = LLVMConstNull(et);
  5777. }
  5778. for (isize i = 0; i < total_elem_count; i++) {
  5779. values[i] = llvm_const_cast(values[i], et);
  5780. }
  5781. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  5782. return res;
  5783. } else if (is_type_struct(type)) {
  5784. ast_node(cl, CompoundLit, value.value_compound);
  5785. if (cl->elems.count == 0) {
  5786. return lb_const_nil(m, original_type);
  5787. }
  5788. if (is_type_raw_union(type)) {
  5789. return lb_const_nil(m, original_type);
  5790. }
  5791. isize offset = 0;
  5792. if (type->Struct.custom_align > 0) {
  5793. offset = 1;
  5794. }
  5795. isize value_count = type->Struct.fields.count + offset;
  5796. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  5797. bool *visited = gb_alloc_array(temporary_allocator(), bool, value_count);
  5798. if (cl->elems.count > 0) {
  5799. if (cl->elems[0]->kind == Ast_FieldValue) {
  5800. isize elem_count = cl->elems.count;
  5801. for (isize i = 0; i < elem_count; i++) {
  5802. ast_node(fv, FieldValue, cl->elems[i]);
  5803. String name = fv->field->Ident.token.string;
  5804. TypeAndValue tav = fv->value->tav;
  5805. GB_ASSERT(tav.mode != Addressing_Invalid);
  5806. Selection sel = lookup_field(type, name, false);
  5807. Entity *f = type->Struct.fields[sel.index[0]];
  5808. if (elem_type_can_be_constant(f->type)) {
  5809. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  5810. visited[offset+f->Variable.field_index] = true;
  5811. }
  5812. }
  5813. } else {
  5814. for_array(i, cl->elems) {
  5815. Entity *f = type->Struct.fields[i];
  5816. TypeAndValue tav = cl->elems[i]->tav;
  5817. ExactValue val = {};
  5818. if (tav.mode != Addressing_Invalid) {
  5819. val = tav.value;
  5820. }
  5821. if (elem_type_can_be_constant(f->type)) {
  5822. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  5823. visited[offset+f->Variable.field_index] = true;
  5824. }
  5825. }
  5826. }
  5827. }
  5828. for (isize i = 0; i < type->Struct.fields.count; i++) {
  5829. if (!visited[offset+i]) {
  5830. GB_ASSERT(values[offset+i] == nullptr);
  5831. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  5832. }
  5833. }
  5834. if (type->Struct.custom_align > 0) {
  5835. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  5836. }
  5837. bool is_constant = true;
  5838. for (isize i = 0; i < value_count; i++) {
  5839. LLVMValueRef val = values[i];
  5840. if (!LLVMIsConstant(val)) {
  5841. GB_ASSERT(is_local);
  5842. GB_ASSERT(LLVMGetInstructionOpcode(val) == LLVMLoad);
  5843. is_constant = false;
  5844. }
  5845. }
  5846. if (is_constant) {
  5847. res.value = llvm_const_named_struct(lb_type(m, original_type), values, cast(unsigned)value_count);
  5848. return res;
  5849. } else {
  5850. // TODO(bill): THIS IS HACK BUT IT WORKS FOR WHAT I NEED
  5851. LLVMValueRef *old_values = values;
  5852. LLVMValueRef *new_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  5853. for (isize i = 0; i < value_count; i++) {
  5854. LLVMValueRef old_value = old_values[i];
  5855. if (LLVMIsConstant(old_value)) {
  5856. new_values[i] = old_value;
  5857. } else {
  5858. new_values[i] = LLVMConstNull(LLVMTypeOf(old_value));
  5859. }
  5860. }
  5861. LLVMValueRef constant_value = llvm_const_named_struct(lb_type(m, original_type), new_values, cast(unsigned)value_count);
  5862. GB_ASSERT(is_local);
  5863. lbProcedure *p = m->curr_procedure;
  5864. lbAddr v = lb_add_local_generated(p, res.type, true);
  5865. LLVMBuildStore(p->builder, constant_value, v.addr.value);
  5866. for (isize i = 0; i < value_count; i++) {
  5867. LLVMValueRef val = old_values[i];
  5868. if (!LLVMIsConstant(val)) {
  5869. LLVMValueRef dst = LLVMBuildStructGEP(p->builder, v.addr.value, cast(unsigned)i, "");
  5870. LLVMBuildStore(p->builder, val, dst);
  5871. }
  5872. }
  5873. return lb_addr_load(p, v);
  5874. }
  5875. } else if (is_type_bit_set(type)) {
  5876. ast_node(cl, CompoundLit, value.value_compound);
  5877. if (cl->elems.count == 0) {
  5878. return lb_const_nil(m, original_type);
  5879. }
  5880. i64 sz = type_size_of(type);
  5881. if (sz == 0) {
  5882. return lb_const_nil(m, original_type);
  5883. }
  5884. u64 bits = 0;
  5885. for_array(i, cl->elems) {
  5886. Ast *e = cl->elems[i];
  5887. GB_ASSERT(e->kind != Ast_FieldValue);
  5888. TypeAndValue tav = e->tav;
  5889. if (tav.mode != Addressing_Constant) {
  5890. continue;
  5891. }
  5892. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  5893. i64 v = big_int_to_i64(&tav.value.value_integer);
  5894. i64 lower = type->BitSet.lower;
  5895. bits |= 1ull<<cast(u64)(v-lower);
  5896. }
  5897. if (is_type_different_to_arch_endianness(type)) {
  5898. i64 size = type_size_of(type);
  5899. switch (size) {
  5900. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  5901. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  5902. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  5903. }
  5904. }
  5905. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  5906. return res;
  5907. } else {
  5908. return lb_const_nil(m, original_type);
  5909. }
  5910. break;
  5911. case ExactValue_Procedure:
  5912. {
  5913. Ast *expr = value.value_procedure;
  5914. GB_ASSERT(expr != nullptr);
  5915. if (expr->kind == Ast_ProcLit) {
  5916. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  5917. }
  5918. }
  5919. break;
  5920. case ExactValue_Typeid:
  5921. return lb_typeid(m, value.value_typeid);
  5922. }
  5923. return lb_const_nil(m, original_type);
  5924. }
  5925. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  5926. lbModule *m = p->module;
  5927. LLVMValueRef fields[4] = {};
  5928. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id)).value;
  5929. fields[1]/*line*/ = lb_const_int(m, t_i32, pos.line).value;
  5930. fields[2]/*column*/ = lb_const_int(m, t_i32, pos.column).value;
  5931. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  5932. lbValue res = {};
  5933. res.value = llvm_const_named_struct(lb_type(m, t_source_code_location), fields, gb_count_of(fields));
  5934. res.type = t_source_code_location;
  5935. return res;
  5936. }
  5937. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  5938. String proc_name = {};
  5939. if (p->entity) {
  5940. proc_name = p->entity->token.string;
  5941. }
  5942. TokenPos pos = {};
  5943. if (node) {
  5944. pos = ast_token(node).pos;
  5945. }
  5946. return lb_emit_source_code_location(p, proc_name, pos);
  5947. }
  5948. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  5949. switch (op) {
  5950. case Token_Add:
  5951. return x;
  5952. case Token_Not: // Boolean not
  5953. case Token_Xor: // Bitwise not
  5954. case Token_Sub: // Number negation
  5955. break;
  5956. case Token_Pointer:
  5957. GB_PANIC("This should be handled elsewhere");
  5958. break;
  5959. }
  5960. if (is_type_array_like(x.type)) {
  5961. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  5962. Type *tl = base_type(x.type);
  5963. lbValue val = lb_address_from_load_or_generate_local(p, x);
  5964. GB_ASSERT(is_type_array_like(type));
  5965. Type *elem_type = base_array_type(type);
  5966. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5967. lbAddr res_addr = lb_add_local(p, type, nullptr, false, 0, true);
  5968. lbValue res = lb_addr_get_ptr(p, res_addr);
  5969. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5970. i32 count = cast(i32)get_array_type_count(tl);
  5971. LLVMTypeRef vector_type = nullptr;
  5972. if (op != Token_Not && lb_try_vector_cast(p->module, val, &vector_type)) {
  5973. LLVMValueRef vp = LLVMBuildPointerCast(p->builder, val.value, LLVMPointerType(vector_type, 0), "");
  5974. LLVMValueRef v = LLVMBuildLoad2(p->builder, vector_type, vp, "");
  5975. LLVMValueRef opv = nullptr;
  5976. switch (op) {
  5977. case Token_Xor:
  5978. opv = LLVMBuildNot(p->builder, v, "");
  5979. break;
  5980. case Token_Sub:
  5981. if (is_type_float(elem_type)) {
  5982. opv = LLVMBuildFNeg(p->builder, v, "");
  5983. } else {
  5984. opv = LLVMBuildNeg(p->builder, v, "");
  5985. }
  5986. break;
  5987. }
  5988. if (opv != nullptr) {
  5989. LLVMSetAlignment(res.value, cast(unsigned)lb_alignof(vector_type));
  5990. LLVMValueRef res_ptr = LLVMBuildPointerCast(p->builder, res.value, LLVMPointerType(vector_type, 0), "");
  5991. LLVMBuildStore(p->builder, opv, res_ptr);
  5992. return lb_emit_conv(p, lb_emit_load(p, res), type);
  5993. }
  5994. }
  5995. if (inline_array_arith) {
  5996. // inline
  5997. for (i32 i = 0; i < count; i++) {
  5998. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  5999. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  6000. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  6001. }
  6002. } else {
  6003. auto loop_data = lb_loop_start(p, count, t_i32);
  6004. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  6005. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  6006. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  6007. lb_loop_end(p, loop_data);
  6008. }
  6009. return lb_emit_load(p, res);
  6010. }
  6011. if (op == Token_Xor) {
  6012. lbValue cmp = {};
  6013. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  6014. cmp.type = x.type;
  6015. return lb_emit_conv(p, cmp, type);
  6016. }
  6017. if (op == Token_Not) {
  6018. lbValue cmp = {};
  6019. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  6020. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  6021. cmp.type = t_llvm_bool;
  6022. return lb_emit_conv(p, cmp, type);
  6023. }
  6024. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  6025. Type *platform_type = integer_endian_type_to_platform_type(type);
  6026. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  6027. lbValue res = {};
  6028. res.value = LLVMBuildNeg(p->builder, v.value, "");
  6029. res.type = platform_type;
  6030. return lb_emit_byte_swap(p, res, type);
  6031. }
  6032. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  6033. Type *platform_type = integer_endian_type_to_platform_type(type);
  6034. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  6035. lbValue res = {};
  6036. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  6037. res.type = platform_type;
  6038. return lb_emit_byte_swap(p, res, type);
  6039. }
  6040. lbValue res = {};
  6041. switch (op) {
  6042. case Token_Not: // Boolean not
  6043. case Token_Xor: // Bitwise not
  6044. res.value = LLVMBuildNot(p->builder, x.value, "");
  6045. res.type = x.type;
  6046. return res;
  6047. case Token_Sub: // Number negation
  6048. if (is_type_integer(x.type)) {
  6049. res.value = LLVMBuildNeg(p->builder, x.value, "");
  6050. } else if (is_type_float(x.type)) {
  6051. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  6052. } else if (is_type_complex(x.type)) {
  6053. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  6054. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  6055. lbAddr addr = lb_add_local_generated(p, x.type, false);
  6056. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  6057. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  6058. return lb_addr_load(p, addr);
  6059. } else if (is_type_quaternion(x.type)) {
  6060. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  6061. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  6062. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  6063. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  6064. lbAddr addr = lb_add_local_generated(p, x.type, false);
  6065. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  6066. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  6067. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  6068. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  6069. return lb_addr_load(p, addr);
  6070. } else {
  6071. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  6072. }
  6073. res.type = x.type;
  6074. return res;
  6075. }
  6076. return res;
  6077. }
  6078. bool lb_try_direct_vector_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type, lbValue *res_) {
  6079. GB_ASSERT(is_type_array_like(type));
  6080. Type *elem_type = base_array_type(type);
  6081. // NOTE(bill): Shift operations cannot be easily dealt with due to Odin's semantics
  6082. if (op == Token_Shl || op == Token_Shr) {
  6083. return false;
  6084. }
  6085. if (!LLVMIsALoadInst(lhs.value) || !LLVMIsALoadInst(rhs.value)) {
  6086. return false;
  6087. }
  6088. lbValue lhs_ptr = {};
  6089. lbValue rhs_ptr = {};
  6090. lhs_ptr.value = LLVMGetOperand(lhs.value, 0);
  6091. lhs_ptr.type = alloc_type_pointer(lhs.type);
  6092. rhs_ptr.value = LLVMGetOperand(rhs.value, 0);
  6093. rhs_ptr.type = alloc_type_pointer(rhs.type);
  6094. LLVMTypeRef vector_type0 = nullptr;
  6095. LLVMTypeRef vector_type1 = nullptr;
  6096. if (lb_try_vector_cast(p->module, lhs_ptr, &vector_type0) &&
  6097. lb_try_vector_cast(p->module, rhs_ptr, &vector_type1)) {
  6098. GB_ASSERT(vector_type0 == vector_type1);
  6099. LLVMTypeRef vector_type = vector_type0;
  6100. LLVMValueRef lhs_vp = LLVMBuildPointerCast(p->builder, lhs_ptr.value, LLVMPointerType(vector_type, 0), "");
  6101. LLVMValueRef rhs_vp = LLVMBuildPointerCast(p->builder, rhs_ptr.value, LLVMPointerType(vector_type, 0), "");
  6102. LLVMValueRef x = LLVMBuildLoad2(p->builder, vector_type, lhs_vp, "");
  6103. LLVMValueRef y = LLVMBuildLoad2(p->builder, vector_type, rhs_vp, "");
  6104. LLVMValueRef z = nullptr;
  6105. Type *integral_type = base_type(elem_type);
  6106. if (is_type_simd_vector(integral_type)) {
  6107. integral_type = core_array_type(integral_type);
  6108. }
  6109. if (is_type_bit_set(integral_type)) {
  6110. switch (op) {
  6111. case Token_Add: op = Token_Or; break;
  6112. case Token_Sub: op = Token_AndNot; break;
  6113. }
  6114. }
  6115. if (is_type_float(integral_type)) {
  6116. switch (op) {
  6117. case Token_Add:
  6118. z = LLVMBuildFAdd(p->builder, x, y, "");
  6119. break;
  6120. case Token_Sub:
  6121. z = LLVMBuildFSub(p->builder, x, y, "");
  6122. break;
  6123. case Token_Mul:
  6124. z = LLVMBuildFMul(p->builder, x, y, "");
  6125. break;
  6126. case Token_Quo:
  6127. z = LLVMBuildFDiv(p->builder, x, y, "");
  6128. break;
  6129. case Token_Mod:
  6130. z = LLVMBuildFRem(p->builder, x, y, "");
  6131. break;
  6132. default:
  6133. GB_PANIC("Unsupported vector operation");
  6134. break;
  6135. }
  6136. } else {
  6137. switch (op) {
  6138. case Token_Add:
  6139. z = LLVMBuildAdd(p->builder, x, y, "");
  6140. break;
  6141. case Token_Sub:
  6142. z = LLVMBuildSub(p->builder, x, y, "");
  6143. break;
  6144. case Token_Mul:
  6145. z = LLVMBuildMul(p->builder, x, y, "");
  6146. break;
  6147. case Token_Quo:
  6148. if (is_type_unsigned(integral_type)) {
  6149. z = LLVMBuildUDiv(p->builder, x, y, "");
  6150. } else {
  6151. z = LLVMBuildSDiv(p->builder, x, y, "");
  6152. }
  6153. break;
  6154. case Token_Mod:
  6155. if (is_type_unsigned(integral_type)) {
  6156. z = LLVMBuildURem(p->builder, x, y, "");
  6157. } else {
  6158. z = LLVMBuildSRem(p->builder, x, y, "");
  6159. }
  6160. break;
  6161. case Token_ModMod:
  6162. if (is_type_unsigned(integral_type)) {
  6163. z = LLVMBuildURem(p->builder, x, y, "");
  6164. } else {
  6165. LLVMValueRef a = LLVMBuildSRem(p->builder, x, y, "");
  6166. LLVMValueRef b = LLVMBuildAdd(p->builder, a, y, "");
  6167. z = LLVMBuildSRem(p->builder, b, y, "");
  6168. }
  6169. break;
  6170. case Token_And:
  6171. z = LLVMBuildAnd(p->builder, x, y, "");
  6172. break;
  6173. case Token_AndNot:
  6174. z = LLVMBuildAnd(p->builder, x, LLVMBuildNot(p->builder, y, ""), "");
  6175. break;
  6176. case Token_Or:
  6177. z = LLVMBuildOr(p->builder, x, y, "");
  6178. break;
  6179. case Token_Xor:
  6180. z = LLVMBuildXor(p->builder, x, y, "");
  6181. break;
  6182. default:
  6183. GB_PANIC("Unsupported vector operation");
  6184. break;
  6185. }
  6186. }
  6187. if (z != nullptr) {
  6188. lbAddr res = lb_add_local_generated_temp(p, type, lb_alignof(vector_type));
  6189. LLVMValueRef vp = LLVMBuildPointerCast(p->builder, res.addr.value, LLVMPointerType(vector_type, 0), "");
  6190. LLVMBuildStore(p->builder, z, vp);
  6191. lbValue v = lb_addr_load(p, res);
  6192. if (res_) *res_ = v;
  6193. return true;
  6194. }
  6195. }
  6196. return false;
  6197. }
  6198. lbValue lb_emit_arith_array(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  6199. GB_ASSERT(is_type_array_like(lhs.type) || is_type_array_like(rhs.type));
  6200. lhs = lb_emit_conv(p, lhs, type);
  6201. rhs = lb_emit_conv(p, rhs, type);
  6202. GB_ASSERT(is_type_array_like(type));
  6203. Type *elem_type = base_array_type(type);
  6204. i64 count = get_array_type_count(type);
  6205. unsigned n = cast(unsigned)count;
  6206. // NOTE(bill, 2021-06-12): Try to do a direct operation as a vector, if possible
  6207. lbValue direct_vector_res = {};
  6208. if (lb_try_direct_vector_arith(p, op, lhs, rhs, type, &direct_vector_res)) {
  6209. return direct_vector_res;
  6210. }
  6211. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  6212. if (inline_array_arith) {
  6213. auto dst_ptrs = slice_make<lbValue>(temporary_allocator(), n);
  6214. auto a_loads = slice_make<lbValue>(temporary_allocator(), n);
  6215. auto b_loads = slice_make<lbValue>(temporary_allocator(), n);
  6216. auto c_ops = slice_make<lbValue>(temporary_allocator(), n);
  6217. for (unsigned i = 0; i < n; i++) {
  6218. a_loads[i].value = LLVMBuildExtractValue(p->builder, lhs.value, i, "");
  6219. a_loads[i].type = elem_type;
  6220. }
  6221. for (unsigned i = 0; i < n; i++) {
  6222. b_loads[i].value = LLVMBuildExtractValue(p->builder, rhs.value, i, "");
  6223. b_loads[i].type = elem_type;
  6224. }
  6225. for (unsigned i = 0; i < n; i++) {
  6226. c_ops[i] = lb_emit_arith(p, op, a_loads[i], b_loads[i], elem_type);
  6227. }
  6228. lbAddr res = lb_add_local_generated(p, type, false);
  6229. for (unsigned i = 0; i < n; i++) {
  6230. dst_ptrs[i] = lb_emit_array_epi(p, res.addr, i);
  6231. }
  6232. for (unsigned i = 0; i < n; i++) {
  6233. lb_emit_store(p, dst_ptrs[i], c_ops[i]);
  6234. }
  6235. return lb_addr_load(p, res);
  6236. } else {
  6237. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  6238. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  6239. lbAddr res = lb_add_local_generated(p, type, false);
  6240. auto loop_data = lb_loop_start(p, cast(isize)count, t_i32);
  6241. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  6242. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  6243. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  6244. lbValue a = lb_emit_load(p, a_ptr);
  6245. lbValue b = lb_emit_load(p, b_ptr);
  6246. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  6247. lb_emit_store(p, dst_ptr, c);
  6248. lb_loop_end(p, loop_data);
  6249. return lb_addr_load(p, res);
  6250. }
  6251. }
  6252. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  6253. lbModule *m = p->module;
  6254. if (is_type_array_like(lhs.type) || is_type_array_like(rhs.type)) {
  6255. return lb_emit_arith_array(p, op, lhs, rhs, type);
  6256. } else if (is_type_complex(type)) {
  6257. lhs = lb_emit_conv(p, lhs, type);
  6258. rhs = lb_emit_conv(p, rhs, type);
  6259. Type *ft = base_complex_elem_type(type);
  6260. if (op == Token_Quo) {
  6261. auto args = array_make<lbValue>(permanent_allocator(), 2);
  6262. args[0] = lhs;
  6263. args[1] = rhs;
  6264. switch (type_size_of(ft)) {
  6265. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  6266. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  6267. default: GB_PANIC("Unknown float type"); break;
  6268. }
  6269. }
  6270. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  6271. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  6272. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  6273. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  6274. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  6275. lbValue real = {};
  6276. lbValue imag = {};
  6277. switch (op) {
  6278. case Token_Add:
  6279. real = lb_emit_arith(p, Token_Add, a, c, ft);
  6280. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  6281. break;
  6282. case Token_Sub:
  6283. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  6284. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  6285. break;
  6286. case Token_Mul: {
  6287. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  6288. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  6289. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  6290. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  6291. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  6292. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  6293. break;
  6294. }
  6295. }
  6296. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  6297. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  6298. return lb_addr_load(p, res);
  6299. } else if (is_type_quaternion(type)) {
  6300. lhs = lb_emit_conv(p, lhs, type);
  6301. rhs = lb_emit_conv(p, rhs, type);
  6302. Type *ft = base_complex_elem_type(type);
  6303. if (op == Token_Add || op == Token_Sub) {
  6304. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  6305. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  6306. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  6307. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  6308. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  6309. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  6310. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  6311. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  6312. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  6313. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  6314. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  6315. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  6316. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  6317. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  6318. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  6319. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  6320. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  6321. return lb_addr_load(p, res);
  6322. } else if (op == Token_Mul) {
  6323. auto args = array_make<lbValue>(permanent_allocator(), 2);
  6324. args[0] = lhs;
  6325. args[1] = rhs;
  6326. switch (8*type_size_of(ft)) {
  6327. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  6328. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  6329. default: GB_PANIC("Unknown float type"); break;
  6330. }
  6331. } else if (op == Token_Quo) {
  6332. auto args = array_make<lbValue>(permanent_allocator(), 2);
  6333. args[0] = lhs;
  6334. args[1] = rhs;
  6335. switch (8*type_size_of(ft)) {
  6336. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  6337. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  6338. default: GB_PANIC("Unknown float type"); break;
  6339. }
  6340. }
  6341. }
  6342. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  6343. switch (op) {
  6344. case Token_AndNot:
  6345. case Token_And:
  6346. case Token_Or:
  6347. case Token_Xor:
  6348. goto handle_op;
  6349. }
  6350. Type *platform_type = integer_endian_type_to_platform_type(type);
  6351. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  6352. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  6353. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  6354. return lb_emit_byte_swap(p, res, type);
  6355. }
  6356. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  6357. Type *platform_type = integer_endian_type_to_platform_type(type);
  6358. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  6359. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  6360. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  6361. return lb_emit_byte_swap(p, res, type);
  6362. }
  6363. handle_op:
  6364. lhs = lb_emit_conv(p, lhs, type);
  6365. rhs = lb_emit_conv(p, rhs, type);
  6366. lbValue res = {};
  6367. res.type = type;
  6368. // NOTE(bill): Bit Set Aliases for + and -
  6369. if (is_type_bit_set(type)) {
  6370. switch (op) {
  6371. case Token_Add: op = Token_Or; break;
  6372. case Token_Sub: op = Token_AndNot; break;
  6373. }
  6374. }
  6375. Type *integral_type = type;
  6376. if (is_type_simd_vector(integral_type)) {
  6377. integral_type = core_array_type(integral_type);
  6378. }
  6379. switch (op) {
  6380. case Token_Add:
  6381. if (is_type_float(integral_type)) {
  6382. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  6383. return res;
  6384. }
  6385. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  6386. return res;
  6387. case Token_Sub:
  6388. if (is_type_float(integral_type)) {
  6389. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  6390. return res;
  6391. }
  6392. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  6393. return res;
  6394. case Token_Mul:
  6395. if (is_type_float(integral_type)) {
  6396. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  6397. return res;
  6398. }
  6399. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  6400. return res;
  6401. case Token_Quo:
  6402. if (is_type_float(integral_type)) {
  6403. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  6404. return res;
  6405. } else if (is_type_unsigned(integral_type)) {
  6406. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  6407. return res;
  6408. }
  6409. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  6410. return res;
  6411. case Token_Mod:
  6412. if (is_type_float(integral_type)) {
  6413. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  6414. return res;
  6415. } else if (is_type_unsigned(integral_type)) {
  6416. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  6417. return res;
  6418. }
  6419. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  6420. return res;
  6421. case Token_ModMod:
  6422. if (is_type_unsigned(integral_type)) {
  6423. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  6424. return res;
  6425. } else {
  6426. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  6427. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  6428. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  6429. res.value = c;
  6430. return res;
  6431. }
  6432. case Token_And:
  6433. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  6434. return res;
  6435. case Token_Or:
  6436. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  6437. return res;
  6438. case Token_Xor:
  6439. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  6440. return res;
  6441. case Token_Shl:
  6442. {
  6443. rhs = lb_emit_conv(p, rhs, lhs.type);
  6444. LLVMValueRef lhsval = lhs.value;
  6445. LLVMValueRef bits = rhs.value;
  6446. LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  6447. LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
  6448. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  6449. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  6450. res.value = LLVMBuildSelect(p->builder, width_test, res.value, zero, "");
  6451. return res;
  6452. }
  6453. case Token_Shr:
  6454. {
  6455. rhs = lb_emit_conv(p, rhs, lhs.type);
  6456. LLVMValueRef lhsval = lhs.value;
  6457. LLVMValueRef bits = rhs.value;
  6458. bool is_unsigned = is_type_unsigned(integral_type);
  6459. LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  6460. LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
  6461. if (is_unsigned) {
  6462. res.value = LLVMBuildLShr(p->builder, lhsval, bits, "");
  6463. } else {
  6464. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  6465. }
  6466. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  6467. res.value = LLVMBuildSelect(p->builder, width_test, res.value, zero, "");
  6468. return res;
  6469. }
  6470. case Token_AndNot:
  6471. {
  6472. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  6473. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  6474. return res;
  6475. }
  6476. break;
  6477. }
  6478. GB_PANIC("unhandled operator of lb_emit_arith");
  6479. return {};
  6480. }
  6481. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  6482. ast_node(be, BinaryExpr, expr);
  6483. TypeAndValue tv = type_and_value_of_expr(expr);
  6484. switch (be->op.kind) {
  6485. case Token_Add:
  6486. case Token_Sub:
  6487. case Token_Mul:
  6488. case Token_Quo:
  6489. case Token_Mod:
  6490. case Token_ModMod:
  6491. case Token_And:
  6492. case Token_Or:
  6493. case Token_Xor:
  6494. case Token_AndNot: {
  6495. Type *type = default_type(tv.type);
  6496. lbValue left = lb_build_expr(p, be->left);
  6497. lbValue right = lb_build_expr(p, be->right);
  6498. return lb_emit_arith(p, be->op.kind, left, right, type);
  6499. }
  6500. case Token_Shl:
  6501. case Token_Shr: {
  6502. lbValue left, right;
  6503. Type *type = default_type(tv.type);
  6504. left = lb_build_expr(p, be->left);
  6505. if (lb_is_expr_untyped_const(be->right)) {
  6506. // NOTE(bill): RHS shift operands can still be untyped
  6507. // Just bypass the standard lb_build_expr
  6508. right = lb_expr_untyped_const_to_typed(p->module, be->right, type);
  6509. } else {
  6510. right = lb_build_expr(p, be->right);
  6511. }
  6512. return lb_emit_arith(p, be->op.kind, left, right, type);
  6513. }
  6514. case Token_CmpEq:
  6515. case Token_NotEq:
  6516. if (is_type_untyped_nil(be->right->tav.type)) {
  6517. lbValue left = lb_build_expr(p, be->left);
  6518. lbValue cmp = lb_emit_comp_against_nil(p, be->op.kind, left);
  6519. Type *type = default_type(tv.type);
  6520. return lb_emit_conv(p, cmp, type);
  6521. } else if (is_type_untyped_nil(be->left->tav.type)) {
  6522. lbValue right = lb_build_expr(p, be->right);
  6523. lbValue cmp = lb_emit_comp_against_nil(p, be->op.kind, right);
  6524. Type *type = default_type(tv.type);
  6525. return lb_emit_conv(p, cmp, type);
  6526. }
  6527. /*fallthrough*/
  6528. case Token_Lt:
  6529. case Token_LtEq:
  6530. case Token_Gt:
  6531. case Token_GtEq:
  6532. {
  6533. lbValue left = {};
  6534. lbValue right = {};
  6535. if (be->left->tav.mode == Addressing_Type) {
  6536. left = lb_typeid(p->module, be->left->tav.type);
  6537. }
  6538. if (be->right->tav.mode == Addressing_Type) {
  6539. right = lb_typeid(p->module, be->right->tav.type);
  6540. }
  6541. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  6542. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  6543. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  6544. Type *type = default_type(tv.type);
  6545. return lb_emit_conv(p, cmp, type);
  6546. }
  6547. case Token_CmpAnd:
  6548. case Token_CmpOr:
  6549. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  6550. case Token_in:
  6551. case Token_not_in:
  6552. {
  6553. lbValue left = lb_build_expr(p, be->left);
  6554. Type *type = default_type(tv.type);
  6555. lbValue right = lb_build_expr(p, be->right);
  6556. Type *rt = base_type(right.type);
  6557. if (is_type_pointer(rt)) {
  6558. right = lb_emit_load(p, right);
  6559. rt = type_deref(rt);
  6560. }
  6561. switch (rt->kind) {
  6562. case Type_Map:
  6563. {
  6564. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  6565. lbValue h = lb_gen_map_header(p, addr, rt);
  6566. lbValue key = lb_gen_map_hash(p, left, rt->Map.key);
  6567. auto args = array_make<lbValue>(permanent_allocator(), 2);
  6568. args[0] = h;
  6569. args[1] = key;
  6570. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  6571. if (be->op.kind == Token_in) {
  6572. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  6573. } else {
  6574. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  6575. }
  6576. }
  6577. break;
  6578. case Type_BitSet:
  6579. {
  6580. Type *key_type = rt->BitSet.elem;
  6581. GB_ASSERT(are_types_identical(left.type, key_type));
  6582. Type *it = bit_set_to_int(rt);
  6583. left = lb_emit_conv(p, left, it);
  6584. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  6585. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  6586. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  6587. bit = lb_emit_conv(p, bit, it);
  6588. lbValue old_value = lb_emit_transmute(p, right, it);
  6589. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  6590. if (be->op.kind == Token_in) {
  6591. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  6592. } else {
  6593. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  6594. }
  6595. }
  6596. break;
  6597. default:
  6598. GB_PANIC("Invalid 'in' type");
  6599. }
  6600. break;
  6601. }
  6602. break;
  6603. default:
  6604. GB_PANIC("Invalid binary expression");
  6605. break;
  6606. }
  6607. return {};
  6608. }
  6609. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  6610. Type *prev_src = src;
  6611. // Type *prev_dst = dst;
  6612. src = base_type(type_deref(src));
  6613. // dst = base_type(type_deref(dst));
  6614. bool src_is_ptr = src != prev_src;
  6615. // bool dst_is_ptr = dst != prev_dst;
  6616. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  6617. for_array(i, src->Struct.fields) {
  6618. Entity *f = src->Struct.fields[i];
  6619. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  6620. if (are_types_identical(dst, f->type)) {
  6621. return f->token.string;
  6622. }
  6623. if (src_is_ptr && is_type_pointer(dst)) {
  6624. if (are_types_identical(type_deref(dst), f->type)) {
  6625. return f->token.string;
  6626. }
  6627. }
  6628. if (is_type_struct(f->type)) {
  6629. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  6630. if (name.len > 0) {
  6631. return name;
  6632. }
  6633. }
  6634. }
  6635. }
  6636. return str_lit("");
  6637. }
  6638. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  6639. GB_ASSERT(is_type_pointer(value.type));
  6640. GB_ASSERT(is_type_pointer(t));
  6641. GB_ASSERT(lb_is_const(value));
  6642. lbValue res = {};
  6643. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  6644. res.type = t;
  6645. return res;
  6646. }
  6647. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  6648. lbModule *m = p->module;
  6649. t = reduce_tuple_to_single_type(t);
  6650. Type *src_type = value.type;
  6651. if (are_types_identical(t, src_type)) {
  6652. return value;
  6653. }
  6654. Type *src = core_type(src_type);
  6655. Type *dst = core_type(t);
  6656. GB_ASSERT(src != nullptr);
  6657. GB_ASSERT(dst != nullptr);
  6658. if (is_type_untyped_nil(src)) {
  6659. return lb_const_nil(m, t);
  6660. }
  6661. if (is_type_untyped_undef(src)) {
  6662. return lb_const_undef(m, t);
  6663. }
  6664. if (LLVMIsConstant(value.value)) {
  6665. if (is_type_any(dst)) {
  6666. Type *st = default_type(src_type);
  6667. lbAddr default_value = lb_add_local_generated(p, st, false);
  6668. lb_addr_store(p, default_value, value);
  6669. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  6670. lbValue id = lb_typeid(m, st);
  6671. lbAddr res = lb_add_local_generated(p, t, false);
  6672. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  6673. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  6674. lb_emit_store(p, a0, data);
  6675. lb_emit_store(p, a1, id);
  6676. return lb_addr_load(p, res);
  6677. } else if (dst->kind == Type_Basic) {
  6678. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  6679. String str = lb_get_const_string(m, value);
  6680. lbValue res = {};
  6681. res.type = t;
  6682. res.value = llvm_cstring(m, str);
  6683. return res;
  6684. }
  6685. // if (is_type_float(dst)) {
  6686. // return value;
  6687. // } else if (is_type_integer(dst)) {
  6688. // return value;
  6689. // }
  6690. // ExactValue ev = value->Constant.value;
  6691. // if (is_type_float(dst)) {
  6692. // ev = exact_value_to_float(ev);
  6693. // } else if (is_type_complex(dst)) {
  6694. // ev = exact_value_to_complex(ev);
  6695. // } else if (is_type_quaternion(dst)) {
  6696. // ev = exact_value_to_quaternion(ev);
  6697. // } else if (is_type_string(dst)) {
  6698. // // Handled elsewhere
  6699. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  6700. // } else if (is_type_integer(dst)) {
  6701. // ev = exact_value_to_integer(ev);
  6702. // } else if (is_type_pointer(dst)) {
  6703. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  6704. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  6705. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  6706. // }
  6707. // return lb_const_value(p->module, t, ev);
  6708. }
  6709. }
  6710. if (are_types_identical(src, dst)) {
  6711. if (!are_types_identical(src_type, t)) {
  6712. return lb_emit_transmute(p, value, t);
  6713. }
  6714. return value;
  6715. }
  6716. // bool <-> llvm bool
  6717. if (is_type_boolean(src) && dst == t_llvm_bool) {
  6718. lbValue res = {};
  6719. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  6720. res.type = dst;
  6721. return res;
  6722. }
  6723. if (src == t_llvm_bool && is_type_boolean(dst)) {
  6724. lbValue res = {};
  6725. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  6726. res.type = dst;
  6727. return res;
  6728. }
  6729. // integer -> integer
  6730. if (is_type_integer(src) && is_type_integer(dst)) {
  6731. GB_ASSERT(src->kind == Type_Basic &&
  6732. dst->kind == Type_Basic);
  6733. i64 sz = type_size_of(default_type(src));
  6734. i64 dz = type_size_of(default_type(dst));
  6735. if (sz == dz) {
  6736. if (dz > 1 && !types_have_same_internal_endian(src, dst)) {
  6737. return lb_emit_byte_swap(p, value, t);
  6738. }
  6739. lbValue res = {};
  6740. res.value = value.value;
  6741. res.type = t;
  6742. return res;
  6743. }
  6744. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  6745. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6746. value = lb_emit_byte_swap(p, value, platform_src_type);
  6747. }
  6748. LLVMOpcode op = LLVMTrunc;
  6749. if (dz < sz) {
  6750. op = LLVMTrunc;
  6751. } else if (dz == sz) {
  6752. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  6753. // NOTE(bill): Copy the value just for type correctness
  6754. op = LLVMBitCast;
  6755. } else if (dz > sz) {
  6756. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  6757. }
  6758. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  6759. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6760. lbValue res = {};
  6761. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  6762. res.type = t;
  6763. return lb_emit_byte_swap(p, res, t);
  6764. } else {
  6765. lbValue res = {};
  6766. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  6767. res.type = t;
  6768. return res;
  6769. }
  6770. }
  6771. // boolean -> boolean/integer
  6772. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  6773. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  6774. lbValue res = {};
  6775. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  6776. res.type = t;
  6777. return res;
  6778. }
  6779. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  6780. return lb_emit_transmute(p, value, dst);
  6781. }
  6782. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  6783. return lb_emit_transmute(p, value, dst);
  6784. }
  6785. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  6786. return lb_emit_transmute(p, value, dst);
  6787. }
  6788. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  6789. return lb_emit_transmute(p, value, dst);
  6790. }
  6791. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  6792. lbValue c = lb_emit_conv(p, value, t_cstring);
  6793. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6794. args[0] = c;
  6795. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  6796. return lb_emit_conv(p, s, dst);
  6797. }
  6798. // integer -> boolean
  6799. if (is_type_integer(src) && is_type_boolean(dst)) {
  6800. lbValue res = {};
  6801. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  6802. res.type = t_llvm_bool;
  6803. return lb_emit_conv(p, res, t);
  6804. }
  6805. // float -> float
  6806. if (is_type_float(src) && is_type_float(dst)) {
  6807. i64 sz = type_size_of(src);
  6808. i64 dz = type_size_of(dst);
  6809. if (dz == sz) {
  6810. if (types_have_same_internal_endian(src, dst)) {
  6811. lbValue res = {};
  6812. res.type = t;
  6813. res.value = value.value;
  6814. return res;
  6815. } else {
  6816. return lb_emit_byte_swap(p, value, t);
  6817. }
  6818. }
  6819. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6820. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6821. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6822. lbValue res = {};
  6823. res = lb_emit_conv(p, value, platform_src_type);
  6824. res = lb_emit_conv(p, res, platform_dst_type);
  6825. if (is_type_different_to_arch_endianness(dst)) {
  6826. res = lb_emit_byte_swap(p, res, t);
  6827. }
  6828. return lb_emit_conv(p, res, t);
  6829. }
  6830. lbValue res = {};
  6831. res.type = t;
  6832. if (dz >= sz) {
  6833. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  6834. } else {
  6835. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  6836. }
  6837. return res;
  6838. }
  6839. if (is_type_complex(src) && is_type_complex(dst)) {
  6840. Type *ft = base_complex_elem_type(dst);
  6841. lbAddr gen = lb_add_local_generated(p, dst, false);
  6842. lbValue gp = lb_addr_get_ptr(p, gen);
  6843. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6844. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6845. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  6846. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  6847. return lb_addr_load(p, gen);
  6848. }
  6849. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  6850. // @QuaternionLayout
  6851. Type *ft = base_complex_elem_type(dst);
  6852. lbAddr gen = lb_add_local_generated(p, dst, false);
  6853. lbValue gp = lb_addr_get_ptr(p, gen);
  6854. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6855. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6856. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  6857. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  6858. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  6859. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  6860. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  6861. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  6862. return lb_addr_load(p, gen);
  6863. }
  6864. if (is_type_integer(src) && is_type_complex(dst)) {
  6865. Type *ft = base_complex_elem_type(dst);
  6866. lbAddr gen = lb_add_local_generated(p, dst, true);
  6867. lbValue gp = lb_addr_get_ptr(p, gen);
  6868. lbValue real = lb_emit_conv(p, value, ft);
  6869. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  6870. return lb_addr_load(p, gen);
  6871. }
  6872. if (is_type_float(src) && is_type_complex(dst)) {
  6873. Type *ft = base_complex_elem_type(dst);
  6874. lbAddr gen = lb_add_local_generated(p, dst, true);
  6875. lbValue gp = lb_addr_get_ptr(p, gen);
  6876. lbValue real = lb_emit_conv(p, value, ft);
  6877. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  6878. return lb_addr_load(p, gen);
  6879. }
  6880. if (is_type_integer(src) && is_type_quaternion(dst)) {
  6881. Type *ft = base_complex_elem_type(dst);
  6882. lbAddr gen = lb_add_local_generated(p, dst, true);
  6883. lbValue gp = lb_addr_get_ptr(p, gen);
  6884. lbValue real = lb_emit_conv(p, value, ft);
  6885. // @QuaternionLayout
  6886. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  6887. return lb_addr_load(p, gen);
  6888. }
  6889. if (is_type_float(src) && is_type_quaternion(dst)) {
  6890. Type *ft = base_complex_elem_type(dst);
  6891. lbAddr gen = lb_add_local_generated(p, dst, true);
  6892. lbValue gp = lb_addr_get_ptr(p, gen);
  6893. lbValue real = lb_emit_conv(p, value, ft);
  6894. // @QuaternionLayout
  6895. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  6896. return lb_addr_load(p, gen);
  6897. }
  6898. if (is_type_complex(src) && is_type_quaternion(dst)) {
  6899. Type *ft = base_complex_elem_type(dst);
  6900. lbAddr gen = lb_add_local_generated(p, dst, true);
  6901. lbValue gp = lb_addr_get_ptr(p, gen);
  6902. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6903. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6904. // @QuaternionLayout
  6905. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  6906. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  6907. return lb_addr_load(p, gen);
  6908. }
  6909. // float <-> integer
  6910. if (is_type_float(src) && is_type_integer(dst)) {
  6911. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6912. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6913. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6914. lbValue res = {};
  6915. res = lb_emit_conv(p, value, platform_src_type);
  6916. res = lb_emit_conv(p, res, platform_dst_type);
  6917. if (is_type_different_to_arch_endianness(dst)) {
  6918. res = lb_emit_byte_swap(p, res, t);
  6919. }
  6920. return lb_emit_conv(p, res, t);
  6921. }
  6922. lbValue res = {};
  6923. res.type = t;
  6924. if (is_type_unsigned(dst)) {
  6925. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  6926. } else {
  6927. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  6928. }
  6929. return res;
  6930. }
  6931. if (is_type_integer(src) && is_type_float(dst)) {
  6932. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6933. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6934. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6935. lbValue res = {};
  6936. res = lb_emit_conv(p, value, platform_src_type);
  6937. res = lb_emit_conv(p, res, platform_dst_type);
  6938. if (is_type_different_to_arch_endianness(dst)) {
  6939. res = lb_emit_byte_swap(p, res, t);
  6940. }
  6941. return lb_emit_conv(p, res, t);
  6942. }
  6943. if (is_type_integer_128bit(src)) {
  6944. auto args = array_make<lbValue>(temporary_allocator(), 1);
  6945. args[0] = value;
  6946. char const *call = "floattidf";
  6947. if (is_type_unsigned(src)) {
  6948. call = "floattidf_unsigned";
  6949. }
  6950. lbValue res_f64 = lb_emit_runtime_call(p, call, args);
  6951. return lb_emit_conv(p, res_f64, t);
  6952. }
  6953. lbValue res = {};
  6954. res.type = t;
  6955. if (is_type_unsigned(src)) {
  6956. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  6957. } else {
  6958. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  6959. }
  6960. return res;
  6961. }
  6962. // Pointer <-> uintptr
  6963. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  6964. lbValue res = {};
  6965. res.type = t;
  6966. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6967. return res;
  6968. }
  6969. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  6970. lbValue res = {};
  6971. res.type = t;
  6972. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6973. return res;
  6974. }
  6975. #if 1
  6976. if (is_type_union(dst)) {
  6977. for_array(i, dst->Union.variants) {
  6978. Type *vt = dst->Union.variants[i];
  6979. if (are_types_identical(vt, src_type)) {
  6980. lbAddr parent = lb_add_local_generated(p, t, true);
  6981. lb_emit_store_union_variant(p, parent.addr, value, vt);
  6982. return lb_addr_load(p, parent);
  6983. }
  6984. }
  6985. }
  6986. #endif
  6987. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  6988. // subtype polymorphism casting
  6989. if (check_is_assignable_to_using_subtype(src_type, t)) {
  6990. Type *st = type_deref(src_type);
  6991. Type *pst = st;
  6992. st = type_deref(st);
  6993. bool st_is_ptr = is_type_pointer(src_type);
  6994. st = base_type(st);
  6995. Type *dt = t;
  6996. bool dt_is_ptr = type_deref(dt) != dt;
  6997. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  6998. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  6999. if (field_name.len > 0) {
  7000. // NOTE(bill): It can be casted
  7001. Selection sel = lookup_field(st, field_name, false, true);
  7002. if (sel.entity != nullptr) {
  7003. if (st_is_ptr) {
  7004. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  7005. Type *rt = res.type;
  7006. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  7007. res = lb_emit_load(p, res);
  7008. }
  7009. return res;
  7010. } else {
  7011. if (is_type_pointer(value.type)) {
  7012. Type *rt = value.type;
  7013. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  7014. value = lb_emit_load(p, value);
  7015. } else {
  7016. value = lb_emit_deep_field_gep(p, value, sel);
  7017. return lb_emit_load(p, value);
  7018. }
  7019. }
  7020. return lb_emit_deep_field_ev(p, value, sel);
  7021. }
  7022. } else {
  7023. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  7024. }
  7025. }
  7026. }
  7027. // Pointer <-> Pointer
  7028. if (is_type_pointer(src) && is_type_pointer(dst)) {
  7029. lbValue res = {};
  7030. res.type = t;
  7031. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  7032. return res;
  7033. }
  7034. // proc <-> proc
  7035. if (is_type_proc(src) && is_type_proc(dst)) {
  7036. lbValue res = {};
  7037. res.type = t;
  7038. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  7039. return res;
  7040. }
  7041. // pointer -> proc
  7042. if (is_type_pointer(src) && is_type_proc(dst)) {
  7043. lbValue res = {};
  7044. res.type = t;
  7045. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  7046. return res;
  7047. }
  7048. // proc -> pointer
  7049. if (is_type_proc(src) && is_type_pointer(dst)) {
  7050. lbValue res = {};
  7051. res.type = t;
  7052. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  7053. return res;
  7054. }
  7055. // []byte/[]u8 <-> string
  7056. if (is_type_u8_slice(src) && is_type_string(dst)) {
  7057. return lb_emit_transmute(p, value, t);
  7058. }
  7059. if (is_type_string(src) && is_type_u8_slice(dst)) {
  7060. return lb_emit_transmute(p, value, t);
  7061. }
  7062. if (is_type_array_like(dst)) {
  7063. Type *elem = base_array_type(dst);
  7064. lbValue e = lb_emit_conv(p, value, elem);
  7065. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  7066. lbAddr v = lb_add_local_generated(p, t, false);
  7067. isize index_count = cast(isize)get_array_type_count(dst);
  7068. for (isize i = 0; i < index_count; i++) {
  7069. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  7070. lb_emit_store(p, elem, e);
  7071. }
  7072. return lb_addr_load(p, v);
  7073. }
  7074. if (is_type_any(dst)) {
  7075. if (is_type_untyped_nil(src)) {
  7076. return lb_const_nil(p->module, t);
  7077. }
  7078. if (is_type_untyped_undef(src)) {
  7079. return lb_const_undef(p->module, t);
  7080. }
  7081. lbAddr result = lb_add_local_generated(p, t, true);
  7082. Type *st = default_type(src_type);
  7083. lbValue data = lb_address_from_load_or_generate_local(p, value);
  7084. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  7085. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  7086. data = lb_emit_conv(p, data, t_rawptr);
  7087. lbValue id = lb_typeid(p->module, st);
  7088. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  7089. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  7090. lb_emit_store(p, any_data, data);
  7091. lb_emit_store(p, any_id, id);
  7092. return lb_addr_load(p, result);
  7093. }
  7094. i64 src_sz = type_size_of(src);
  7095. i64 dst_sz = type_size_of(dst);
  7096. if (src_sz == dst_sz) {
  7097. // bit_set <-> integer
  7098. if (is_type_integer(src) && is_type_bit_set(dst)) {
  7099. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  7100. res.type = dst;
  7101. return res;
  7102. }
  7103. if (is_type_bit_set(src) && is_type_integer(dst)) {
  7104. lbValue bs = value;
  7105. bs.type = bit_set_to_int(src);
  7106. return lb_emit_conv(p, bs, dst);
  7107. }
  7108. // typeid <-> integer
  7109. if (is_type_integer(src) && is_type_typeid(dst)) {
  7110. return lb_emit_transmute(p, value, dst);
  7111. }
  7112. if (is_type_typeid(src) && is_type_integer(dst)) {
  7113. return lb_emit_transmute(p, value, dst);
  7114. }
  7115. }
  7116. if (is_type_untyped(src)) {
  7117. if (is_type_string(src) && is_type_string(dst)) {
  7118. lbAddr result = lb_add_local_generated(p, t, false);
  7119. lb_addr_store(p, result, value);
  7120. return lb_addr_load(p, result);
  7121. }
  7122. }
  7123. gb_printf_err("%.*s\n", LIT(p->name));
  7124. gb_printf_err("lb_emit_conv: src -> dst\n");
  7125. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  7126. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  7127. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  7128. gb_printf_err("Not Identical %p != %p\n", src, dst);
  7129. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  7130. type_to_string(src_type), type_to_string(t),
  7131. LIT(p->name));
  7132. return {};
  7133. }
  7134. bool lb_is_type_aggregate(Type *t) {
  7135. t = base_type(t);
  7136. switch (t->kind) {
  7137. case Type_Basic:
  7138. switch (t->Basic.kind) {
  7139. case Basic_string:
  7140. case Basic_any:
  7141. return true;
  7142. case Basic_complex32:
  7143. case Basic_complex64:
  7144. case Basic_complex128:
  7145. case Basic_quaternion64:
  7146. case Basic_quaternion128:
  7147. case Basic_quaternion256:
  7148. return true;
  7149. }
  7150. break;
  7151. case Type_Pointer:
  7152. return false;
  7153. case Type_Array:
  7154. case Type_Slice:
  7155. case Type_Struct:
  7156. case Type_Union:
  7157. case Type_Tuple:
  7158. case Type_DynamicArray:
  7159. case Type_Map:
  7160. case Type_SimdVector:
  7161. return true;
  7162. case Type_Named:
  7163. return lb_is_type_aggregate(t->Named.base);
  7164. }
  7165. return false;
  7166. }
  7167. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  7168. Type *src_type = value.type;
  7169. if (are_types_identical(t, src_type)) {
  7170. return value;
  7171. }
  7172. lbValue res = {};
  7173. res.type = t;
  7174. Type *src = base_type(src_type);
  7175. Type *dst = base_type(t);
  7176. lbModule *m = p->module;
  7177. i64 sz = type_size_of(src);
  7178. i64 dz = type_size_of(dst);
  7179. if (sz != dz) {
  7180. LLVMTypeRef s = lb_type(m, src);
  7181. LLVMTypeRef d = lb_type(m, dst);
  7182. i64 llvm_sz = lb_sizeof(s);
  7183. i64 llvm_dz = lb_sizeof(d);
  7184. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  7185. }
  7186. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  7187. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  7188. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  7189. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  7190. return res;
  7191. }
  7192. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  7193. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  7194. return res;
  7195. }
  7196. if (is_type_uintptr(src) && is_type_proc(dst)) {
  7197. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  7198. return res;
  7199. }
  7200. if (is_type_proc(src) && is_type_uintptr(dst)) {
  7201. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  7202. return res;
  7203. }
  7204. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  7205. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  7206. return res;
  7207. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  7208. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  7209. return res;
  7210. }
  7211. if (is_type_pointer(src) && is_type_pointer(dst)) {
  7212. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  7213. return res;
  7214. }
  7215. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  7216. lbValue s = lb_address_from_load_or_generate_local(p, value);
  7217. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  7218. return lb_emit_load(p, d);
  7219. }
  7220. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  7221. return res;
  7222. }
  7223. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  7224. GB_ASSERT(addr.kind == lbAddr_Context);
  7225. GB_ASSERT(addr.ctx.sel.index.count == 0);
  7226. lbModule *m = p->module;
  7227. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7228. args[0] = addr.addr;
  7229. lb_emit_runtime_call(p, "__init_context", args);
  7230. }
  7231. lbContextData *lb_push_context_onto_stack_from_implicit_parameter(lbProcedure *p) {
  7232. Type *pt = base_type(p->type);
  7233. GB_ASSERT(pt->kind == Type_Proc);
  7234. GB_ASSERT(pt->Proc.calling_convention == ProcCC_Odin);
  7235. String name = str_lit("__.context_ptr");
  7236. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), t_context_ptr, false, false);
  7237. e->flags |= EntityFlag_NoAlias;
  7238. LLVMValueRef context_ptr = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  7239. LLVMSetValueName2(context_ptr, cast(char const *)name.text, name.len);
  7240. context_ptr = LLVMBuildPointerCast(p->builder, context_ptr, lb_type(p->module, e->type), "");
  7241. lbValue param = {context_ptr, e->type};
  7242. lb_add_entity(p->module, e, param);
  7243. lbAddr ctx_addr = {};
  7244. ctx_addr.kind = lbAddr_Context;
  7245. ctx_addr.addr = param;
  7246. lbContextData *cd = array_add_and_get(&p->context_stack);
  7247. cd->ctx = ctx_addr;
  7248. cd->scope_index = -1;
  7249. cd->uses = +1; // make sure it has been used already
  7250. return cd;
  7251. }
  7252. lbContextData *lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  7253. ctx.kind = lbAddr_Context;
  7254. lbContextData *cd = array_add_and_get(&p->context_stack);
  7255. cd->ctx = ctx;
  7256. cd->scope_index = p->scope_index;
  7257. return cd;
  7258. }
  7259. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  7260. if (p->context_stack.count > 0) {
  7261. return p->context_stack[p->context_stack.count-1].ctx;
  7262. }
  7263. Type *pt = base_type(p->type);
  7264. GB_ASSERT(pt->kind == Type_Proc);
  7265. GB_ASSERT(pt->Proc.calling_convention != ProcCC_Odin);
  7266. lbAddr c = lb_add_local_generated(p, t_context, true);
  7267. c.kind = lbAddr_Context;
  7268. lb_emit_init_context(p, c);
  7269. lb_push_context_onto_stack(p, c);
  7270. lb_add_debug_context_variable(p, c);
  7271. return c;
  7272. }
  7273. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  7274. if (LLVMIsALoadInst(value.value)) {
  7275. lbValue res = {};
  7276. res.value = LLVMGetOperand(value.value, 0);
  7277. res.type = alloc_type_pointer(value.type);
  7278. return res;
  7279. }
  7280. GB_ASSERT(is_type_typed(value.type));
  7281. lbAddr res = lb_add_local_generated(p, value.type, false);
  7282. lb_addr_store(p, res, value);
  7283. return res.addr;
  7284. }
  7285. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  7286. if (LLVMIsALoadInst(value.value)) {
  7287. lbValue res = {};
  7288. res.value = LLVMGetOperand(value.value, 0);
  7289. res.type = alloc_type_pointer(value.type);
  7290. return res;
  7291. }
  7292. GB_PANIC("lb_address_from_load");
  7293. return {};
  7294. }
  7295. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  7296. i64 type_alignment = type_align_of(new_type);
  7297. if (alignment < type_alignment) {
  7298. alignment = type_alignment;
  7299. }
  7300. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  7301. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  7302. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  7303. lb_addr_store(p, ptr, val);
  7304. // ptr.kind = lbAddr_Context;
  7305. return ptr.addr;
  7306. }
  7307. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  7308. GB_ASSERT(is_type_pointer(s.type));
  7309. Type *t = base_type(type_deref(s.type));
  7310. Type *result_type = nullptr;
  7311. if (is_type_relative_pointer(t)) {
  7312. s = lb_addr_get_ptr(p, lb_addr(s));
  7313. }
  7314. if (is_type_struct(t)) {
  7315. result_type = get_struct_field_type(t, index);
  7316. } else if (is_type_union(t)) {
  7317. GB_ASSERT(index == -1);
  7318. return lb_emit_union_tag_ptr(p, s);
  7319. } else if (is_type_tuple(t)) {
  7320. GB_ASSERT(t->Tuple.variables.count > 0);
  7321. result_type = t->Tuple.variables[index]->type;
  7322. } else if (is_type_complex(t)) {
  7323. Type *ft = base_complex_elem_type(t);
  7324. switch (index) {
  7325. case 0: result_type = ft; break;
  7326. case 1: result_type = ft; break;
  7327. }
  7328. } else if (is_type_quaternion(t)) {
  7329. Type *ft = base_complex_elem_type(t);
  7330. switch (index) {
  7331. case 0: result_type = ft; break;
  7332. case 1: result_type = ft; break;
  7333. case 2: result_type = ft; break;
  7334. case 3: result_type = ft; break;
  7335. }
  7336. } else if (is_type_slice(t)) {
  7337. switch (index) {
  7338. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  7339. case 1: result_type = t_int; break;
  7340. }
  7341. } else if (is_type_string(t)) {
  7342. switch (index) {
  7343. case 0: result_type = t_u8_ptr; break;
  7344. case 1: result_type = t_int; break;
  7345. }
  7346. } else if (is_type_any(t)) {
  7347. switch (index) {
  7348. case 0: result_type = t_rawptr; break;
  7349. case 1: result_type = t_typeid; break;
  7350. }
  7351. } else if (is_type_dynamic_array(t)) {
  7352. switch (index) {
  7353. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  7354. case 1: result_type = t_int; break;
  7355. case 2: result_type = t_int; break;
  7356. case 3: result_type = t_allocator; break;
  7357. }
  7358. } else if (is_type_map(t)) {
  7359. init_map_internal_types(t);
  7360. Type *itp = alloc_type_pointer(t->Map.internal_type);
  7361. s = lb_emit_transmute(p, s, itp);
  7362. Type *gst = t->Map.internal_type;
  7363. GB_ASSERT(gst->kind == Type_Struct);
  7364. switch (index) {
  7365. case 0: result_type = get_struct_field_type(gst, 0); break;
  7366. case 1: result_type = get_struct_field_type(gst, 1); break;
  7367. }
  7368. } else if (is_type_array(t)) {
  7369. return lb_emit_array_epi(p, s, index);
  7370. } else if (is_type_relative_slice(t)) {
  7371. switch (index) {
  7372. case 0: result_type = t->RelativeSlice.base_integer; break;
  7373. case 1: result_type = t->RelativeSlice.base_integer; break;
  7374. }
  7375. } else {
  7376. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  7377. }
  7378. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  7379. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  7380. index += 1;
  7381. }
  7382. if (lb_is_const(s)) {
  7383. lbModule *m = p->module;
  7384. lbValue res = {};
  7385. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  7386. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  7387. res.type = alloc_type_pointer(result_type);
  7388. return res;
  7389. } else {
  7390. lbValue res = {};
  7391. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  7392. res.type = alloc_type_pointer(result_type);
  7393. return res;
  7394. }
  7395. }
  7396. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  7397. if (LLVMIsALoadInst(s.value)) {
  7398. lbValue res = {};
  7399. res.value = LLVMGetOperand(s.value, 0);
  7400. res.type = alloc_type_pointer(s.type);
  7401. lbValue ptr = lb_emit_struct_ep(p, res, index);
  7402. return lb_emit_load(p, ptr);
  7403. }
  7404. Type *t = base_type(s.type);
  7405. Type *result_type = nullptr;
  7406. switch (t->kind) {
  7407. case Type_Basic:
  7408. switch (t->Basic.kind) {
  7409. case Basic_string:
  7410. switch (index) {
  7411. case 0: result_type = t_u8_ptr; break;
  7412. case 1: result_type = t_int; break;
  7413. }
  7414. break;
  7415. case Basic_any:
  7416. switch (index) {
  7417. case 0: result_type = t_rawptr; break;
  7418. case 1: result_type = t_typeid; break;
  7419. }
  7420. break;
  7421. case Basic_complex32:
  7422. case Basic_complex64:
  7423. case Basic_complex128:
  7424. {
  7425. Type *ft = base_complex_elem_type(t);
  7426. switch (index) {
  7427. case 0: result_type = ft; break;
  7428. case 1: result_type = ft; break;
  7429. }
  7430. break;
  7431. }
  7432. case Basic_quaternion64:
  7433. case Basic_quaternion128:
  7434. case Basic_quaternion256:
  7435. {
  7436. Type *ft = base_complex_elem_type(t);
  7437. switch (index) {
  7438. case 0: result_type = ft; break;
  7439. case 1: result_type = ft; break;
  7440. case 2: result_type = ft; break;
  7441. case 3: result_type = ft; break;
  7442. }
  7443. break;
  7444. }
  7445. }
  7446. break;
  7447. case Type_Struct:
  7448. result_type = get_struct_field_type(t, index);
  7449. break;
  7450. case Type_Union:
  7451. GB_ASSERT(index == -1);
  7452. // return lb_emit_union_tag_value(p, s);
  7453. GB_PANIC("lb_emit_union_tag_value");
  7454. case Type_Tuple:
  7455. GB_ASSERT(t->Tuple.variables.count > 0);
  7456. result_type = t->Tuple.variables[index]->type;
  7457. if (t->Tuple.variables.count == 1) {
  7458. return s;
  7459. }
  7460. break;
  7461. case Type_Slice:
  7462. switch (index) {
  7463. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  7464. case 1: result_type = t_int; break;
  7465. }
  7466. break;
  7467. case Type_DynamicArray:
  7468. switch (index) {
  7469. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  7470. case 1: result_type = t_int; break;
  7471. case 2: result_type = t_int; break;
  7472. case 3: result_type = t_allocator; break;
  7473. }
  7474. break;
  7475. case Type_Map:
  7476. {
  7477. init_map_internal_types(t);
  7478. Type *gst = t->Map.generated_struct_type;
  7479. switch (index) {
  7480. case 0: result_type = get_struct_field_type(gst, 0); break;
  7481. case 1: result_type = get_struct_field_type(gst, 1); break;
  7482. }
  7483. }
  7484. break;
  7485. case Type_Array:
  7486. result_type = t->Array.elem;
  7487. break;
  7488. default:
  7489. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  7490. break;
  7491. }
  7492. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  7493. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  7494. index += 1;
  7495. }
  7496. lbValue res = {};
  7497. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  7498. res.type = result_type;
  7499. return res;
  7500. }
  7501. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  7502. GB_ASSERT(sel.index.count > 0);
  7503. Type *type = type_deref(e.type);
  7504. for_array(i, sel.index) {
  7505. i32 index = cast(i32)sel.index[i];
  7506. if (is_type_pointer(type)) {
  7507. type = type_deref(type);
  7508. e = lb_emit_load(p, e);
  7509. }
  7510. type = core_type(type);
  7511. if (is_type_quaternion(type)) {
  7512. e = lb_emit_struct_ep(p, e, index);
  7513. } else if (is_type_raw_union(type)) {
  7514. type = get_struct_field_type(type, index);
  7515. GB_ASSERT(is_type_pointer(e.type));
  7516. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  7517. } else if (is_type_struct(type)) {
  7518. type = get_struct_field_type(type, index);
  7519. e = lb_emit_struct_ep(p, e, index);
  7520. } else if (type->kind == Type_Union) {
  7521. GB_ASSERT(index == -1);
  7522. type = t_type_info_ptr;
  7523. e = lb_emit_struct_ep(p, e, index);
  7524. } else if (type->kind == Type_Tuple) {
  7525. type = type->Tuple.variables[index]->type;
  7526. e = lb_emit_struct_ep(p, e, index);
  7527. } else if (type->kind == Type_Basic) {
  7528. switch (type->Basic.kind) {
  7529. case Basic_any: {
  7530. if (index == 0) {
  7531. type = t_rawptr;
  7532. } else if (index == 1) {
  7533. type = t_type_info_ptr;
  7534. }
  7535. e = lb_emit_struct_ep(p, e, index);
  7536. break;
  7537. }
  7538. case Basic_string:
  7539. e = lb_emit_struct_ep(p, e, index);
  7540. break;
  7541. default:
  7542. GB_PANIC("un-gep-able type %s", type_to_string(type));
  7543. break;
  7544. }
  7545. } else if (type->kind == Type_Slice) {
  7546. e = lb_emit_struct_ep(p, e, index);
  7547. } else if (type->kind == Type_DynamicArray) {
  7548. e = lb_emit_struct_ep(p, e, index);
  7549. } else if (type->kind == Type_Array) {
  7550. e = lb_emit_array_epi(p, e, index);
  7551. } else if (type->kind == Type_Map) {
  7552. e = lb_emit_struct_ep(p, e, index);
  7553. } else if (type->kind == Type_RelativePointer) {
  7554. e = lb_emit_struct_ep(p, e, index);
  7555. } else {
  7556. GB_PANIC("un-gep-able type %s", type_to_string(type));
  7557. }
  7558. }
  7559. return e;
  7560. }
  7561. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  7562. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  7563. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  7564. return lb_emit_load(p, res);
  7565. }
  7566. void lb_build_defer_stmt(lbProcedure *p, lbDefer const &d) {
  7567. if (p->curr_block == nullptr) {
  7568. return;
  7569. }
  7570. // NOTE(bill): The prev block may defer injection before it's terminator
  7571. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  7572. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  7573. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  7574. return;
  7575. }
  7576. isize prev_context_stack_count = p->context_stack.count;
  7577. GB_ASSERT(prev_context_stack_count <= p->context_stack.capacity);
  7578. defer (p->context_stack.count = prev_context_stack_count);
  7579. p->context_stack.count = d.context_stack_count;
  7580. lbBlock *b = lb_create_block(p, "defer");
  7581. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  7582. lb_emit_jump(p, b);
  7583. }
  7584. lb_start_block(p, b);
  7585. if (d.kind == lbDefer_Node) {
  7586. lb_build_stmt(p, d.stmt);
  7587. } else if (d.kind == lbDefer_Instr) {
  7588. // NOTE(bill): Need to make a new copy
  7589. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  7590. LLVMInsertIntoBuilder(p->builder, instr);
  7591. } else if (d.kind == lbDefer_Proc) {
  7592. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  7593. }
  7594. }
  7595. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  7596. isize count = p->defer_stmts.count;
  7597. isize i = count;
  7598. while (i --> 0) {
  7599. lbDefer const &d = p->defer_stmts[i];
  7600. if (kind == lbDeferExit_Default) {
  7601. if (p->scope_index == d.scope_index &&
  7602. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  7603. lb_build_defer_stmt(p, d);
  7604. array_pop(&p->defer_stmts);
  7605. continue;
  7606. } else {
  7607. break;
  7608. }
  7609. } else if (kind == lbDeferExit_Return) {
  7610. lb_build_defer_stmt(p, d);
  7611. } else if (kind == lbDeferExit_Branch) {
  7612. GB_ASSERT(block != nullptr);
  7613. isize lower_limit = block->scope_index;
  7614. if (lower_limit < d.scope_index) {
  7615. lb_build_defer_stmt(p, d);
  7616. }
  7617. }
  7618. }
  7619. }
  7620. void lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  7621. Type *pt = base_type(p->type);
  7622. GB_ASSERT(pt->kind == Type_Proc);
  7623. if (pt->Proc.calling_convention == ProcCC_Odin) {
  7624. GB_ASSERT(p->context_stack.count != 0);
  7625. }
  7626. lbDefer *d = array_add_and_get(&p->defer_stmts);
  7627. d->kind = lbDefer_Node;
  7628. d->scope_index = scope_index;
  7629. d->context_stack_count = p->context_stack.count;
  7630. d->block = p->curr_block;
  7631. d->stmt = stmt;
  7632. }
  7633. void lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  7634. Type *pt = base_type(p->type);
  7635. GB_ASSERT(pt->kind == Type_Proc);
  7636. if (pt->Proc.calling_convention == ProcCC_Odin) {
  7637. GB_ASSERT(p->context_stack.count != 0);
  7638. }
  7639. lbDefer *d = array_add_and_get(&p->defer_stmts);
  7640. d->kind = lbDefer_Proc;
  7641. d->scope_index = p->scope_index;
  7642. d->block = p->curr_block;
  7643. d->context_stack_count = p->context_stack.count;
  7644. d->proc.deferred = deferred;
  7645. d->proc.result_as_args = result_as_args;
  7646. }
  7647. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  7648. Array<lbValue> array = {};
  7649. Type *t = base_type(value.type);
  7650. if (t == nullptr) {
  7651. // Do nothing
  7652. } else if (is_type_tuple(t)) {
  7653. GB_ASSERT(t->kind == Type_Tuple);
  7654. auto *rt = &t->Tuple;
  7655. if (rt->variables.count > 0) {
  7656. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  7657. for_array(i, rt->variables) {
  7658. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  7659. array[i] = elem;
  7660. }
  7661. }
  7662. } else {
  7663. array = array_make<lbValue>(permanent_allocator(), 1);
  7664. array[0] = value;
  7665. }
  7666. return array;
  7667. }
  7668. 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) {
  7669. GB_ASSERT(p->module->ctx == LLVMGetTypeContext(LLVMTypeOf(value.value)));
  7670. unsigned arg_count = cast(unsigned)processed_args.count;
  7671. if (return_ptr.value != nullptr) {
  7672. arg_count += 1;
  7673. }
  7674. if (context_ptr.addr.value != nullptr) {
  7675. arg_count += 1;
  7676. }
  7677. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  7678. isize arg_index = 0;
  7679. if (return_ptr.value != nullptr) {
  7680. args[arg_index++] = return_ptr.value;
  7681. }
  7682. for_array(i, processed_args) {
  7683. lbValue arg = processed_args[i];
  7684. args[arg_index++] = arg.value;
  7685. }
  7686. if (context_ptr.addr.value != nullptr) {
  7687. LLVMValueRef cp = context_ptr.addr.value;
  7688. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  7689. args[arg_index++] = cp;
  7690. }
  7691. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  7692. GB_ASSERT(curr_block != p->decl_block->block);
  7693. {
  7694. LLVMTypeRef ftp = lb_type(p->module, value.type);
  7695. LLVMTypeRef ft = LLVMGetElementType(ftp);
  7696. LLVMValueRef fn = value.value;
  7697. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  7698. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  7699. }
  7700. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  7701. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  7702. {
  7703. unsigned param_count = LLVMCountParamTypes(fnp);
  7704. GB_ASSERT(arg_count >= param_count);
  7705. LLVMTypeRef *param_types = gb_alloc_array(temporary_allocator(), LLVMTypeRef, param_count);
  7706. LLVMGetParamTypes(fnp, param_types);
  7707. for (unsigned i = 0; i < param_count; i++) {
  7708. LLVMTypeRef param_type = param_types[i];
  7709. LLVMTypeRef arg_type = LLVMTypeOf(args[i]);
  7710. GB_ASSERT_MSG(
  7711. arg_type == param_type,
  7712. "Parameter types do not match: %s != %s, argument: %s",
  7713. LLVMPrintTypeToString(arg_type),
  7714. LLVMPrintTypeToString(param_type),
  7715. LLVMPrintValueToString(args[i])
  7716. );
  7717. }
  7718. }
  7719. LLVMValueRef ret = LLVMBuildCall2(p->builder, fnp, fn, args, arg_count, "");
  7720. switch (inlining) {
  7721. case ProcInlining_none:
  7722. break;
  7723. case ProcInlining_inline:
  7724. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  7725. break;
  7726. case ProcInlining_no_inline:
  7727. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "noinline"));
  7728. break;
  7729. }
  7730. lbValue res = {};
  7731. res.value = ret;
  7732. res.type = abi_rt;
  7733. return res;
  7734. }
  7735. }
  7736. lbValue lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  7737. AstPackage *pkg = m->info->runtime_package;
  7738. Entity *e = scope_lookup_current(pkg->scope, name);
  7739. return lb_find_procedure_value_from_entity(m, e);
  7740. }
  7741. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  7742. String name = make_string_c(c_name);
  7743. lbValue proc = lb_lookup_runtime_procedure(p->module, name);
  7744. return lb_emit_call(p, proc, args);
  7745. }
  7746. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_copy_elision_hint) {
  7747. lbModule *m = p->module;
  7748. Type *pt = base_type(value.type);
  7749. GB_ASSERT(pt->kind == Type_Proc);
  7750. Type *results = pt->Proc.results;
  7751. if (p->entity != nullptr) {
  7752. if (p->entity->flags & EntityFlag_Disabled) {
  7753. return {};
  7754. }
  7755. }
  7756. lbAddr context_ptr = {};
  7757. if (pt->Proc.calling_convention == ProcCC_Odin) {
  7758. context_ptr = lb_find_or_generate_context_ptr(p);
  7759. }
  7760. defer (if (pt->Proc.diverging) {
  7761. LLVMBuildUnreachable(p->builder);
  7762. });
  7763. bool is_c_vararg = pt->Proc.c_vararg;
  7764. isize param_count = pt->Proc.param_count;
  7765. if (is_c_vararg) {
  7766. GB_ASSERT(param_count-1 <= args.count);
  7767. param_count -= 1;
  7768. } else {
  7769. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  7770. }
  7771. lbValue result = {};
  7772. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  7773. {
  7774. lbFunctionType *ft = lb_get_function_type(m, p, pt);
  7775. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  7776. unsigned param_index = 0;
  7777. for (isize i = 0; i < param_count; i++) {
  7778. Entity *e = pt->Proc.params->Tuple.variables[i];
  7779. if (e->kind != Entity_Variable) {
  7780. continue;
  7781. }
  7782. GB_ASSERT(e->flags & EntityFlag_Param);
  7783. Type *original_type = e->type;
  7784. lbArgType *arg = &ft->args[param_index];
  7785. if (arg->kind == lbArg_Ignore) {
  7786. continue;
  7787. }
  7788. lbValue x = lb_emit_conv(p, args[i], original_type);
  7789. LLVMTypeRef xt = lb_type(p->module, x.type);
  7790. if (arg->kind == lbArg_Direct) {
  7791. LLVMTypeRef abi_type = arg->cast_type;
  7792. if (!abi_type) {
  7793. abi_type = arg->type;
  7794. }
  7795. if (xt == abi_type) {
  7796. array_add(&processed_args, x);
  7797. } else {
  7798. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  7799. array_add(&processed_args, x);
  7800. }
  7801. } else if (arg->kind == lbArg_Indirect) {
  7802. lbValue ptr = {};
  7803. if (arg->is_byval) {
  7804. ptr = lb_copy_value_to_ptr(p, x, original_type, arg->byval_alignment);
  7805. } else if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  7806. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  7807. // i.e. `T const &` in C++
  7808. ptr = lb_address_from_load_or_generate_local(p, x);
  7809. } else {
  7810. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  7811. }
  7812. array_add(&processed_args, ptr);
  7813. }
  7814. param_index += 1;
  7815. }
  7816. if (is_c_vararg) {
  7817. for (isize i = processed_args.count; i < args.count; i++) {
  7818. array_add(&processed_args, args[i]);
  7819. }
  7820. }
  7821. if (inlining == ProcInlining_none) {
  7822. inlining = p->inlining;
  7823. }
  7824. Type *rt = reduce_tuple_to_single_type(results);
  7825. if (return_by_pointer) {
  7826. lbValue return_ptr = {};
  7827. if (use_copy_elision_hint && p->copy_elision_hint.ptr.value != nullptr) {
  7828. if (are_types_identical(type_deref(p->copy_elision_hint.ptr.type), rt)) {
  7829. return_ptr = lb_consume_copy_elision_hint(p);
  7830. }
  7831. }
  7832. if (return_ptr.value == nullptr) {
  7833. lbAddr r = lb_add_local_generated(p, rt, true);
  7834. return_ptr = r.addr;
  7835. }
  7836. GB_ASSERT(is_type_pointer(return_ptr.type));
  7837. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  7838. result = lb_emit_load(p, return_ptr);
  7839. } else if (rt != nullptr) {
  7840. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  7841. if (ft->ret.cast_type) {
  7842. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  7843. }
  7844. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  7845. result.type = rt;
  7846. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  7847. result.type = t_llvm_bool;
  7848. }
  7849. if (!is_type_tuple(rt)) {
  7850. result = lb_emit_conv(p, result, rt);
  7851. }
  7852. } else {
  7853. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  7854. }
  7855. }
  7856. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  7857. if (found != nullptr) {
  7858. Entity *e = *found;
  7859. if (e != nullptr && entity_has_deferred_procedure(e)) {
  7860. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  7861. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  7862. lbValue deferred = lb_find_procedure_value_from_entity(p->module, deferred_entity);
  7863. auto in_args = args;
  7864. Array<lbValue> result_as_args = {};
  7865. switch (kind) {
  7866. case DeferredProcedure_none:
  7867. break;
  7868. case DeferredProcedure_in:
  7869. result_as_args = in_args;
  7870. break;
  7871. case DeferredProcedure_out:
  7872. result_as_args = lb_value_to_array(p, result);
  7873. break;
  7874. case DeferredProcedure_in_out:
  7875. {
  7876. auto out_args = lb_value_to_array(p, result);
  7877. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  7878. array_copy(&result_as_args, in_args, 0);
  7879. array_copy(&result_as_args, out_args, in_args.count);
  7880. }
  7881. break;
  7882. }
  7883. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  7884. }
  7885. }
  7886. return result;
  7887. }
  7888. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  7889. Type *t = s.type;
  7890. GB_ASSERT(is_type_pointer(t));
  7891. Type *st = base_type(type_deref(t));
  7892. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  7893. GB_ASSERT_MSG(is_type_integer(core_type(index.type)), "%s", type_to_string(index.type));
  7894. LLVMValueRef indices[2] = {};
  7895. indices[0] = llvm_zero(p->module);
  7896. indices[1] = lb_emit_conv(p, index, t_int).value;
  7897. Type *ptr = base_array_type(st);
  7898. lbValue res = {};
  7899. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  7900. res.type = alloc_type_pointer(ptr);
  7901. return res;
  7902. }
  7903. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  7904. Type *t = s.type;
  7905. GB_ASSERT(is_type_pointer(t));
  7906. Type *st = base_type(type_deref(t));
  7907. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  7908. GB_ASSERT(0 <= index);
  7909. Type *ptr = base_array_type(st);
  7910. LLVMValueRef indices[2] = {
  7911. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  7912. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  7913. };
  7914. lbValue res = {};
  7915. if (lb_is_const(s)) {
  7916. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  7917. } else {
  7918. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  7919. }
  7920. res.type = alloc_type_pointer(ptr);
  7921. return res;
  7922. }
  7923. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  7924. LLVMValueRef indices[1] = {index.value};
  7925. lbValue res = {};
  7926. res.type = ptr.type;
  7927. if (lb_is_const(ptr) && lb_is_const(index)) {
  7928. res.value = LLVMConstGEP(ptr.value, indices, 1);
  7929. } else {
  7930. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  7931. }
  7932. return res;
  7933. }
  7934. LLVMValueRef llvm_const_slice(lbModule *m, lbValue data, lbValue len) {
  7935. GB_ASSERT(is_type_pointer(data.type));
  7936. GB_ASSERT(are_types_identical(len.type, t_int));
  7937. LLVMValueRef vals[2] = {
  7938. data.value,
  7939. len.value,
  7940. };
  7941. return LLVMConstStructInContext(m->ctx, vals, gb_count_of(vals), false);
  7942. }
  7943. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  7944. Type *t = lb_addr_type(slice);
  7945. GB_ASSERT(is_type_slice(t));
  7946. lbValue ptr = lb_addr_get_ptr(p, slice);
  7947. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  7948. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  7949. }
  7950. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  7951. Type *t = lb_addr_type(string);
  7952. GB_ASSERT(is_type_string(t));
  7953. lbValue ptr = lb_addr_get_ptr(p, string);
  7954. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  7955. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  7956. }
  7957. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  7958. Type *t = base_type(string.type);
  7959. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  7960. return lb_emit_struct_ev(p, string, 0);
  7961. }
  7962. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  7963. Type *t = base_type(string.type);
  7964. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  7965. return lb_emit_struct_ev(p, string, 1);
  7966. }
  7967. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  7968. GB_ASSERT(is_type_cstring(value.type));
  7969. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7970. args[0] = lb_emit_conv(p, value, t_cstring);
  7971. return lb_emit_runtime_call(p, "cstring_len", args);
  7972. }
  7973. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  7974. Type *t = type_deref(array_ptr.type);
  7975. GB_ASSERT(is_type_array(t));
  7976. return lb_emit_struct_ep(p, array_ptr, 0);
  7977. }
  7978. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  7979. GB_ASSERT(is_type_slice(slice.type));
  7980. return lb_emit_struct_ev(p, slice, 0);
  7981. }
  7982. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  7983. GB_ASSERT(is_type_slice(slice.type));
  7984. return lb_emit_struct_ev(p, slice, 1);
  7985. }
  7986. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  7987. GB_ASSERT(is_type_dynamic_array(da.type));
  7988. return lb_emit_struct_ev(p, da, 0);
  7989. }
  7990. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  7991. GB_ASSERT(is_type_dynamic_array(da.type));
  7992. return lb_emit_struct_ev(p, da, 1);
  7993. }
  7994. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  7995. GB_ASSERT(is_type_dynamic_array(da.type));
  7996. return lb_emit_struct_ev(p, da, 2);
  7997. }
  7998. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  7999. GB_ASSERT(is_type_dynamic_array(da.type));
  8000. return lb_emit_struct_ev(p, da, 3);
  8001. }
  8002. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  8003. Type *t = base_type(value.type);
  8004. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  8005. init_map_internal_types(t);
  8006. Type *gst = t->Map.generated_struct_type;
  8007. i32 index = 1;
  8008. lbValue entries = lb_emit_struct_ev(p, value, index);
  8009. return entries;
  8010. }
  8011. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  8012. Type *t = base_type(type_deref(value.type));
  8013. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  8014. init_map_internal_types(t);
  8015. Type *gst = t->Map.generated_struct_type;
  8016. i32 index = 1;
  8017. lbValue entries = lb_emit_struct_ep(p, value, index);
  8018. return entries;
  8019. }
  8020. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  8021. lbValue entries = lb_map_entries(p, value);
  8022. return lb_dynamic_array_len(p, entries);
  8023. }
  8024. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  8025. lbValue entries = lb_map_entries(p, value);
  8026. return lb_dynamic_array_cap(p, entries);
  8027. }
  8028. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  8029. Type *t = base_type(value.type);
  8030. bool is_ptr = false;
  8031. if (is_type_pointer(t)) {
  8032. is_ptr = true;
  8033. t = base_type(type_deref(t));
  8034. }
  8035. if (t->Struct.soa_kind == StructSoa_Fixed) {
  8036. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  8037. }
  8038. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  8039. t->Struct.soa_kind == StructSoa_Dynamic);
  8040. isize n = 0;
  8041. Type *elem = base_type(t->Struct.soa_elem);
  8042. if (elem->kind == Type_Struct) {
  8043. n = cast(isize)elem->Struct.fields.count;
  8044. } else if (elem->kind == Type_Array) {
  8045. n = cast(isize)elem->Array.count;
  8046. } else {
  8047. GB_PANIC("Unreachable");
  8048. }
  8049. if (is_ptr) {
  8050. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  8051. return lb_emit_load(p, v);
  8052. }
  8053. return lb_emit_struct_ev(p, value, cast(i32)n);
  8054. }
  8055. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  8056. Type *t = base_type(value.type);
  8057. bool is_ptr = false;
  8058. if (is_type_pointer(t)) {
  8059. is_ptr = true;
  8060. t = base_type(type_deref(t));
  8061. }
  8062. if (t->Struct.soa_kind == StructSoa_Fixed) {
  8063. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  8064. }
  8065. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  8066. isize n = 0;
  8067. Type *elem = base_type(t->Struct.soa_elem);
  8068. if (elem->kind == Type_Struct) {
  8069. n = cast(isize)elem->Struct.fields.count+1;
  8070. } else if (elem->kind == Type_Array) {
  8071. n = cast(isize)elem->Array.count+1;
  8072. } else {
  8073. GB_PANIC("Unreachable");
  8074. }
  8075. if (is_ptr) {
  8076. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  8077. return lb_emit_load(p, v);
  8078. }
  8079. return lb_emit_struct_ev(p, value, cast(i32)n);
  8080. }
  8081. lbValue lb_soa_zip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  8082. GB_ASSERT(ce->args.count > 0);
  8083. auto slices = slice_make<lbValue>(temporary_allocator(), ce->args.count);
  8084. for_array(i, slices) {
  8085. Ast *arg = ce->args[i];
  8086. if (arg->kind == Ast_FieldValue) {
  8087. arg = arg->FieldValue.value;
  8088. }
  8089. slices[i] = lb_build_expr(p, arg);
  8090. }
  8091. lbValue len = lb_slice_len(p, slices[0]);
  8092. for (isize i = 1; i < slices.count; i++) {
  8093. lbValue other_len = lb_slice_len(p, slices[i]);
  8094. len = lb_emit_min(p, t_int, len, other_len);
  8095. }
  8096. GB_ASSERT(is_type_soa_struct(tv.type));
  8097. lbAddr res = lb_add_local_generated(p, tv.type, true);
  8098. for_array(i, slices) {
  8099. lbValue src = lb_slice_elem(p, slices[i]);
  8100. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  8101. lb_emit_store(p, dst, src);
  8102. }
  8103. lbValue len_dst = lb_emit_struct_ep(p, res.addr, cast(i32)slices.count);
  8104. lb_emit_store(p, len_dst, len);
  8105. return lb_addr_load(p, res);
  8106. }
  8107. lbValue lb_soa_unzip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  8108. GB_ASSERT(ce->args.count == 1);
  8109. lbValue arg = lb_build_expr(p, ce->args[0]);
  8110. Type *t = base_type(arg.type);
  8111. GB_ASSERT(is_type_soa_struct(t) && t->Struct.soa_kind == StructSoa_Slice);
  8112. lbValue len = lb_soa_struct_len(p, arg);
  8113. lbAddr res = lb_add_local_generated(p, tv.type, true);
  8114. if (is_type_tuple(tv.type)) {
  8115. lbValue rp = lb_addr_get_ptr(p, res);
  8116. for (i32 i = 0; i < cast(i32)(t->Struct.fields.count-1); i++) {
  8117. lbValue ptr = lb_emit_struct_ev(p, arg, i);
  8118. lbAddr dst = lb_addr(lb_emit_struct_ep(p, rp, i));
  8119. lb_fill_slice(p, dst, ptr, len);
  8120. }
  8121. } else {
  8122. GB_ASSERT(is_type_slice(tv.type));
  8123. lbValue ptr = lb_emit_struct_ev(p, arg, 0);
  8124. lb_fill_slice(p, res, ptr, len);
  8125. }
  8126. return lb_addr_load(p, res);
  8127. }
  8128. void lb_emit_try_lhs_rhs(lbProcedure *p, Ast *arg, TypeAndValue const &tv, lbValue *lhs_, lbValue *rhs_) {
  8129. lbValue lhs = {};
  8130. lbValue rhs = {};
  8131. lbValue value = lb_build_expr(p, arg);
  8132. if (is_type_tuple(value.type)) {
  8133. i32 n = cast(i32)(value.type->Tuple.variables.count-1);
  8134. if (value.type->Tuple.variables.count == 2) {
  8135. lhs = lb_emit_struct_ev(p, value, 0);
  8136. } else {
  8137. lbAddr lhs_addr = lb_add_local_generated(p, tv.type, false);
  8138. lbValue lhs_ptr = lb_addr_get_ptr(p, lhs_addr);
  8139. for (i32 i = 0; i < n; i++) {
  8140. lb_emit_store(p, lb_emit_struct_ep(p, lhs_ptr, i), lb_emit_struct_ev(p, value, i));
  8141. }
  8142. lhs = lb_addr_load(p, lhs_addr);
  8143. }
  8144. rhs = lb_emit_struct_ev(p, value, n);
  8145. } else {
  8146. rhs = value;
  8147. }
  8148. GB_ASSERT(rhs.value != nullptr);
  8149. if (lhs_) *lhs_ = lhs;
  8150. if (rhs_) *rhs_ = rhs;
  8151. }
  8152. lbValue lb_emit_try_has_value(lbProcedure *p, lbValue rhs) {
  8153. lbValue has_value = {};
  8154. if (is_type_boolean(rhs.type)) {
  8155. has_value = rhs;
  8156. } else {
  8157. GB_ASSERT_MSG(type_has_nil(rhs.type), "%s", type_to_string(rhs.type));
  8158. has_value = lb_emit_comp_against_nil(p, Token_CmpEq, rhs);
  8159. }
  8160. GB_ASSERT(has_value.value != nullptr);
  8161. return has_value;
  8162. }
  8163. // lbValue lb_emit_try(lbProcedure *p, Ast *arg, TypeAndValue const &tv) {
  8164. // lbValue lhs = {};
  8165. // lbValue rhs = {};
  8166. // lb_emit_try_lhs_rhs(p, arg, tv, &lhs, &rhs);
  8167. // lbBlock *return_block = lb_create_block(p, "try.return", false);
  8168. // lbBlock *continue_block = lb_create_block(p, "try.continue", false);
  8169. // lb_emit_if(p, lb_emit_try_has_value(p, rhs), continue_block, return_block);
  8170. // lb_start_block(p, return_block);
  8171. // {
  8172. // Type *proc_type = base_type(p->type);
  8173. // Type *results = proc_type->Proc.results;
  8174. // GB_ASSERT(results != nullptr && results->kind == Type_Tuple);
  8175. // TypeTuple *tuple = &results->Tuple;
  8176. // GB_ASSERT(tuple->variables.count != 0);
  8177. // Entity *end_entity = tuple->variables[tuple->variables.count-1];
  8178. // rhs = lb_emit_conv(p, rhs, end_entity->type);
  8179. // if (p->type->Proc.has_named_results) {
  8180. // GB_ASSERT(end_entity->token.string.len != 0);
  8181. // // NOTE(bill): store the named values before returning
  8182. // lbValue found = map_must_get(&p->module->values, hash_entity(end_entity));
  8183. // lb_emit_store(p, found, rhs);
  8184. // lb_build_return_stmt(p, {});
  8185. // } else {
  8186. // GB_ASSERT(tuple->variables.count == 1);
  8187. // lb_build_return_stmt_internal(p, rhs);
  8188. // }
  8189. // }
  8190. // lb_start_block(p, continue_block);
  8191. // if (tv.type != nullptr) {
  8192. // return lb_emit_conv(p, lhs, tv.type);
  8193. // }
  8194. // return {};
  8195. // }
  8196. lbValue lb_emit_or_else(lbProcedure *p, Ast *arg, Ast *else_expr, TypeAndValue const &tv) {
  8197. lbValue lhs = {};
  8198. lbValue rhs = {};
  8199. lb_emit_try_lhs_rhs(p, arg, tv, &lhs, &rhs);
  8200. LLVMValueRef incoming_values[2] = {};
  8201. LLVMBasicBlockRef incoming_blocks[2] = {};
  8202. GB_ASSERT(else_expr != nullptr);
  8203. lbBlock *then = lb_create_block(p, "or_else.then");
  8204. lbBlock *done = lb_create_block(p, "or_else.done"); // NOTE(bill): Append later
  8205. lbBlock *else_ = lb_create_block(p, "or_else.else");
  8206. lb_emit_if(p, lb_emit_try_has_value(p, rhs), then, else_);
  8207. lb_start_block(p, then);
  8208. Type *type = default_type(tv.type);
  8209. incoming_values[0] = lb_emit_conv(p, lhs, type).value;
  8210. lb_emit_jump(p, done);
  8211. lb_start_block(p, else_);
  8212. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, else_expr), type).value;
  8213. lb_emit_jump(p, done);
  8214. lb_start_block(p, done);
  8215. lbValue res = {};
  8216. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8217. res.type = type;
  8218. GB_ASSERT(p->curr_block->preds.count >= 2);
  8219. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8220. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8221. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8222. return res;
  8223. }
  8224. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  8225. ast_node(ce, CallExpr, expr);
  8226. switch (id) {
  8227. case BuiltinProc_DIRECTIVE: {
  8228. ast_node(bd, BasicDirective, ce->proc);
  8229. String name = bd->name.string;
  8230. GB_ASSERT(name == "location");
  8231. String procedure = p->entity->token.string;
  8232. TokenPos pos = ast_token(ce->proc).pos;
  8233. if (ce->args.count > 0) {
  8234. Ast *ident = unselector_expr(ce->args[0]);
  8235. GB_ASSERT(ident->kind == Ast_Ident);
  8236. Entity *e = entity_of_node(ident);
  8237. GB_ASSERT(e != nullptr);
  8238. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  8239. procedure = e->parent_proc_decl->entity->token.string;
  8240. } else {
  8241. procedure = str_lit("");
  8242. }
  8243. pos = e->token.pos;
  8244. }
  8245. return lb_emit_source_code_location(p, procedure, pos);
  8246. }
  8247. case BuiltinProc_type_info_of: {
  8248. Ast *arg = ce->args[0];
  8249. TypeAndValue tav = type_and_value_of_expr(arg);
  8250. if (tav.mode == Addressing_Type) {
  8251. Type *t = default_type(type_of_expr(arg));
  8252. return lb_type_info(p->module, t);
  8253. }
  8254. GB_ASSERT(is_type_typeid(tav.type));
  8255. auto args = array_make<lbValue>(permanent_allocator(), 1);
  8256. args[0] = lb_build_expr(p, arg);
  8257. return lb_emit_runtime_call(p, "__type_info_of", args);
  8258. }
  8259. case BuiltinProc_typeid_of: {
  8260. Ast *arg = ce->args[0];
  8261. TypeAndValue tav = type_and_value_of_expr(arg);
  8262. GB_ASSERT(tav.mode == Addressing_Type);
  8263. Type *t = default_type(type_of_expr(arg));
  8264. return lb_typeid(p->module, t);
  8265. }
  8266. case BuiltinProc_len: {
  8267. lbValue v = lb_build_expr(p, ce->args[0]);
  8268. Type *t = base_type(v.type);
  8269. if (is_type_pointer(t)) {
  8270. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  8271. v = lb_emit_load(p, v);
  8272. t = type_deref(t);
  8273. }
  8274. if (is_type_cstring(t)) {
  8275. return lb_cstring_len(p, v);
  8276. } else if (is_type_string(t)) {
  8277. return lb_string_len(p, v);
  8278. } else if (is_type_array(t)) {
  8279. GB_PANIC("Array lengths are constant");
  8280. } else if (is_type_slice(t)) {
  8281. return lb_slice_len(p, v);
  8282. } else if (is_type_dynamic_array(t)) {
  8283. return lb_dynamic_array_len(p, v);
  8284. } else if (is_type_map(t)) {
  8285. return lb_map_len(p, v);
  8286. } else if (is_type_soa_struct(t)) {
  8287. return lb_soa_struct_len(p, v);
  8288. }
  8289. GB_PANIC("Unreachable");
  8290. break;
  8291. }
  8292. case BuiltinProc_cap: {
  8293. lbValue v = lb_build_expr(p, ce->args[0]);
  8294. Type *t = base_type(v.type);
  8295. if (is_type_pointer(t)) {
  8296. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  8297. v = lb_emit_load(p, v);
  8298. t = type_deref(t);
  8299. }
  8300. if (is_type_string(t)) {
  8301. GB_PANIC("Unreachable");
  8302. } else if (is_type_array(t)) {
  8303. GB_PANIC("Array lengths are constant");
  8304. } else if (is_type_slice(t)) {
  8305. return lb_slice_len(p, v);
  8306. } else if (is_type_dynamic_array(t)) {
  8307. return lb_dynamic_array_cap(p, v);
  8308. } else if (is_type_map(t)) {
  8309. return lb_map_cap(p, v);
  8310. } else if (is_type_soa_struct(t)) {
  8311. return lb_soa_struct_cap(p, v);
  8312. }
  8313. GB_PANIC("Unreachable");
  8314. break;
  8315. }
  8316. case BuiltinProc_swizzle: {
  8317. isize index_count = ce->args.count-1;
  8318. if (is_type_simd_vector(tv.type)) {
  8319. lbValue vec = lb_build_expr(p, ce->args[0]);
  8320. if (index_count == 0) {
  8321. return vec;
  8322. }
  8323. unsigned mask_len = cast(unsigned)index_count;
  8324. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  8325. for (isize i = 1; i < ce->args.count; i++) {
  8326. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  8327. GB_ASSERT(is_type_integer(tv.type));
  8328. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  8329. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  8330. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  8331. }
  8332. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  8333. LLVMValueRef v1 = vec.value;
  8334. LLVMValueRef v2 = vec.value;
  8335. lbValue res = {};
  8336. res.type = tv.type;
  8337. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  8338. return res;
  8339. }
  8340. lbAddr addr = lb_build_addr(p, ce->args[0]);
  8341. if (index_count == 0) {
  8342. return lb_addr_load(p, addr);
  8343. }
  8344. lbValue src = lb_addr_get_ptr(p, addr);
  8345. // TODO(bill): Should this be zeroed or not?
  8346. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  8347. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  8348. for (i32 i = 1; i < ce->args.count; i++) {
  8349. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  8350. GB_ASSERT(is_type_integer(tv.type));
  8351. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  8352. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  8353. i32 dst_index = i-1;
  8354. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  8355. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  8356. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  8357. }
  8358. return lb_addr_load(p, dst);
  8359. }
  8360. case BuiltinProc_complex: {
  8361. lbValue real = lb_build_expr(p, ce->args[0]);
  8362. lbValue imag = lb_build_expr(p, ce->args[1]);
  8363. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  8364. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  8365. Type *ft = base_complex_elem_type(tv.type);
  8366. real = lb_emit_conv(p, real, ft);
  8367. imag = lb_emit_conv(p, imag, ft);
  8368. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  8369. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  8370. return lb_emit_load(p, dst);
  8371. }
  8372. case BuiltinProc_quaternion: {
  8373. lbValue real = lb_build_expr(p, ce->args[0]);
  8374. lbValue imag = lb_build_expr(p, ce->args[1]);
  8375. lbValue jmag = lb_build_expr(p, ce->args[2]);
  8376. lbValue kmag = lb_build_expr(p, ce->args[3]);
  8377. // @QuaternionLayout
  8378. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  8379. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  8380. Type *ft = base_complex_elem_type(tv.type);
  8381. real = lb_emit_conv(p, real, ft);
  8382. imag = lb_emit_conv(p, imag, ft);
  8383. jmag = lb_emit_conv(p, jmag, ft);
  8384. kmag = lb_emit_conv(p, kmag, ft);
  8385. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  8386. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  8387. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  8388. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  8389. return lb_emit_load(p, dst);
  8390. }
  8391. case BuiltinProc_real: {
  8392. lbValue val = lb_build_expr(p, ce->args[0]);
  8393. if (is_type_complex(val.type)) {
  8394. lbValue real = lb_emit_struct_ev(p, val, 0);
  8395. return lb_emit_conv(p, real, tv.type);
  8396. } else if (is_type_quaternion(val.type)) {
  8397. // @QuaternionLayout
  8398. lbValue real = lb_emit_struct_ev(p, val, 3);
  8399. return lb_emit_conv(p, real, tv.type);
  8400. }
  8401. GB_PANIC("invalid type for real");
  8402. return {};
  8403. }
  8404. case BuiltinProc_imag: {
  8405. lbValue val = lb_build_expr(p, ce->args[0]);
  8406. if (is_type_complex(val.type)) {
  8407. lbValue imag = lb_emit_struct_ev(p, val, 1);
  8408. return lb_emit_conv(p, imag, tv.type);
  8409. } else if (is_type_quaternion(val.type)) {
  8410. // @QuaternionLayout
  8411. lbValue imag = lb_emit_struct_ev(p, val, 0);
  8412. return lb_emit_conv(p, imag, tv.type);
  8413. }
  8414. GB_PANIC("invalid type for imag");
  8415. return {};
  8416. }
  8417. case BuiltinProc_jmag: {
  8418. lbValue val = lb_build_expr(p, ce->args[0]);
  8419. if (is_type_quaternion(val.type)) {
  8420. // @QuaternionLayout
  8421. lbValue imag = lb_emit_struct_ev(p, val, 1);
  8422. return lb_emit_conv(p, imag, tv.type);
  8423. }
  8424. GB_PANIC("invalid type for jmag");
  8425. return {};
  8426. }
  8427. case BuiltinProc_kmag: {
  8428. lbValue val = lb_build_expr(p, ce->args[0]);
  8429. if (is_type_quaternion(val.type)) {
  8430. // @QuaternionLayout
  8431. lbValue imag = lb_emit_struct_ev(p, val, 2);
  8432. return lb_emit_conv(p, imag, tv.type);
  8433. }
  8434. GB_PANIC("invalid type for kmag");
  8435. return {};
  8436. }
  8437. case BuiltinProc_conj: {
  8438. lbValue val = lb_build_expr(p, ce->args[0]);
  8439. lbValue res = {};
  8440. Type *t = val.type;
  8441. if (is_type_complex(t)) {
  8442. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  8443. lbValue real = lb_emit_struct_ev(p, val, 0);
  8444. lbValue imag = lb_emit_struct_ev(p, val, 1);
  8445. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  8446. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  8447. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  8448. } else if (is_type_quaternion(t)) {
  8449. // @QuaternionLayout
  8450. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  8451. lbValue real = lb_emit_struct_ev(p, val, 3);
  8452. lbValue imag = lb_emit_struct_ev(p, val, 0);
  8453. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  8454. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  8455. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  8456. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  8457. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  8458. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  8459. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  8460. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  8461. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  8462. }
  8463. return lb_emit_load(p, res);
  8464. }
  8465. case BuiltinProc_expand_to_tuple: {
  8466. lbValue val = lb_build_expr(p, ce->args[0]);
  8467. Type *t = base_type(val.type);
  8468. if (!is_type_tuple(tv.type)) {
  8469. if (t->kind == Type_Struct) {
  8470. GB_ASSERT(t->Struct.fields.count == 1);
  8471. return lb_emit_struct_ev(p, val, 0);
  8472. } else if (t->kind == Type_Array) {
  8473. GB_ASSERT(t->Array.count == 1);
  8474. return lb_emit_array_epi(p, val, 0);
  8475. } else {
  8476. GB_PANIC("Unknown type of expand_to_tuple");
  8477. }
  8478. }
  8479. GB_ASSERT(is_type_tuple(tv.type));
  8480. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  8481. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  8482. if (t->kind == Type_Struct) {
  8483. for_array(src_index, t->Struct.fields) {
  8484. Entity *field = t->Struct.fields[src_index];
  8485. i32 field_index = field->Variable.field_index;
  8486. lbValue f = lb_emit_struct_ev(p, val, field_index);
  8487. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  8488. lb_emit_store(p, ep, f);
  8489. }
  8490. } else if (is_type_array_like(t)) {
  8491. // TODO(bill): Clean-up this code
  8492. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  8493. i32 n = cast(i32)get_array_type_count(t);
  8494. for (i32 i = 0; i < n; i++) {
  8495. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  8496. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  8497. lb_emit_store(p, ep, f);
  8498. }
  8499. } else {
  8500. GB_PANIC("Unknown type of expand_to_tuple");
  8501. }
  8502. return lb_emit_load(p, tuple);
  8503. }
  8504. case BuiltinProc_min: {
  8505. Type *t = type_of_expr(expr);
  8506. if (ce->args.count == 2) {
  8507. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  8508. } else {
  8509. lbValue x = lb_build_expr(p, ce->args[0]);
  8510. for (isize i = 1; i < ce->args.count; i++) {
  8511. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  8512. }
  8513. return x;
  8514. }
  8515. }
  8516. case BuiltinProc_max: {
  8517. Type *t = type_of_expr(expr);
  8518. if (ce->args.count == 2) {
  8519. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  8520. } else {
  8521. lbValue x = lb_build_expr(p, ce->args[0]);
  8522. for (isize i = 1; i < ce->args.count; i++) {
  8523. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  8524. }
  8525. return x;
  8526. }
  8527. }
  8528. case BuiltinProc_abs: {
  8529. lbValue x = lb_build_expr(p, ce->args[0]);
  8530. Type *t = x.type;
  8531. if (is_type_unsigned(t)) {
  8532. return x;
  8533. }
  8534. if (is_type_quaternion(t)) {
  8535. i64 sz = 8*type_size_of(t);
  8536. auto args = array_make<lbValue>(permanent_allocator(), 1);
  8537. args[0] = x;
  8538. switch (sz) {
  8539. case 64: return lb_emit_runtime_call(p, "abs_quaternion64", args);
  8540. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  8541. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  8542. }
  8543. GB_PANIC("Unknown complex type");
  8544. } else if (is_type_complex(t)) {
  8545. i64 sz = 8*type_size_of(t);
  8546. auto args = array_make<lbValue>(permanent_allocator(), 1);
  8547. args[0] = x;
  8548. switch (sz) {
  8549. case 32: return lb_emit_runtime_call(p, "abs_complex32", args);
  8550. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  8551. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  8552. }
  8553. GB_PANIC("Unknown complex type");
  8554. }
  8555. lbValue zero = lb_const_nil(p->module, t);
  8556. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  8557. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  8558. return lb_emit_select(p, cond, neg, x);
  8559. }
  8560. case BuiltinProc_clamp:
  8561. return lb_emit_clamp(p, type_of_expr(expr),
  8562. lb_build_expr(p, ce->args[0]),
  8563. lb_build_expr(p, ce->args[1]),
  8564. lb_build_expr(p, ce->args[2]));
  8565. case BuiltinProc_soa_zip:
  8566. return lb_soa_zip(p, ce, tv);
  8567. case BuiltinProc_soa_unzip:
  8568. return lb_soa_unzip(p, ce, tv);
  8569. case BuiltinProc_or_else:
  8570. return lb_emit_or_else(p, ce->args[0], ce->args[1], tv);
  8571. // "Intrinsics"
  8572. case BuiltinProc_alloca:
  8573. {
  8574. lbValue sz = lb_build_expr(p, ce->args[0]);
  8575. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  8576. lbValue res = {};
  8577. res.type = t_u8_ptr;
  8578. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  8579. LLVMSetAlignment(res.value, cast(unsigned)al);
  8580. return res;
  8581. }
  8582. case BuiltinProc_cpu_relax:
  8583. if (build_context.metrics.arch == TargetArch_386 ||
  8584. build_context.metrics.arch == TargetArch_amd64) {
  8585. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  8586. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  8587. cast(char *)"pause", 5,
  8588. cast(char *)"", 0,
  8589. /*HasSideEffects*/true, /*IsAlignStack*/false,
  8590. LLVMInlineAsmDialectATT
  8591. );
  8592. GB_ASSERT(the_asm != nullptr);
  8593. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  8594. } else if (build_context.metrics.arch == TargetArch_arm64) {
  8595. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  8596. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  8597. cast(char *)"yield", 5,
  8598. cast(char *)"", 0,
  8599. /*HasSideEffects*/true, /*IsAlignStack*/false,
  8600. LLVMInlineAsmDialectATT
  8601. );
  8602. GB_ASSERT(the_asm != nullptr);
  8603. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  8604. }
  8605. return {};
  8606. case BuiltinProc_debug_trap:
  8607. case BuiltinProc_trap:
  8608. {
  8609. char const *name = nullptr;
  8610. switch (id) {
  8611. case BuiltinProc_debug_trap: name = "llvm.debugtrap"; break;
  8612. case BuiltinProc_trap: name = "llvm.trap"; break;
  8613. }
  8614. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8615. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  8616. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, nullptr, 0);
  8617. LLVMBuildCall(p->builder, ip, nullptr, 0, "");
  8618. if (id == BuiltinProc_trap) {
  8619. LLVMBuildUnreachable(p->builder);
  8620. }
  8621. return {};
  8622. }
  8623. case BuiltinProc_read_cycle_counter:
  8624. {
  8625. char const *name = "llvm.readcyclecounter";
  8626. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8627. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  8628. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, nullptr, 0);
  8629. lbValue res = {};
  8630. res.value = LLVMBuildCall(p->builder, ip, nullptr, 0, "");
  8631. res.type = tv.type;
  8632. return res;
  8633. }
  8634. case BuiltinProc_count_trailing_zeros:
  8635. return lb_emit_count_trailing_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  8636. case BuiltinProc_count_leading_zeros:
  8637. return lb_emit_count_leading_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  8638. case BuiltinProc_count_ones:
  8639. return lb_emit_count_ones(p, lb_build_expr(p, ce->args[0]), tv.type);
  8640. case BuiltinProc_count_zeros:
  8641. return lb_emit_count_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  8642. case BuiltinProc_reverse_bits:
  8643. return lb_emit_reverse_bits(p, lb_build_expr(p, ce->args[0]), tv.type);
  8644. case BuiltinProc_byte_swap:
  8645. {
  8646. lbValue x = lb_build_expr(p, ce->args[0]);
  8647. x = lb_emit_conv(p, x, tv.type);
  8648. return lb_emit_byte_swap(p, x, tv.type);
  8649. }
  8650. case BuiltinProc_overflow_add:
  8651. case BuiltinProc_overflow_sub:
  8652. case BuiltinProc_overflow_mul:
  8653. {
  8654. Type *main_type = tv.type;
  8655. Type *type = main_type;
  8656. if (is_type_tuple(main_type)) {
  8657. type = main_type->Tuple.variables[0]->type;
  8658. }
  8659. lbValue x = lb_build_expr(p, ce->args[0]);
  8660. lbValue y = lb_build_expr(p, ce->args[1]);
  8661. x = lb_emit_conv(p, x, type);
  8662. y = lb_emit_conv(p, y, type);
  8663. char const *name = nullptr;
  8664. if (is_type_unsigned(type)) {
  8665. switch (id) {
  8666. case BuiltinProc_overflow_add: name = "llvm.uadd.with.overflow"; break;
  8667. case BuiltinProc_overflow_sub: name = "llvm.usub.with.overflow"; break;
  8668. case BuiltinProc_overflow_mul: name = "llvm.umul.with.overflow"; break;
  8669. }
  8670. } else {
  8671. switch (id) {
  8672. case BuiltinProc_overflow_add: name = "llvm.sadd.with.overflow"; break;
  8673. case BuiltinProc_overflow_sub: name = "llvm.ssub.with.overflow"; break;
  8674. case BuiltinProc_overflow_mul: name = "llvm.smul.with.overflow"; break;
  8675. }
  8676. }
  8677. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8678. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8679. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8680. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8681. LLVMValueRef args[2] = {};
  8682. args[0] = x.value;
  8683. args[1] = y.value;
  8684. lbValue res = {};
  8685. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8686. if (is_type_tuple(main_type)) {
  8687. Type *res_type = nullptr;
  8688. gbAllocator a = permanent_allocator();
  8689. res_type = alloc_type_tuple();
  8690. array_init(&res_type->Tuple.variables, a, 2);
  8691. res_type->Tuple.variables[0] = alloc_entity_field(nullptr, blank_token, type, false, 0);
  8692. res_type->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  8693. res.type = res_type;
  8694. } else {
  8695. res.value = LLVMBuildExtractValue(p->builder, res.value, 0, "");
  8696. res.type = type;
  8697. }
  8698. return res;
  8699. }
  8700. case BuiltinProc_sqrt:
  8701. {
  8702. Type *type = tv.type;
  8703. lbValue x = lb_build_expr(p, ce->args[0]);
  8704. x = lb_emit_conv(p, x, type);
  8705. char const *name = "llvm.sqrt";
  8706. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8707. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8708. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8709. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8710. LLVMValueRef args[1] = {};
  8711. args[0] = x.value;
  8712. lbValue res = {};
  8713. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8714. res.type = type;
  8715. return res;
  8716. }
  8717. case BuiltinProc_mem_copy:
  8718. case BuiltinProc_mem_copy_non_overlapping:
  8719. {
  8720. lbValue dst = lb_build_expr(p, ce->args[0]);
  8721. lbValue src = lb_build_expr(p, ce->args[1]);
  8722. lbValue len = lb_build_expr(p, ce->args[2]);
  8723. dst = lb_emit_conv(p, dst, t_rawptr);
  8724. src = lb_emit_conv(p, src, t_rawptr);
  8725. len = lb_emit_conv(p, len, t_int);
  8726. bool is_inlinable = false;
  8727. if (ce->args[2]->tav.mode == Addressing_Constant) {
  8728. ExactValue ev = exact_value_to_integer(ce->args[2]->tav.value);
  8729. i64 const_len = exact_value_to_i64(ev);
  8730. // TODO(bill): Determine when it is better to do the `*.inline` versions
  8731. if (const_len <= 4*build_context.word_size) {
  8732. is_inlinable = true;
  8733. }
  8734. }
  8735. char const *name = nullptr;
  8736. switch (id) {
  8737. case BuiltinProc_mem_copy:
  8738. if (is_inlinable) {
  8739. name = "llvm.memmove.inline";
  8740. } else {
  8741. name = "llvm.memmove";
  8742. }
  8743. break;
  8744. case BuiltinProc_mem_copy_non_overlapping:
  8745. if (is_inlinable) {
  8746. name = "llvm.memcpy.line";
  8747. } else {
  8748. name = "llvm.memcpy";
  8749. }
  8750. break;
  8751. }
  8752. LLVMTypeRef types[3] = {
  8753. lb_type(p->module, t_rawptr),
  8754. lb_type(p->module, t_rawptr),
  8755. lb_type(p->module, t_int)
  8756. };
  8757. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8758. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s.%s.%s", name, LLVMPrintTypeToString(types[0]), LLVMPrintTypeToString(types[1]), LLVMPrintTypeToString(types[2]));
  8759. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8760. LLVMValueRef args[4] = {};
  8761. args[0] = dst.value;
  8762. args[1] = src.value;
  8763. args[2] = len.value;
  8764. args[3] = LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, false); // is_volatile parameter
  8765. LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8766. return {};
  8767. }
  8768. case BuiltinProc_mem_zero:
  8769. {
  8770. lbValue ptr = lb_build_expr(p, ce->args[0]);
  8771. lbValue len = lb_build_expr(p, ce->args[1]);
  8772. ptr = lb_emit_conv(p, ptr, t_rawptr);
  8773. len = lb_emit_conv(p, len, t_int);
  8774. unsigned alignment = 1;
  8775. lb_mem_zero_ptr_internal(p, ptr.value, len.value, alignment);
  8776. return {};
  8777. }
  8778. case BuiltinProc_ptr_offset:
  8779. {
  8780. lbValue ptr = lb_build_expr(p, ce->args[0]);
  8781. lbValue len = lb_build_expr(p, ce->args[1]);
  8782. len = lb_emit_conv(p, len, t_int);
  8783. LLVMValueRef indices[1] = {
  8784. len.value,
  8785. };
  8786. lbValue res = {};
  8787. res.type = tv.type;
  8788. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, gb_count_of(indices), "");
  8789. return res;
  8790. }
  8791. case BuiltinProc_ptr_sub:
  8792. {
  8793. lbValue ptr0 = lb_build_expr(p, ce->args[0]);
  8794. lbValue ptr1 = lb_build_expr(p, ce->args[1]);
  8795. LLVMTypeRef type_int = lb_type(p->module, t_int);
  8796. LLVMValueRef diff = LLVMBuildPtrDiff(p->builder, ptr0.value, ptr1.value, "");
  8797. diff = LLVMBuildIntCast2(p->builder, diff, type_int, /*signed*/true, "");
  8798. lbValue res = {};
  8799. res.type = t_int;
  8800. res.value = diff;
  8801. return res;
  8802. }
  8803. case BuiltinProc_atomic_fence:
  8804. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  8805. return {};
  8806. case BuiltinProc_atomic_fence_acq:
  8807. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  8808. return {};
  8809. case BuiltinProc_atomic_fence_rel:
  8810. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  8811. return {};
  8812. case BuiltinProc_atomic_fence_acqrel:
  8813. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  8814. return {};
  8815. case BuiltinProc_volatile_store:
  8816. case BuiltinProc_atomic_store:
  8817. case BuiltinProc_atomic_store_rel:
  8818. case BuiltinProc_atomic_store_relaxed:
  8819. case BuiltinProc_atomic_store_unordered: {
  8820. lbValue dst = lb_build_expr(p, ce->args[0]);
  8821. lbValue val = lb_build_expr(p, ce->args[1]);
  8822. val = lb_emit_conv(p, val, type_deref(dst.type));
  8823. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  8824. switch (id) {
  8825. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  8826. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  8827. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  8828. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  8829. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  8830. }
  8831. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  8832. return {};
  8833. }
  8834. case BuiltinProc_volatile_load:
  8835. case BuiltinProc_atomic_load:
  8836. case BuiltinProc_atomic_load_acq:
  8837. case BuiltinProc_atomic_load_relaxed:
  8838. case BuiltinProc_atomic_load_unordered: {
  8839. lbValue dst = lb_build_expr(p, ce->args[0]);
  8840. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  8841. switch (id) {
  8842. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  8843. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  8844. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  8845. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  8846. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  8847. }
  8848. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  8849. lbValue res = {};
  8850. res.value = instr;
  8851. res.type = type_deref(dst.type);
  8852. return res;
  8853. }
  8854. case BuiltinProc_atomic_add:
  8855. case BuiltinProc_atomic_add_acq:
  8856. case BuiltinProc_atomic_add_rel:
  8857. case BuiltinProc_atomic_add_acqrel:
  8858. case BuiltinProc_atomic_add_relaxed:
  8859. case BuiltinProc_atomic_sub:
  8860. case BuiltinProc_atomic_sub_acq:
  8861. case BuiltinProc_atomic_sub_rel:
  8862. case BuiltinProc_atomic_sub_acqrel:
  8863. case BuiltinProc_atomic_sub_relaxed:
  8864. case BuiltinProc_atomic_and:
  8865. case BuiltinProc_atomic_and_acq:
  8866. case BuiltinProc_atomic_and_rel:
  8867. case BuiltinProc_atomic_and_acqrel:
  8868. case BuiltinProc_atomic_and_relaxed:
  8869. case BuiltinProc_atomic_nand:
  8870. case BuiltinProc_atomic_nand_acq:
  8871. case BuiltinProc_atomic_nand_rel:
  8872. case BuiltinProc_atomic_nand_acqrel:
  8873. case BuiltinProc_atomic_nand_relaxed:
  8874. case BuiltinProc_atomic_or:
  8875. case BuiltinProc_atomic_or_acq:
  8876. case BuiltinProc_atomic_or_rel:
  8877. case BuiltinProc_atomic_or_acqrel:
  8878. case BuiltinProc_atomic_or_relaxed:
  8879. case BuiltinProc_atomic_xor:
  8880. case BuiltinProc_atomic_xor_acq:
  8881. case BuiltinProc_atomic_xor_rel:
  8882. case BuiltinProc_atomic_xor_acqrel:
  8883. case BuiltinProc_atomic_xor_relaxed:
  8884. case BuiltinProc_atomic_xchg:
  8885. case BuiltinProc_atomic_xchg_acq:
  8886. case BuiltinProc_atomic_xchg_rel:
  8887. case BuiltinProc_atomic_xchg_acqrel:
  8888. case BuiltinProc_atomic_xchg_relaxed: {
  8889. lbValue dst = lb_build_expr(p, ce->args[0]);
  8890. lbValue val = lb_build_expr(p, ce->args[1]);
  8891. val = lb_emit_conv(p, val, type_deref(dst.type));
  8892. LLVMAtomicRMWBinOp op = {};
  8893. LLVMAtomicOrdering ordering = {};
  8894. switch (id) {
  8895. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8896. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  8897. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  8898. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8899. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  8900. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8901. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  8902. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  8903. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8904. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  8905. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8906. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  8907. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  8908. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8909. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  8910. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8911. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  8912. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  8913. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8914. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  8915. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8916. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  8917. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  8918. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8919. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  8920. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8921. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  8922. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  8923. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8924. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  8925. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8926. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  8927. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  8928. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8929. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  8930. }
  8931. lbValue res = {};
  8932. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  8933. res.type = tv.type;
  8934. return res;
  8935. }
  8936. case BuiltinProc_atomic_cxchg:
  8937. case BuiltinProc_atomic_cxchg_acq:
  8938. case BuiltinProc_atomic_cxchg_rel:
  8939. case BuiltinProc_atomic_cxchg_acqrel:
  8940. case BuiltinProc_atomic_cxchg_relaxed:
  8941. case BuiltinProc_atomic_cxchg_failrelaxed:
  8942. case BuiltinProc_atomic_cxchg_failacq:
  8943. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  8944. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  8945. case BuiltinProc_atomic_cxchgweak:
  8946. case BuiltinProc_atomic_cxchgweak_acq:
  8947. case BuiltinProc_atomic_cxchgweak_rel:
  8948. case BuiltinProc_atomic_cxchgweak_acqrel:
  8949. case BuiltinProc_atomic_cxchgweak_relaxed:
  8950. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  8951. case BuiltinProc_atomic_cxchgweak_failacq:
  8952. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  8953. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  8954. Type *type = expr->tav.type;
  8955. lbValue address = lb_build_expr(p, ce->args[0]);
  8956. Type *elem = type_deref(address.type);
  8957. lbValue old_value = lb_build_expr(p, ce->args[1]);
  8958. lbValue new_value = lb_build_expr(p, ce->args[2]);
  8959. old_value = lb_emit_conv(p, old_value, elem);
  8960. new_value = lb_emit_conv(p, new_value, elem);
  8961. LLVMAtomicOrdering success_ordering = {};
  8962. LLVMAtomicOrdering failure_ordering = {};
  8963. LLVMBool weak = false;
  8964. switch (id) {
  8965. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8966. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8967. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8968. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8969. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  8970. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  8971. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  8972. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  8973. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  8974. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8975. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  8976. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  8977. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  8978. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  8979. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  8980. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  8981. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  8982. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  8983. }
  8984. // TODO(bill): Figure out how to make it weak
  8985. LLVMBool single_threaded = weak;
  8986. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  8987. p->builder, address.value,
  8988. old_value.value, new_value.value,
  8989. success_ordering,
  8990. failure_ordering,
  8991. single_threaded
  8992. );
  8993. if (tv.type->kind == Type_Tuple) {
  8994. Type *fix_typed = alloc_type_tuple();
  8995. array_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  8996. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  8997. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  8998. lbValue res = {};
  8999. res.value = value;
  9000. res.type = fix_typed;
  9001. return res;
  9002. } else {
  9003. lbValue res = {};
  9004. res.value = LLVMBuildExtractValue(p->builder, value, 0, "");
  9005. res.type = tv.type;
  9006. return res;
  9007. }
  9008. }
  9009. case BuiltinProc_type_equal_proc:
  9010. return lb_get_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  9011. case BuiltinProc_type_hasher_proc:
  9012. return lb_get_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  9013. case BuiltinProc_fixed_point_mul:
  9014. case BuiltinProc_fixed_point_div:
  9015. case BuiltinProc_fixed_point_mul_sat:
  9016. case BuiltinProc_fixed_point_div_sat:
  9017. {
  9018. bool do_bswap = is_type_different_to_arch_endianness(tv.type);
  9019. Type *platform_type = integer_endian_type_to_platform_type(tv.type);
  9020. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), platform_type);
  9021. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), platform_type);
  9022. lbValue scale = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), t_i32);
  9023. char const *name = nullptr;
  9024. if (is_type_unsigned(tv.type)) {
  9025. switch (id) {
  9026. case BuiltinProc_fixed_point_mul: name = "llvm.umul.fix"; break;
  9027. case BuiltinProc_fixed_point_div: name = "llvm.udiv.fix"; break;
  9028. case BuiltinProc_fixed_point_mul_sat: name = "llvm.umul.fix.sat"; break;
  9029. case BuiltinProc_fixed_point_div_sat: name = "llvm.udiv.fix.sat"; break;
  9030. }
  9031. } else {
  9032. switch (id) {
  9033. case BuiltinProc_fixed_point_mul: name = "llvm.smul.fix"; break;
  9034. case BuiltinProc_fixed_point_div: name = "llvm.sdiv.fix"; break;
  9035. case BuiltinProc_fixed_point_mul_sat: name = "llvm.smul.fix.sat"; break;
  9036. case BuiltinProc_fixed_point_div_sat: name = "llvm.sdiv.fix.sat"; break;
  9037. }
  9038. }
  9039. GB_ASSERT(name != nullptr);
  9040. LLVMTypeRef types[1] = {lb_type(p->module, platform_type)};
  9041. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  9042. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  9043. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  9044. lbValue res = {};
  9045. LLVMValueRef args[3] = {};
  9046. args[0] = x.value;
  9047. args[1] = y.value;
  9048. args[2] = scale.value;
  9049. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  9050. res.type = platform_type;
  9051. return lb_emit_conv(p, res, tv.type);
  9052. }
  9053. case BuiltinProc_expect:
  9054. {
  9055. Type *t = default_type(tv.type);
  9056. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t);
  9057. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t);
  9058. char const *name = "llvm.expect";
  9059. LLVMTypeRef types[1] = {lb_type(p->module, t)};
  9060. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  9061. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  9062. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  9063. lbValue res = {};
  9064. LLVMValueRef args[2] = {};
  9065. args[0] = x.value;
  9066. args[1] = y.value;
  9067. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  9068. res.type = t;
  9069. return lb_emit_conv(p, res, t);
  9070. }
  9071. }
  9072. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  9073. return {};
  9074. }
  9075. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  9076. switch (param_value.kind) {
  9077. case ParameterValue_Constant:
  9078. if (is_type_constant_type(parameter_type)) {
  9079. auto res = lb_const_value(p->module, parameter_type, param_value.value);
  9080. return res;
  9081. } else {
  9082. ExactValue ev = param_value.value;
  9083. lbValue arg = {};
  9084. Type *type = type_of_expr(param_value.original_ast_expr);
  9085. if (type != nullptr) {
  9086. arg = lb_const_value(p->module, type, ev);
  9087. } else {
  9088. arg = lb_const_value(p->module, parameter_type, param_value.value);
  9089. }
  9090. return lb_emit_conv(p, arg, parameter_type);
  9091. }
  9092. case ParameterValue_Nil:
  9093. return lb_const_nil(p->module, parameter_type);
  9094. case ParameterValue_Location:
  9095. {
  9096. String proc_name = {};
  9097. if (p->entity != nullptr) {
  9098. proc_name = p->entity->token.string;
  9099. }
  9100. return lb_emit_source_code_location(p, proc_name, pos);
  9101. }
  9102. case ParameterValue_Value:
  9103. return lb_build_expr(p, param_value.ast_value);
  9104. }
  9105. return lb_const_nil(p->module, parameter_type);
  9106. }
  9107. lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr);
  9108. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  9109. expr = unparen_expr(expr);
  9110. ast_node(ce, CallExpr, expr);
  9111. if (ce->sce_temp_data) {
  9112. return *(lbValue *)ce->sce_temp_data;
  9113. }
  9114. lbValue res = lb_build_call_expr_internal(p, expr);
  9115. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  9116. GB_ASSERT(is_type_tuple(res.type));
  9117. GB_ASSERT(res.type->Tuple.variables.count == 2);
  9118. return lb_emit_struct_ev(p, res, 0);
  9119. }
  9120. return res;
  9121. }
  9122. lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr) {
  9123. lbModule *m = p->module;
  9124. TypeAndValue tv = type_and_value_of_expr(expr);
  9125. ast_node(ce, CallExpr, expr);
  9126. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  9127. AddressingMode proc_mode = proc_tv.mode;
  9128. if (proc_mode == Addressing_Type) {
  9129. GB_ASSERT(ce->args.count == 1);
  9130. lbValue x = lb_build_expr(p, ce->args[0]);
  9131. lbValue y = lb_emit_conv(p, x, tv.type);
  9132. return y;
  9133. }
  9134. Ast *pexpr = unparen_expr(ce->proc);
  9135. if (proc_mode == Addressing_Builtin) {
  9136. Entity *e = entity_of_node(pexpr);
  9137. BuiltinProcId id = BuiltinProc_Invalid;
  9138. if (e != nullptr) {
  9139. id = cast(BuiltinProcId)e->Builtin.id;
  9140. } else {
  9141. id = BuiltinProc_DIRECTIVE;
  9142. }
  9143. return lb_build_builtin_proc(p, expr, tv, id);
  9144. }
  9145. // NOTE(bill): Regular call
  9146. lbValue value = {};
  9147. Ast *proc_expr = unparen_expr(ce->proc);
  9148. if (proc_expr->tav.mode == Addressing_Constant) {
  9149. ExactValue v = proc_expr->tav.value;
  9150. switch (v.kind) {
  9151. case ExactValue_Integer:
  9152. {
  9153. u64 u = big_int_to_u64(&v.value_integer);
  9154. lbValue x = {};
  9155. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  9156. x.type = t_uintptr;
  9157. x = lb_emit_conv(p, x, t_rawptr);
  9158. value = lb_emit_conv(p, x, proc_expr->tav.type);
  9159. break;
  9160. }
  9161. case ExactValue_Pointer:
  9162. {
  9163. u64 u = cast(u64)v.value_pointer;
  9164. lbValue x = {};
  9165. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  9166. x.type = t_uintptr;
  9167. x = lb_emit_conv(p, x, t_rawptr);
  9168. value = lb_emit_conv(p, x, proc_expr->tav.type);
  9169. break;
  9170. }
  9171. }
  9172. }
  9173. Entity *proc_entity = entity_of_node(proc_expr);
  9174. if (proc_entity != nullptr) {
  9175. if (proc_entity->flags & EntityFlag_Disabled) {
  9176. return {};
  9177. }
  9178. }
  9179. if (value.value == nullptr) {
  9180. value = lb_build_expr(p, proc_expr);
  9181. }
  9182. GB_ASSERT(value.value != nullptr);
  9183. Type *proc_type_ = base_type(value.type);
  9184. GB_ASSERT(proc_type_->kind == Type_Proc);
  9185. TypeProc *pt = &proc_type_->Proc;
  9186. if (is_call_expr_field_value(ce)) {
  9187. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  9188. for_array(arg_index, ce->args) {
  9189. Ast *arg = ce->args[arg_index];
  9190. ast_node(fv, FieldValue, arg);
  9191. GB_ASSERT(fv->field->kind == Ast_Ident);
  9192. String name = fv->field->Ident.token.string;
  9193. isize index = lookup_procedure_parameter(pt, name);
  9194. GB_ASSERT(index >= 0);
  9195. TypeAndValue tav = type_and_value_of_expr(fv->value);
  9196. if (tav.mode == Addressing_Type) {
  9197. args[index] = lb_const_nil(m, tav.type);
  9198. } else {
  9199. args[index] = lb_build_expr(p, fv->value);
  9200. }
  9201. }
  9202. TypeTuple *params = &pt->params->Tuple;
  9203. for (isize i = 0; i < args.count; i++) {
  9204. Entity *e = params->variables[i];
  9205. if (e->kind == Entity_TypeName) {
  9206. args[i] = lb_const_nil(m, e->type);
  9207. } else if (e->kind == Entity_Constant) {
  9208. continue;
  9209. } else {
  9210. GB_ASSERT(e->kind == Entity_Variable);
  9211. if (args[i].value == nullptr) {
  9212. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  9213. } else {
  9214. args[i] = lb_emit_conv(p, args[i], e->type);
  9215. }
  9216. }
  9217. }
  9218. for (isize i = 0; i < args.count; i++) {
  9219. Entity *e = params->variables[i];
  9220. if (args[i].type == nullptr) {
  9221. continue;
  9222. } else if (is_type_untyped_nil(args[i].type)) {
  9223. args[i] = lb_const_nil(m, e->type);
  9224. } else if (is_type_untyped_undef(args[i].type)) {
  9225. args[i] = lb_const_undef(m, e->type);
  9226. }
  9227. }
  9228. return lb_emit_call(p, value, args, ce->inlining, p->copy_elision_hint.ast == expr);
  9229. }
  9230. isize arg_index = 0;
  9231. isize arg_count = 0;
  9232. for_array(i, ce->args) {
  9233. Ast *arg = ce->args[i];
  9234. TypeAndValue tav = type_and_value_of_expr(arg);
  9235. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  9236. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  9237. Type *at = tav.type;
  9238. if (at->kind == Type_Tuple) {
  9239. arg_count += at->Tuple.variables.count;
  9240. } else {
  9241. arg_count++;
  9242. }
  9243. }
  9244. isize param_count = 0;
  9245. if (pt->params) {
  9246. GB_ASSERT(pt->params->kind == Type_Tuple);
  9247. param_count = pt->params->Tuple.variables.count;
  9248. }
  9249. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  9250. isize variadic_index = pt->variadic_index;
  9251. bool variadic = pt->variadic && variadic_index >= 0;
  9252. bool vari_expand = ce->ellipsis.pos.line != 0;
  9253. bool is_c_vararg = pt->c_vararg;
  9254. String proc_name = {};
  9255. if (p->entity != nullptr) {
  9256. proc_name = p->entity->token.string;
  9257. }
  9258. TokenPos pos = ast_token(ce->proc).pos;
  9259. TypeTuple *param_tuple = nullptr;
  9260. if (pt->params) {
  9261. GB_ASSERT(pt->params->kind == Type_Tuple);
  9262. param_tuple = &pt->params->Tuple;
  9263. }
  9264. for_array(i, ce->args) {
  9265. Ast *arg = ce->args[i];
  9266. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  9267. if (arg_tv.mode == Addressing_Type) {
  9268. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  9269. } else {
  9270. lbValue a = lb_build_expr(p, arg);
  9271. Type *at = a.type;
  9272. if (at->kind == Type_Tuple) {
  9273. for_array(i, at->Tuple.variables) {
  9274. Entity *e = at->Tuple.variables[i];
  9275. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  9276. args[arg_index++] = v;
  9277. }
  9278. } else {
  9279. args[arg_index++] = a;
  9280. }
  9281. }
  9282. }
  9283. if (param_count > 0) {
  9284. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  9285. GB_ASSERT(param_count < 1000000);
  9286. if (arg_count < param_count) {
  9287. isize end = cast(isize)param_count;
  9288. if (variadic) {
  9289. end = variadic_index;
  9290. }
  9291. while (arg_index < end) {
  9292. Entity *e = param_tuple->variables[arg_index];
  9293. GB_ASSERT(e->kind == Entity_Variable);
  9294. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  9295. }
  9296. }
  9297. if (is_c_vararg) {
  9298. GB_ASSERT(variadic);
  9299. GB_ASSERT(!vari_expand);
  9300. isize i = 0;
  9301. for (; i < variadic_index; i++) {
  9302. Entity *e = param_tuple->variables[i];
  9303. if (e->kind == Entity_Variable) {
  9304. args[i] = lb_emit_conv(p, args[i], e->type);
  9305. }
  9306. }
  9307. Type *variadic_type = param_tuple->variables[i]->type;
  9308. GB_ASSERT(is_type_slice(variadic_type));
  9309. variadic_type = base_type(variadic_type)->Slice.elem;
  9310. if (!is_type_any(variadic_type)) {
  9311. for (; i < arg_count; i++) {
  9312. args[i] = lb_emit_conv(p, args[i], variadic_type);
  9313. }
  9314. } else {
  9315. for (; i < arg_count; i++) {
  9316. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  9317. }
  9318. }
  9319. } else if (variadic) {
  9320. isize i = 0;
  9321. for (; i < variadic_index; i++) {
  9322. Entity *e = param_tuple->variables[i];
  9323. if (e->kind == Entity_Variable) {
  9324. args[i] = lb_emit_conv(p, args[i], e->type);
  9325. }
  9326. }
  9327. if (!vari_expand) {
  9328. Type *variadic_type = param_tuple->variables[i]->type;
  9329. GB_ASSERT(is_type_slice(variadic_type));
  9330. variadic_type = base_type(variadic_type)->Slice.elem;
  9331. for (; i < arg_count; i++) {
  9332. args[i] = lb_emit_conv(p, args[i], variadic_type);
  9333. }
  9334. }
  9335. } else {
  9336. for (isize i = 0; i < param_count; i++) {
  9337. Entity *e = param_tuple->variables[i];
  9338. if (e->kind == Entity_Variable) {
  9339. if (args[i].value == nullptr) {
  9340. continue;
  9341. }
  9342. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  9343. args[i] = lb_emit_conv(p, args[i], e->type);
  9344. }
  9345. }
  9346. }
  9347. if (variadic && !vari_expand && !is_c_vararg) {
  9348. // variadic call argument generation
  9349. Type *slice_type = param_tuple->variables[variadic_index]->type;
  9350. Type *elem_type = base_type(slice_type)->Slice.elem;
  9351. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  9352. isize slice_len = arg_count+1 - (variadic_index+1);
  9353. if (slice_len > 0) {
  9354. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  9355. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  9356. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  9357. lb_emit_store(p, addr, args[i]);
  9358. }
  9359. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  9360. lbValue len = lb_const_int(m, t_int, slice_len);
  9361. lb_fill_slice(p, slice, base_elem, len);
  9362. }
  9363. arg_count = param_count;
  9364. args[variadic_index] = lb_addr_load(p, slice);
  9365. }
  9366. }
  9367. if (variadic && variadic_index+1 < param_count) {
  9368. for (isize i = variadic_index+1; i < param_count; i++) {
  9369. Entity *e = param_tuple->variables[i];
  9370. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  9371. }
  9372. }
  9373. isize final_count = param_count;
  9374. if (is_c_vararg) {
  9375. final_count = arg_count;
  9376. }
  9377. if (param_tuple != nullptr) {
  9378. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  9379. Entity *e = param_tuple->variables[i];
  9380. if (args[i].type == nullptr) {
  9381. continue;
  9382. } else if (is_type_untyped_nil(args[i].type)) {
  9383. args[i] = lb_const_nil(m, e->type);
  9384. } else if (is_type_untyped_undef(args[i].type)) {
  9385. args[i] = lb_const_undef(m, e->type);
  9386. }
  9387. }
  9388. }
  9389. auto call_args = array_slice(args, 0, final_count);
  9390. return lb_emit_call(p, value, call_args, ce->inlining, p->copy_elision_hint.ast == expr);
  9391. }
  9392. bool lb_is_const(lbValue value) {
  9393. LLVMValueRef v = value.value;
  9394. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  9395. // TODO(bill): Is this correct behaviour?
  9396. return true;
  9397. }
  9398. if (LLVMIsConstant(v)) {
  9399. return true;
  9400. }
  9401. return false;
  9402. }
  9403. bool lb_is_const_or_global(lbValue value) {
  9404. if (lb_is_const(value)) {
  9405. return true;
  9406. }
  9407. if (LLVMGetValueKind(value.value) == LLVMGlobalVariableValueKind) {
  9408. LLVMTypeRef t = LLVMGetElementType(LLVMTypeOf(value.value));
  9409. if (!lb_is_type_kind(t, LLVMPointerTypeKind)) {
  9410. return false;
  9411. }
  9412. LLVMTypeRef elem = LLVMGetElementType(t);
  9413. return lb_is_type_kind(elem, LLVMFunctionTypeKind);
  9414. }
  9415. return false;
  9416. }
  9417. bool lb_is_const_nil(lbValue value) {
  9418. LLVMValueRef v = value.value;
  9419. if (LLVMIsConstant(v)) {
  9420. if (LLVMIsAConstantAggregateZero(v)) {
  9421. return true;
  9422. } else if (LLVMIsAConstantPointerNull(v)) {
  9423. return true;
  9424. }
  9425. }
  9426. return false;
  9427. }
  9428. String lb_get_const_string(lbModule *m, lbValue value) {
  9429. GB_ASSERT(lb_is_const(value));
  9430. GB_ASSERT(LLVMIsConstant(value.value));
  9431. Type *t = base_type(value.type);
  9432. GB_ASSERT(are_types_identical(t, t_string));
  9433. unsigned ptr_indices[1] = {0};
  9434. unsigned len_indices[1] = {1};
  9435. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  9436. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  9437. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  9438. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  9439. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  9440. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  9441. size_t length = 0;
  9442. char const *text = LLVMGetAsString(underlying_ptr, &length);
  9443. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  9444. return make_string(cast(u8 const *)text, real_length);
  9445. }
  9446. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  9447. GB_ASSERT(is_type_pointer(addr.type));
  9448. Type *type = type_deref(addr.type);
  9449. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  9450. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  9451. }
  9452. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *end_type) {
  9453. GB_ASSERT(type_size_of(value.type) == type_size_of(end_type));
  9454. if (type_size_of(value.type) < 2) {
  9455. return value;
  9456. }
  9457. Type *original_type = value.type;
  9458. if (is_type_float(original_type)) {
  9459. i64 sz = type_size_of(original_type);
  9460. Type *integer_type = nullptr;
  9461. switch (sz) {
  9462. case 2: integer_type = t_u16; break;
  9463. case 4: integer_type = t_u32; break;
  9464. case 8: integer_type = t_u64; break;
  9465. }
  9466. GB_ASSERT(integer_type != nullptr);
  9467. value = lb_emit_transmute(p, value, integer_type);
  9468. }
  9469. char const *name = "llvm.bswap";
  9470. LLVMTypeRef types[1] = {lb_type(p->module, value.type)};
  9471. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  9472. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  9473. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  9474. LLVMValueRef args[1] = {};
  9475. args[0] = value.value;
  9476. lbValue res = {};
  9477. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  9478. res.type = value.type;
  9479. if (is_type_float(original_type)) {
  9480. res = lb_emit_transmute(p, res, original_type);
  9481. }
  9482. res.type = end_type;
  9483. return res;
  9484. }
  9485. lbValue lb_emit_count_ones(lbProcedure *p, lbValue x, Type *type) {
  9486. x = lb_emit_conv(p, x, type);
  9487. char const *name = "llvm.ctpop";
  9488. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  9489. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  9490. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  9491. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  9492. LLVMValueRef args[1] = {};
  9493. args[0] = x.value;
  9494. lbValue res = {};
  9495. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  9496. res.type = type;
  9497. return res;
  9498. }
  9499. lbValue lb_emit_count_zeros(lbProcedure *p, lbValue x, Type *type) {
  9500. i64 sz = 8*type_size_of(type);
  9501. lbValue size = lb_const_int(p->module, type, cast(u64)sz);
  9502. lbValue count = lb_emit_count_ones(p, x, type);
  9503. return lb_emit_arith(p, Token_Sub, size, count, type);
  9504. }
  9505. lbValue lb_emit_count_trailing_zeros(lbProcedure *p, lbValue x, Type *type) {
  9506. x = lb_emit_conv(p, x, type);
  9507. char const *name = "llvm.cttz";
  9508. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  9509. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  9510. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  9511. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  9512. LLVMValueRef args[2] = {};
  9513. args[0] = x.value;
  9514. args[1] = LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx));
  9515. lbValue res = {};
  9516. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  9517. res.type = type;
  9518. return res;
  9519. }
  9520. lbValue lb_emit_count_leading_zeros(lbProcedure *p, lbValue x, Type *type) {
  9521. x = lb_emit_conv(p, x, type);
  9522. char const *name = "llvm.ctlz";
  9523. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  9524. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  9525. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  9526. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  9527. LLVMValueRef args[2] = {};
  9528. args[0] = x.value;
  9529. args[1] = LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx));
  9530. lbValue res = {};
  9531. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  9532. res.type = type;
  9533. return res;
  9534. }
  9535. lbValue lb_emit_reverse_bits(lbProcedure *p, lbValue x, Type *type) {
  9536. x = lb_emit_conv(p, x, type);
  9537. char const *name = "llvm.bitreverse";
  9538. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  9539. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  9540. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  9541. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  9542. LLVMValueRef args[1] = {};
  9543. args[0] = x.value;
  9544. lbValue res = {};
  9545. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  9546. res.type = type;
  9547. return res;
  9548. }
  9549. lbValue lb_emit_bit_set_card(lbProcedure *p, lbValue x) {
  9550. GB_ASSERT(is_type_bit_set(x.type));
  9551. Type *underlying = bit_set_to_int(x.type);
  9552. lbValue card = lb_emit_count_ones(p, x, underlying);
  9553. return lb_emit_conv(p, card, t_int);
  9554. }
  9555. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  9556. lbLoopData data = {};
  9557. lbValue max = lb_const_int(p->module, t_int, count);
  9558. data.idx_addr = lb_add_local_generated(p, index_type, true);
  9559. data.body = lb_create_block(p, "loop.body");
  9560. data.done = lb_create_block(p, "loop.done");
  9561. data.loop = lb_create_block(p, "loop.loop");
  9562. lb_emit_jump(p, data.loop);
  9563. lb_start_block(p, data.loop);
  9564. data.idx = lb_addr_load(p, data.idx_addr);
  9565. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  9566. lb_emit_if(p, cond, data.body, data.done);
  9567. lb_start_block(p, data.body);
  9568. return data;
  9569. }
  9570. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  9571. if (data.idx_addr.addr.value != nullptr) {
  9572. lb_emit_increment(p, data.idx_addr.addr);
  9573. lb_emit_jump(p, data.loop);
  9574. lb_start_block(p, data.done);
  9575. }
  9576. }
  9577. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  9578. lbValue res = {};
  9579. res.type = t_llvm_bool;
  9580. Type *t = x.type;
  9581. Type *bt = base_type(t);
  9582. TypeKind type_kind = bt->kind;
  9583. switch (type_kind) {
  9584. case Type_Basic:
  9585. switch (bt->Basic.kind) {
  9586. case Basic_rawptr:
  9587. case Basic_cstring:
  9588. if (op_kind == Token_CmpEq) {
  9589. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  9590. } else if (op_kind == Token_NotEq) {
  9591. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  9592. }
  9593. return res;
  9594. case Basic_any:
  9595. {
  9596. // TODO(bill): is this correct behaviour for nil comparison for any?
  9597. lbValue data = lb_emit_struct_ev(p, x, 0);
  9598. lbValue ti = lb_emit_struct_ev(p, x, 1);
  9599. if (op_kind == Token_CmpEq) {
  9600. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  9601. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  9602. res.value = LLVMBuildOr(p->builder, a, b, "");
  9603. return res;
  9604. } else if (op_kind == Token_NotEq) {
  9605. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  9606. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  9607. res.value = LLVMBuildAnd(p->builder, a, b, "");
  9608. return res;
  9609. }
  9610. }
  9611. break;
  9612. case Basic_typeid:
  9613. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  9614. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  9615. }
  9616. break;
  9617. case Type_Enum:
  9618. case Type_Pointer:
  9619. case Type_Proc:
  9620. case Type_BitSet:
  9621. if (op_kind == Token_CmpEq) {
  9622. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  9623. } else if (op_kind == Token_NotEq) {
  9624. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  9625. }
  9626. return res;
  9627. case Type_Slice:
  9628. {
  9629. lbValue data = lb_emit_struct_ev(p, x, 0);
  9630. if (op_kind == Token_CmpEq) {
  9631. res.value = LLVMBuildIsNull(p->builder, data.value, "");
  9632. return res;
  9633. } else if (op_kind == Token_NotEq) {
  9634. res.value = LLVMBuildIsNotNull(p->builder, data.value, "");
  9635. return res;
  9636. }
  9637. }
  9638. break;
  9639. case Type_DynamicArray:
  9640. {
  9641. lbValue data = lb_emit_struct_ev(p, x, 0);
  9642. if (op_kind == Token_CmpEq) {
  9643. res.value = LLVMBuildIsNull(p->builder, data.value, "");
  9644. return res;
  9645. } else if (op_kind == Token_NotEq) {
  9646. res.value = LLVMBuildIsNotNull(p->builder, data.value, "");
  9647. return res;
  9648. }
  9649. }
  9650. break;
  9651. case Type_Map:
  9652. {
  9653. lbValue map_ptr = lb_address_from_load_or_generate_local(p, x);
  9654. unsigned indices[2] = {0, 0};
  9655. LLVMValueRef hashes_data = LLVMBuildStructGEP(p->builder, map_ptr.value, 0, "");
  9656. LLVMValueRef hashes_data_ptr_ptr = LLVMBuildStructGEP(p->builder, hashes_data, 0, "");
  9657. LLVMValueRef hashes_data_ptr = LLVMBuildLoad(p->builder, hashes_data_ptr_ptr, "");
  9658. if (op_kind == Token_CmpEq) {
  9659. res.value = LLVMBuildIsNull(p->builder, hashes_data_ptr, "");
  9660. return res;
  9661. } else {
  9662. res.value = LLVMBuildIsNotNull(p->builder, hashes_data_ptr, "");
  9663. return res;
  9664. }
  9665. }
  9666. break;
  9667. case Type_Union:
  9668. {
  9669. if (type_size_of(t) == 0) {
  9670. if (op_kind == Token_CmpEq) {
  9671. return lb_const_bool(p->module, t_llvm_bool, true);
  9672. } else if (op_kind == Token_NotEq) {
  9673. return lb_const_bool(p->module, t_llvm_bool, false);
  9674. }
  9675. } else if (is_type_union_maybe_pointer(t)) {
  9676. lbValue tag = lb_emit_transmute(p, x, t_rawptr);
  9677. return lb_emit_comp_against_nil(p, op_kind, tag);
  9678. } else {
  9679. lbValue tag = lb_emit_union_tag_value(p, x);
  9680. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  9681. }
  9682. }
  9683. case Type_Struct:
  9684. if (is_type_soa_struct(t)) {
  9685. Type *bt = base_type(t);
  9686. if (bt->Struct.soa_kind == StructSoa_Slice) {
  9687. LLVMValueRef the_value = {};
  9688. if (bt->Struct.fields.count == 0) {
  9689. lbValue len = lb_soa_struct_len(p, x);
  9690. the_value = len.value;
  9691. } else {
  9692. lbValue first_field = lb_emit_struct_ev(p, x, 0);
  9693. the_value = first_field.value;
  9694. }
  9695. if (op_kind == Token_CmpEq) {
  9696. res.value = LLVMBuildIsNull(p->builder, the_value, "");
  9697. return res;
  9698. } else if (op_kind == Token_NotEq) {
  9699. res.value = LLVMBuildIsNotNull(p->builder, the_value, "");
  9700. return res;
  9701. }
  9702. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  9703. LLVMValueRef the_value = {};
  9704. if (bt->Struct.fields.count == 0) {
  9705. lbValue cap = lb_soa_struct_cap(p, x);
  9706. the_value = cap.value;
  9707. } else {
  9708. lbValue first_field = lb_emit_struct_ev(p, x, 0);
  9709. the_value = first_field.value;
  9710. }
  9711. if (op_kind == Token_CmpEq) {
  9712. res.value = LLVMBuildIsNull(p->builder, the_value, "");
  9713. return res;
  9714. } else if (op_kind == Token_NotEq) {
  9715. res.value = LLVMBuildIsNotNull(p->builder, the_value, "");
  9716. return res;
  9717. }
  9718. }
  9719. } else if (is_type_struct(t) && type_has_nil(t)) {
  9720. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9721. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  9722. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  9723. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  9724. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  9725. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  9726. return res;
  9727. }
  9728. break;
  9729. }
  9730. GB_PANIC("Unknown handled type: %s -> %s", type_to_string(t), type_to_string(bt));
  9731. return {};
  9732. }
  9733. lbValue lb_get_equal_proc_for_type(lbModule *m, Type *type) {
  9734. Type *original_type = type;
  9735. type = base_type(type);
  9736. GB_ASSERT(is_type_comparable(type));
  9737. Type *pt = alloc_type_pointer(type);
  9738. LLVMTypeRef ptr_type = lb_type(m, pt);
  9739. auto key = hash_type(type);
  9740. lbProcedure **found = map_get(&m->equal_procs, key);
  9741. lbProcedure *compare_proc = nullptr;
  9742. if (found) {
  9743. compare_proc = *found;
  9744. GB_ASSERT(compare_proc != nullptr);
  9745. return {compare_proc->value, compare_proc->type};
  9746. }
  9747. static u32 proc_index = 0;
  9748. char buf[16] = {};
  9749. isize n = gb_snprintf(buf, 16, "__$equal%u", ++proc_index);
  9750. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  9751. String proc_name = make_string_c(str);
  9752. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  9753. map_set(&m->equal_procs, key, p);
  9754. lb_begin_procedure_body(p);
  9755. LLVMValueRef x = LLVMGetParam(p->value, 0);
  9756. LLVMValueRef y = LLVMGetParam(p->value, 1);
  9757. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  9758. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  9759. lbValue lhs = {x, pt};
  9760. lbValue rhs = {y, pt};
  9761. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  9762. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  9763. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  9764. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  9765. lb_start_block(p, block_same_ptr);
  9766. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  9767. lb_start_block(p, block_diff_ptr);
  9768. if (type->kind == Type_Struct) {
  9769. type_set_offsets(type);
  9770. lbBlock *block_false = lb_create_block(p, "bfalse");
  9771. lbValue res = lb_const_bool(m, t_bool, true);
  9772. for_array(i, type->Struct.fields) {
  9773. lbBlock *next_block = lb_create_block(p, "btrue");
  9774. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  9775. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  9776. lbValue left = lb_emit_load(p, pleft);
  9777. lbValue right = lb_emit_load(p, pright);
  9778. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  9779. lb_emit_if(p, ok, next_block, block_false);
  9780. lb_emit_jump(p, next_block);
  9781. lb_start_block(p, next_block);
  9782. }
  9783. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  9784. lb_start_block(p, block_false);
  9785. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  9786. } else if (type->kind == Type_Union) {
  9787. if (is_type_union_maybe_pointer(type)) {
  9788. Type *v = type->Union.variants[0];
  9789. Type *pv = alloc_type_pointer(v);
  9790. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, pv));
  9791. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, pv));
  9792. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  9793. ok = lb_emit_conv(p, ok, t_bool);
  9794. LLVMBuildRet(p->builder, ok.value);
  9795. } else {
  9796. lbBlock *block_false = lb_create_block(p, "bfalse");
  9797. lbBlock *block_switch = lb_create_block(p, "bswitch");
  9798. lbValue left_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, lhs));
  9799. lbValue right_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, rhs));
  9800. lbValue tag_eq = lb_emit_comp(p, Token_CmpEq, left_tag, right_tag);
  9801. lb_emit_if(p, tag_eq, block_switch, block_false);
  9802. lb_start_block(p, block_switch);
  9803. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, left_tag.value, block_false->block, cast(unsigned)type->Union.variants.count);
  9804. for_array(i, type->Union.variants) {
  9805. lbBlock *case_block = lb_create_block(p, "bcase");
  9806. lb_start_block(p, case_block);
  9807. Type *v = type->Union.variants[i];
  9808. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  9809. Type *vp = alloc_type_pointer(v);
  9810. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, vp));
  9811. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, vp));
  9812. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  9813. ok = lb_emit_conv(p, ok, t_bool);
  9814. LLVMBuildRet(p->builder, ok.value);
  9815. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  9816. }
  9817. lb_start_block(p, block_false);
  9818. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  9819. }
  9820. } else {
  9821. lbValue left = lb_emit_load(p, lhs);
  9822. lbValue right = lb_emit_load(p, rhs);
  9823. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  9824. ok = lb_emit_conv(p, ok, t_bool);
  9825. LLVMBuildRet(p->builder, ok.value);
  9826. }
  9827. lb_end_procedure_body(p);
  9828. compare_proc = p;
  9829. return {compare_proc->value, compare_proc->type};
  9830. }
  9831. lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  9832. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  9833. i64 sz = type_size_of(type);
  9834. if (1 <= sz && sz <= 16) {
  9835. char name[20] = {};
  9836. gb_snprintf(name, 20, "default_hasher%d", cast(i32)sz);
  9837. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9838. args[0] = data;
  9839. args[1] = seed;
  9840. return lb_emit_runtime_call(p, name, args);
  9841. }
  9842. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9843. args[0] = data;
  9844. args[1] = seed;
  9845. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  9846. return lb_emit_runtime_call(p, "default_hasher_n", args);
  9847. }
  9848. lbValue lb_get_hasher_proc_for_type(lbModule *m, Type *type) {
  9849. Type *original_type = type;
  9850. type = core_type(type);
  9851. GB_ASSERT(is_type_valid_for_keys(type));
  9852. Type *pt = alloc_type_pointer(type);
  9853. LLVMTypeRef ptr_type = lb_type(m, pt);
  9854. auto key = hash_type(type);
  9855. lbProcedure **found = map_get(&m->hasher_procs, key);
  9856. if (found) {
  9857. GB_ASSERT(*found != nullptr);
  9858. return {(*found)->value, (*found)->type};
  9859. }
  9860. static u32 proc_index = 0;
  9861. char buf[16] = {};
  9862. isize n = gb_snprintf(buf, 16, "__$hasher%u", ++proc_index);
  9863. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  9864. String proc_name = make_string_c(str);
  9865. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  9866. map_set(&m->hasher_procs, key, p);
  9867. lb_begin_procedure_body(p);
  9868. defer (lb_end_procedure_body(p));
  9869. LLVMValueRef x = LLVMGetParam(p->value, 0);
  9870. LLVMValueRef y = LLVMGetParam(p->value, 1);
  9871. lbValue data = {x, t_rawptr};
  9872. lbValue seed = {y, t_uintptr};
  9873. LLVMAttributeRef nonnull_attr = lb_create_enum_attribute(m->ctx, "nonnull");
  9874. LLVMAddAttributeAtIndex(p->value, 1+0, nonnull_attr);
  9875. if (is_type_simple_compare(type)) {
  9876. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  9877. LLVMBuildRet(p->builder, res.value);
  9878. return {p->value, p->type};
  9879. }
  9880. if (type->kind == Type_Struct) {
  9881. type_set_offsets(type);
  9882. data = lb_emit_conv(p, data, t_u8_ptr);
  9883. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9884. for_array(i, type->Struct.fields) {
  9885. i64 offset = type->Struct.offsets[i];
  9886. Entity *field = type->Struct.fields[i];
  9887. lbValue field_hasher = lb_get_hasher_proc_for_type(m, field->type);
  9888. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  9889. args[0] = ptr;
  9890. args[1] = seed;
  9891. seed = lb_emit_call(p, field_hasher, args);
  9892. }
  9893. LLVMBuildRet(p->builder, seed.value);
  9894. } else if (type->kind == Type_Union) {
  9895. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9896. if (is_type_union_maybe_pointer(type)) {
  9897. Type *v = type->Union.variants[0];
  9898. lbValue variant_hasher = lb_get_hasher_proc_for_type(m, v);
  9899. args[0] = data;
  9900. args[1] = seed;
  9901. lbValue res = lb_emit_call(p, variant_hasher, args);
  9902. LLVMBuildRet(p->builder, res.value);
  9903. }
  9904. lbBlock *end_block = lb_create_block(p, "bend");
  9905. data = lb_emit_conv(p, data, pt);
  9906. lbValue tag_ptr = lb_emit_union_tag_ptr(p, data);
  9907. lbValue tag = lb_emit_load(p, tag_ptr);
  9908. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, tag.value, end_block->block, cast(unsigned)type->Union.variants.count);
  9909. for_array(i, type->Union.variants) {
  9910. lbBlock *case_block = lb_create_block(p, "bcase");
  9911. lb_start_block(p, case_block);
  9912. Type *v = type->Union.variants[i];
  9913. Type *vp = alloc_type_pointer(v);
  9914. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  9915. lbValue variant_hasher = lb_get_hasher_proc_for_type(m, v);
  9916. args[0] = data;
  9917. args[1] = seed;
  9918. lbValue res = lb_emit_call(p, variant_hasher, args);
  9919. LLVMBuildRet(p->builder, res.value);
  9920. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  9921. }
  9922. lb_start_block(p, end_block);
  9923. LLVMBuildRet(p->builder, seed.value);
  9924. } else if (type->kind == Type_Array) {
  9925. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  9926. lb_addr_store(p, pres, seed);
  9927. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9928. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->Array.elem);
  9929. auto loop_data = lb_loop_start(p, cast(isize)type->Array.count, t_i32);
  9930. data = lb_emit_conv(p, data, pt);
  9931. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  9932. args[0] = ptr;
  9933. args[1] = lb_addr_load(p, pres);
  9934. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  9935. lb_addr_store(p, pres, new_seed);
  9936. lb_loop_end(p, loop_data);
  9937. lbValue res = lb_addr_load(p, pres);
  9938. LLVMBuildRet(p->builder, res.value);
  9939. } else if (type->kind == Type_EnumeratedArray) {
  9940. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  9941. lb_addr_store(p, res, seed);
  9942. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9943. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  9944. auto loop_data = lb_loop_start(p, cast(isize)type->EnumeratedArray.count, t_i32);
  9945. data = lb_emit_conv(p, data, pt);
  9946. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  9947. args[0] = ptr;
  9948. args[1] = lb_addr_load(p, res);
  9949. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  9950. lb_addr_store(p, res, new_seed);
  9951. lb_loop_end(p, loop_data);
  9952. lbValue vres = lb_addr_load(p, res);
  9953. LLVMBuildRet(p->builder, vres.value);
  9954. } else if (is_type_cstring(type)) {
  9955. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9956. args[0] = data;
  9957. args[1] = seed;
  9958. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  9959. LLVMBuildRet(p->builder, res.value);
  9960. } else if (is_type_string(type)) {
  9961. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9962. args[0] = data;
  9963. args[1] = seed;
  9964. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  9965. LLVMBuildRet(p->builder, res.value);
  9966. } else {
  9967. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  9968. }
  9969. return {p->value, p->type};
  9970. }
  9971. lbValue lb_compare_records(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right, Type *type) {
  9972. GB_ASSERT((is_type_struct(type) || is_type_union(type)) && is_type_comparable(type));
  9973. lbValue left_ptr = lb_address_from_load_or_generate_local(p, left);
  9974. lbValue right_ptr = lb_address_from_load_or_generate_local(p, right);
  9975. lbValue res = {};
  9976. if (is_type_simple_compare(type)) {
  9977. // TODO(bill): Test to see if this is actually faster!!!!
  9978. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9979. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  9980. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  9981. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  9982. res = lb_emit_runtime_call(p, "memory_equal", args);
  9983. } else {
  9984. lbValue value = lb_get_equal_proc_for_type(p->module, type);
  9985. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9986. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  9987. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  9988. res = lb_emit_call(p, value, args);
  9989. }
  9990. if (op_kind == Token_NotEq) {
  9991. res = lb_emit_unary_arith(p, Token_Not, res, res.type);
  9992. }
  9993. return res;
  9994. }
  9995. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  9996. Type *a = core_type(left.type);
  9997. Type *b = core_type(right.type);
  9998. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  9999. lbValue nil_check = {};
  10000. if (is_type_untyped_nil(left.type)) {
  10001. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  10002. } else if (is_type_untyped_nil(right.type)) {
  10003. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  10004. }
  10005. if (nil_check.value != nullptr) {
  10006. return nil_check;
  10007. }
  10008. if (are_types_identical(a, b)) {
  10009. // NOTE(bill): No need for a conversion
  10010. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  10011. left = lb_emit_conv(p, left, right.type);
  10012. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  10013. right = lb_emit_conv(p, right, left.type);
  10014. } else {
  10015. Type *lt = left.type;
  10016. Type *rt = right.type;
  10017. lt = left.type;
  10018. rt = right.type;
  10019. i64 ls = type_size_of(lt);
  10020. i64 rs = type_size_of(rt);
  10021. // NOTE(bill): Quick heuristic, larger types are usually the target type
  10022. if (ls < rs) {
  10023. left = lb_emit_conv(p, left, rt);
  10024. } else if (ls > rs) {
  10025. right = lb_emit_conv(p, right, lt);
  10026. } else {
  10027. if (is_type_union(rt)) {
  10028. left = lb_emit_conv(p, left, rt);
  10029. } else {
  10030. right = lb_emit_conv(p, right, lt);
  10031. }
  10032. }
  10033. }
  10034. if (is_type_array(a) || is_type_enumerated_array(a)) {
  10035. Type *tl = base_type(a);
  10036. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  10037. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  10038. TokenKind cmp_op = Token_And;
  10039. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  10040. if (op_kind == Token_NotEq) {
  10041. res = lb_const_bool(p->module, t_llvm_bool, false);
  10042. cmp_op = Token_Or;
  10043. } else if (op_kind == Token_CmpEq) {
  10044. res = lb_const_bool(p->module, t_llvm_bool, true);
  10045. cmp_op = Token_And;
  10046. }
  10047. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  10048. i32 count = 0;
  10049. switch (tl->kind) {
  10050. case Type_Array: count = cast(i32)tl->Array.count; break;
  10051. case Type_EnumeratedArray: count = cast(i32)tl->EnumeratedArray.count; break;
  10052. }
  10053. if (inline_array_arith) {
  10054. // inline
  10055. lbAddr val = lb_add_local_generated(p, t_bool, false);
  10056. lb_addr_store(p, val, res);
  10057. for (i32 i = 0; i < count; i++) {
  10058. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  10059. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  10060. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  10061. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  10062. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  10063. }
  10064. return lb_addr_load(p, val);
  10065. } else {
  10066. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  10067. // TODO(bill): Test to see if this is actually faster!!!!
  10068. auto args = array_make<lbValue>(permanent_allocator(), 3);
  10069. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  10070. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  10071. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  10072. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  10073. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  10074. return lb_emit_conv(p, res, t_bool);
  10075. } else {
  10076. lbAddr val = lb_add_local_generated(p, t_bool, false);
  10077. lb_addr_store(p, val, res);
  10078. auto loop_data = lb_loop_start(p, count, t_i32);
  10079. {
  10080. lbValue i = loop_data.idx;
  10081. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  10082. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  10083. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  10084. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  10085. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  10086. }
  10087. lb_loop_end(p, loop_data);
  10088. return lb_addr_load(p, val);
  10089. }
  10090. }
  10091. }
  10092. if ((is_type_struct(a) || is_type_union(a)) && is_type_comparable(a)) {
  10093. return lb_compare_records(p, op_kind, left, right, a);
  10094. }
  10095. if ((is_type_struct(b) || is_type_union(b)) && is_type_comparable(b)) {
  10096. return lb_compare_records(p, op_kind, left, right, b);
  10097. }
  10098. if (is_type_string(a)) {
  10099. if (is_type_cstring(a)) {
  10100. left = lb_emit_conv(p, left, t_string);
  10101. right = lb_emit_conv(p, right, t_string);
  10102. }
  10103. char const *runtime_procedure = nullptr;
  10104. switch (op_kind) {
  10105. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  10106. case Token_NotEq: runtime_procedure = "string_ne"; break;
  10107. case Token_Lt: runtime_procedure = "string_lt"; break;
  10108. case Token_Gt: runtime_procedure = "string_gt"; break;
  10109. case Token_LtEq: runtime_procedure = "string_le"; break;
  10110. case Token_GtEq: runtime_procedure = "string_gt"; break;
  10111. }
  10112. GB_ASSERT(runtime_procedure != nullptr);
  10113. auto args = array_make<lbValue>(permanent_allocator(), 2);
  10114. args[0] = left;
  10115. args[1] = right;
  10116. return lb_emit_runtime_call(p, runtime_procedure, args);
  10117. }
  10118. if (is_type_complex(a)) {
  10119. char const *runtime_procedure = "";
  10120. i64 sz = 8*type_size_of(a);
  10121. switch (sz) {
  10122. case 32:
  10123. switch (op_kind) {
  10124. case Token_CmpEq: runtime_procedure = "complex32_eq"; break;
  10125. case Token_NotEq: runtime_procedure = "complex32_ne"; break;
  10126. }
  10127. break;
  10128. case 64:
  10129. switch (op_kind) {
  10130. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  10131. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  10132. }
  10133. break;
  10134. case 128:
  10135. switch (op_kind) {
  10136. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  10137. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  10138. }
  10139. break;
  10140. }
  10141. GB_ASSERT(runtime_procedure != nullptr);
  10142. auto args = array_make<lbValue>(permanent_allocator(), 2);
  10143. args[0] = left;
  10144. args[1] = right;
  10145. return lb_emit_runtime_call(p, runtime_procedure, args);
  10146. }
  10147. if (is_type_quaternion(a)) {
  10148. char const *runtime_procedure = "";
  10149. i64 sz = 8*type_size_of(a);
  10150. switch (sz) {
  10151. case 64:
  10152. switch (op_kind) {
  10153. case Token_CmpEq: runtime_procedure = "quaternion64_eq"; break;
  10154. case Token_NotEq: runtime_procedure = "quaternion64_ne"; break;
  10155. }
  10156. break;
  10157. case 128:
  10158. switch (op_kind) {
  10159. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  10160. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  10161. }
  10162. break;
  10163. case 256:
  10164. switch (op_kind) {
  10165. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  10166. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  10167. }
  10168. break;
  10169. }
  10170. GB_ASSERT(runtime_procedure != nullptr);
  10171. auto args = array_make<lbValue>(permanent_allocator(), 2);
  10172. args[0] = left;
  10173. args[1] = right;
  10174. return lb_emit_runtime_call(p, runtime_procedure, args);
  10175. }
  10176. if (is_type_bit_set(a)) {
  10177. switch (op_kind) {
  10178. case Token_Lt:
  10179. case Token_LtEq:
  10180. case Token_Gt:
  10181. case Token_GtEq:
  10182. {
  10183. Type *it = bit_set_to_int(a);
  10184. lbValue lhs = lb_emit_transmute(p, left, it);
  10185. lbValue rhs = lb_emit_transmute(p, right, it);
  10186. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  10187. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  10188. // (lhs & rhs) == lhs
  10189. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  10190. res.type = t_llvm_bool;
  10191. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  10192. // (lhs & rhs) == rhs
  10193. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  10194. res.type = t_llvm_bool;
  10195. }
  10196. // NOTE(bill): Strict subsets
  10197. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  10198. // res &~ (lhs == rhs)
  10199. lbValue eq = {};
  10200. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  10201. eq.type = t_llvm_bool;
  10202. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  10203. }
  10204. return res;
  10205. }
  10206. case Token_CmpEq:
  10207. case Token_NotEq:
  10208. {
  10209. LLVMIntPredicate pred = {};
  10210. switch (op_kind) {
  10211. case Token_CmpEq: pred = LLVMIntEQ; break;
  10212. case Token_NotEq: pred = LLVMIntNE; break;
  10213. }
  10214. lbValue res = {};
  10215. res.type = t_llvm_bool;
  10216. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  10217. return res;
  10218. }
  10219. }
  10220. }
  10221. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  10222. Type *t = left.type;
  10223. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  10224. Type *platform_type = integer_endian_type_to_platform_type(t);
  10225. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  10226. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  10227. left = x;
  10228. right = y;
  10229. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  10230. Type *platform_type = integer_endian_type_to_platform_type(t);
  10231. lbValue x = lb_emit_conv(p, left, platform_type);
  10232. lbValue y = lb_emit_conv(p, right, platform_type);
  10233. left = x;
  10234. right = y;
  10235. }
  10236. }
  10237. a = core_type(left.type);
  10238. b = core_type(right.type);
  10239. lbValue res = {};
  10240. res.type = t_llvm_bool;
  10241. if (is_type_integer(a) ||
  10242. is_type_boolean(a) ||
  10243. is_type_pointer(a) ||
  10244. is_type_proc(a) ||
  10245. is_type_enum(a)) {
  10246. LLVMIntPredicate pred = {};
  10247. if (is_type_unsigned(left.type)) {
  10248. switch (op_kind) {
  10249. case Token_Gt: pred = LLVMIntUGT; break;
  10250. case Token_GtEq: pred = LLVMIntUGE; break;
  10251. case Token_Lt: pred = LLVMIntULT; break;
  10252. case Token_LtEq: pred = LLVMIntULE; break;
  10253. }
  10254. } else {
  10255. switch (op_kind) {
  10256. case Token_Gt: pred = LLVMIntSGT; break;
  10257. case Token_GtEq: pred = LLVMIntSGE; break;
  10258. case Token_Lt: pred = LLVMIntSLT; break;
  10259. case Token_LtEq: pred = LLVMIntSLE; break;
  10260. }
  10261. }
  10262. switch (op_kind) {
  10263. case Token_CmpEq: pred = LLVMIntEQ; break;
  10264. case Token_NotEq: pred = LLVMIntNE; break;
  10265. }
  10266. LLVMValueRef lhs = left.value;
  10267. LLVMValueRef rhs = right.value;
  10268. if (LLVMTypeOf(lhs) != LLVMTypeOf(rhs)) {
  10269. if (lb_is_type_kind(LLVMTypeOf(lhs), LLVMPointerTypeKind)) {
  10270. rhs = LLVMBuildPointerCast(p->builder, rhs, LLVMTypeOf(lhs), "");
  10271. }
  10272. }
  10273. res.value = LLVMBuildICmp(p->builder, pred, lhs, rhs, "");
  10274. } else if (is_type_float(a)) {
  10275. LLVMRealPredicate pred = {};
  10276. switch (op_kind) {
  10277. case Token_CmpEq: pred = LLVMRealOEQ; break;
  10278. case Token_Gt: pred = LLVMRealOGT; break;
  10279. case Token_GtEq: pred = LLVMRealOGE; break;
  10280. case Token_Lt: pred = LLVMRealOLT; break;
  10281. case Token_LtEq: pred = LLVMRealOLE; break;
  10282. case Token_NotEq: pred = LLVMRealONE; break;
  10283. }
  10284. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  10285. } else if (is_type_typeid(a)) {
  10286. LLVMIntPredicate pred = {};
  10287. switch (op_kind) {
  10288. case Token_Gt: pred = LLVMIntUGT; break;
  10289. case Token_GtEq: pred = LLVMIntUGE; break;
  10290. case Token_Lt: pred = LLVMIntULT; break;
  10291. case Token_LtEq: pred = LLVMIntULE; break;
  10292. case Token_CmpEq: pred = LLVMIntEQ; break;
  10293. case Token_NotEq: pred = LLVMIntNE; break;
  10294. }
  10295. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  10296. } else {
  10297. 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)));
  10298. }
  10299. return res;
  10300. }
  10301. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  10302. lbProcedure **found = map_get(&m->gen->anonymous_proc_lits, hash_pointer(expr));
  10303. if (found) {
  10304. return lb_find_procedure_value_from_entity(m, (*found)->entity);
  10305. }
  10306. ast_node(pl, ProcLit, expr);
  10307. // NOTE(bill): Generate a new name
  10308. // parent$count
  10309. isize name_len = prefix_name.len + 1 + 8 + 1;
  10310. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  10311. i32 name_id = cast(i32)m->gen->anonymous_proc_lits.entries.count;
  10312. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  10313. String name = make_string((u8 *)name_text, name_len-1);
  10314. Type *type = type_of_expr(expr);
  10315. Token token = {};
  10316. token.pos = ast_token(expr).pos;
  10317. token.kind = Token_Ident;
  10318. token.string = name;
  10319. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  10320. e->file = expr->file;
  10321. e->decl_info = pl->decl;
  10322. e->code_gen_module = m;
  10323. lbProcedure *p = lb_create_procedure(m, e);
  10324. lbValue value = {};
  10325. value.value = p->value;
  10326. value.type = p->type;
  10327. array_add(&m->procedures_to_generate, p);
  10328. if (parent != nullptr) {
  10329. array_add(&parent->children, p);
  10330. } else {
  10331. string_map_set(&m->members, name, value);
  10332. }
  10333. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  10334. map_set(&m->gen->anonymous_proc_lits, hash_pointer(expr), p);
  10335. return value;
  10336. }
  10337. lbValue lb_emit_union_cast_only_ok_check(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  10338. GB_ASSERT(is_type_tuple(type));
  10339. lbModule *m = p->module;
  10340. Type *src_type = value.type;
  10341. bool is_ptr = is_type_pointer(src_type);
  10342. // IMPORTANT NOTE(bill): This assumes that the value is completely ignored
  10343. // so when it does an assignment, it complete ignores the value.
  10344. // Just make it two booleans and ignore the first one
  10345. //
  10346. // _, ok := x.(T);
  10347. //
  10348. Type *ok_type = type->Tuple.variables[1]->type;
  10349. Type *gen_tuple_types[2] = {};
  10350. gen_tuple_types[0] = ok_type;
  10351. gen_tuple_types[1] = ok_type;
  10352. Type *gen_tuple = alloc_type_tuple_from_field_types(gen_tuple_types, gb_count_of(gen_tuple_types), false, true);
  10353. lbAddr v = lb_add_local_generated(p, gen_tuple, false);
  10354. if (is_ptr) {
  10355. value = lb_emit_load(p, value);
  10356. }
  10357. Type *src = base_type(type_deref(src_type));
  10358. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  10359. Type *dst = type->Tuple.variables[0]->type;
  10360. lbValue cond = {};
  10361. if (is_type_union_maybe_pointer(src)) {
  10362. lbValue data = lb_emit_transmute(p, value, dst);
  10363. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  10364. } else {
  10365. lbValue tag = lb_emit_union_tag_value(p, value);
  10366. lbValue dst_tag = lb_const_union_tag(m, src, dst);
  10367. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  10368. }
  10369. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  10370. lb_emit_store(p, gep1, cond);
  10371. return lb_addr_load(p, v);
  10372. }
  10373. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  10374. lbModule *m = p->module;
  10375. Type *src_type = value.type;
  10376. bool is_ptr = is_type_pointer(src_type);
  10377. bool is_tuple = true;
  10378. Type *tuple = type;
  10379. if (type->kind != Type_Tuple) {
  10380. is_tuple = false;
  10381. tuple = make_optional_ok_type(type);
  10382. }
  10383. lbAddr v = lb_add_local_generated(p, tuple, true);
  10384. if (is_ptr) {
  10385. value = lb_emit_load(p, value);
  10386. }
  10387. Type *src = base_type(type_deref(src_type));
  10388. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  10389. Type *dst = tuple->Tuple.variables[0]->type;
  10390. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  10391. lbValue tag = {};
  10392. lbValue dst_tag = {};
  10393. lbValue cond = {};
  10394. lbValue data = {};
  10395. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  10396. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  10397. if (is_type_union_maybe_pointer(src)) {
  10398. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  10399. } else {
  10400. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  10401. dst_tag = lb_const_union_tag(m, src, dst);
  10402. }
  10403. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  10404. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  10405. if (data.value != nullptr) {
  10406. GB_ASSERT(is_type_union_maybe_pointer(src));
  10407. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  10408. } else {
  10409. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  10410. }
  10411. lb_emit_if(p, cond, ok_block, end_block);
  10412. lb_start_block(p, ok_block);
  10413. if (data.value == nullptr) {
  10414. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  10415. }
  10416. lb_emit_store(p, gep0, data);
  10417. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  10418. lb_emit_jump(p, end_block);
  10419. lb_start_block(p, end_block);
  10420. if (!is_tuple) {
  10421. {
  10422. // NOTE(bill): Panic on invalid conversion
  10423. Type *dst_type = tuple->Tuple.variables[0]->type;
  10424. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  10425. auto args = array_make<lbValue>(permanent_allocator(), 7);
  10426. args[0] = ok;
  10427. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  10428. args[2] = lb_const_int(m, t_i32, pos.line);
  10429. args[3] = lb_const_int(m, t_i32, pos.column);
  10430. args[4] = lb_typeid(m, src_type);
  10431. args[5] = lb_typeid(m, dst_type);
  10432. args[6] = lb_emit_conv(p, value_, t_rawptr);
  10433. lb_emit_runtime_call(p, "type_assertion_check2", args);
  10434. }
  10435. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  10436. }
  10437. return lb_addr_load(p, v);
  10438. }
  10439. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  10440. lbModule *m = p->module;
  10441. Type *src_type = value.type;
  10442. if (is_type_pointer(src_type)) {
  10443. value = lb_emit_load(p, value);
  10444. }
  10445. bool is_tuple = true;
  10446. Type *tuple = type;
  10447. if (type->kind != Type_Tuple) {
  10448. is_tuple = false;
  10449. tuple = make_optional_ok_type(type);
  10450. }
  10451. Type *dst_type = tuple->Tuple.variables[0]->type;
  10452. lbAddr v = lb_add_local_generated(p, tuple, true);
  10453. lbValue dst_typeid = lb_typeid(m, dst_type);
  10454. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  10455. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  10456. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  10457. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  10458. lb_emit_if(p, cond, ok_block, end_block);
  10459. lb_start_block(p, ok_block);
  10460. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  10461. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  10462. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  10463. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  10464. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  10465. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  10466. lb_emit_jump(p, end_block);
  10467. lb_start_block(p, end_block);
  10468. if (!is_tuple) {
  10469. // NOTE(bill): Panic on invalid conversion
  10470. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  10471. auto args = array_make<lbValue>(permanent_allocator(), 7);
  10472. args[0] = ok;
  10473. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  10474. args[2] = lb_const_int(m, t_i32, pos.line);
  10475. args[3] = lb_const_int(m, t_i32, pos.column);
  10476. args[4] = any_typeid;
  10477. args[5] = dst_typeid;
  10478. args[6] = lb_emit_struct_ev(p, value, 0);;
  10479. lb_emit_runtime_call(p, "type_assertion_check2", args);
  10480. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  10481. }
  10482. return v;
  10483. }
  10484. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  10485. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  10486. }
  10487. lbValue lb_find_ident(lbProcedure *p, lbModule *m, Entity *e, Ast *expr) {
  10488. auto *found = map_get(&m->values, hash_entity(e));
  10489. if (found) {
  10490. auto v = *found;
  10491. // NOTE(bill): This is because pointers are already pointers in LLVM
  10492. if (is_type_proc(v.type)) {
  10493. return v;
  10494. }
  10495. return lb_emit_load(p, v);
  10496. } else if (e != nullptr && e->kind == Entity_Variable) {
  10497. return lb_addr_load(p, lb_build_addr(p, expr));
  10498. }
  10499. if (e->kind == Entity_Procedure) {
  10500. return lb_find_procedure_value_from_entity(m, e);
  10501. }
  10502. if (USE_SEPARTE_MODULES) {
  10503. lbModule *other_module = lb_pkg_module(m->gen, e->pkg);
  10504. if (other_module != m) {
  10505. String name = lb_get_entity_name(other_module, e);
  10506. lb_set_entity_from_other_modules_linkage_correctly(other_module, e, name);
  10507. lbValue g = {};
  10508. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  10509. g.type = alloc_type_pointer(e->type);
  10510. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  10511. lb_add_entity(m, e, g);
  10512. lb_add_member(m, name, g);
  10513. return lb_emit_load(p, g);
  10514. }
  10515. }
  10516. String pkg = {};
  10517. if (e->pkg) {
  10518. pkg = e->pkg->name;
  10519. }
  10520. gb_printf_err("Error in: %s\n", token_pos_to_string(ast_token(expr).pos));
  10521. 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);
  10522. return {};
  10523. }
  10524. bool lb_is_expr_constant_zero(Ast *expr) {
  10525. GB_ASSERT(expr != nullptr);
  10526. auto v = exact_value_to_integer(expr->tav.value);
  10527. if (v.kind == ExactValue_Integer) {
  10528. return big_int_cmp_zero(&v.value_integer) == 0;
  10529. }
  10530. return false;
  10531. }
  10532. lbValue lb_build_unary_and(lbProcedure *p, Ast *expr) {
  10533. ast_node(ue, UnaryExpr, expr);
  10534. auto tv = type_and_value_of_expr(expr);
  10535. Ast *ue_expr = unparen_expr(ue->expr);
  10536. if (ue_expr->kind == Ast_IndexExpr && tv.mode == Addressing_OptionalOkPtr && is_type_tuple(tv.type)) {
  10537. Type *tuple = tv.type;
  10538. Type *map_type = type_of_expr(ue_expr->IndexExpr.expr);
  10539. Type *ot = base_type(map_type);
  10540. Type *t = base_type(type_deref(ot));
  10541. bool deref = t != ot;
  10542. GB_ASSERT(t->kind == Type_Map);
  10543. ast_node(ie, IndexExpr, ue_expr);
  10544. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  10545. if (deref) {
  10546. map_val = lb_emit_load(p, map_val);
  10547. }
  10548. lbValue key = lb_build_expr(p, ie->index);
  10549. key = lb_emit_conv(p, key, t->Map.key);
  10550. Type *result_type = type_of_expr(expr);
  10551. lbAddr addr = lb_addr_map(map_val, key, t, alloc_type_pointer(t->Map.value));
  10552. lbValue ptr = lb_addr_get_ptr(p, addr);
  10553. lbValue ok = lb_emit_comp_against_nil(p, Token_NotEq, ptr);
  10554. ok = lb_emit_conv(p, ok, tuple->Tuple.variables[1]->type);
  10555. lbAddr res = lb_add_local_generated(p, tuple, false);
  10556. lbValue gep0 = lb_emit_struct_ep(p, res.addr, 0);
  10557. lbValue gep1 = lb_emit_struct_ep(p, res.addr, 1);
  10558. lb_emit_store(p, gep0, ptr);
  10559. lb_emit_store(p, gep1, ok);
  10560. return lb_addr_load(p, res);
  10561. } if (ue_expr->kind == Ast_CompoundLit) {
  10562. lbValue v = lb_build_expr(p, ue->expr);
  10563. Type *type = v.type;
  10564. lbAddr addr = {};
  10565. if (p->is_startup) {
  10566. addr = lb_add_global_generated(p->module, type, v);
  10567. } else {
  10568. addr = lb_add_local_generated(p, type, false);
  10569. }
  10570. lb_addr_store(p, addr, v);
  10571. return addr.addr;
  10572. } else if (ue_expr->kind == Ast_TypeAssertion) {
  10573. if (is_type_tuple(tv.type)) {
  10574. Type *tuple = tv.type;
  10575. Type *ptr_type = tuple->Tuple.variables[0]->type;
  10576. Type *ok_type = tuple->Tuple.variables[1]->type;
  10577. ast_node(ta, TypeAssertion, ue_expr);
  10578. TokenPos pos = ast_token(expr).pos;
  10579. Type *type = type_of_expr(ue_expr);
  10580. GB_ASSERT(!is_type_tuple(type));
  10581. lbValue e = lb_build_expr(p, ta->expr);
  10582. Type *t = type_deref(e.type);
  10583. if (is_type_union(t)) {
  10584. lbValue v = e;
  10585. if (!is_type_pointer(v.type)) {
  10586. v = lb_address_from_load_or_generate_local(p, v);
  10587. }
  10588. Type *src_type = type_deref(v.type);
  10589. Type *dst_type = type;
  10590. lbValue src_tag = {};
  10591. lbValue dst_tag = {};
  10592. if (is_type_union_maybe_pointer(src_type)) {
  10593. src_tag = lb_emit_comp_against_nil(p, Token_NotEq, v);
  10594. dst_tag = lb_const_bool(p->module, t_bool, true);
  10595. } else {
  10596. src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  10597. dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  10598. }
  10599. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  10600. lbValue data_ptr = lb_emit_conv(p, v, ptr_type);
  10601. lbAddr res = lb_add_local_generated(p, tuple, true);
  10602. lbValue gep0 = lb_emit_struct_ep(p, res.addr, 0);
  10603. lbValue gep1 = lb_emit_struct_ep(p, res.addr, 1);
  10604. lb_emit_store(p, gep0, lb_emit_select(p, ok, data_ptr, lb_const_nil(p->module, ptr_type)));
  10605. lb_emit_store(p, gep1, lb_emit_conv(p, ok, ok_type));
  10606. return lb_addr_load(p, res);
  10607. } else if (is_type_any(t)) {
  10608. lbValue v = e;
  10609. if (is_type_pointer(v.type)) {
  10610. v = lb_emit_load(p, v);
  10611. }
  10612. lbValue data_ptr = lb_emit_conv(p, lb_emit_struct_ev(p, v, 0), ptr_type);
  10613. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  10614. lbValue id = lb_typeid(p->module, type);
  10615. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  10616. lbAddr res = lb_add_local_generated(p, tuple, false);
  10617. lbValue gep0 = lb_emit_struct_ep(p, res.addr, 0);
  10618. lbValue gep1 = lb_emit_struct_ep(p, res.addr, 1);
  10619. lb_emit_store(p, gep0, lb_emit_select(p, ok, data_ptr, lb_const_nil(p->module, ptr_type)));
  10620. lb_emit_store(p, gep1, lb_emit_conv(p, ok, ok_type));
  10621. return lb_addr_load(p, res);
  10622. } else {
  10623. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  10624. }
  10625. } else {
  10626. GB_ASSERT(is_type_pointer(tv.type));
  10627. ast_node(ta, TypeAssertion, ue_expr);
  10628. TokenPos pos = ast_token(expr).pos;
  10629. Type *type = type_of_expr(ue_expr);
  10630. GB_ASSERT(!is_type_tuple(type));
  10631. lbValue e = lb_build_expr(p, ta->expr);
  10632. Type *t = type_deref(e.type);
  10633. if (is_type_union(t)) {
  10634. lbValue v = e;
  10635. if (!is_type_pointer(v.type)) {
  10636. v = lb_address_from_load_or_generate_local(p, v);
  10637. }
  10638. Type *src_type = type_deref(v.type);
  10639. Type *dst_type = type;
  10640. lbValue src_tag = {};
  10641. lbValue dst_tag = {};
  10642. if (is_type_union_maybe_pointer(src_type)) {
  10643. src_tag = lb_emit_comp_against_nil(p, Token_NotEq, v);
  10644. dst_tag = lb_const_bool(p->module, t_bool, true);
  10645. } else {
  10646. src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  10647. dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  10648. }
  10649. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  10650. auto args = array_make<lbValue>(permanent_allocator(), 6);
  10651. args[0] = ok;
  10652. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  10653. args[2] = lb_const_int(p->module, t_i32, pos.line);
  10654. args[3] = lb_const_int(p->module, t_i32, pos.column);
  10655. args[4] = lb_typeid(p->module, src_type);
  10656. args[5] = lb_typeid(p->module, dst_type);
  10657. lb_emit_runtime_call(p, "type_assertion_check", args);
  10658. lbValue data_ptr = v;
  10659. return lb_emit_conv(p, data_ptr, tv.type);
  10660. } else if (is_type_any(t)) {
  10661. lbValue v = e;
  10662. if (is_type_pointer(v.type)) {
  10663. v = lb_emit_load(p, v);
  10664. }
  10665. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  10666. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  10667. lbValue id = lb_typeid(p->module, type);
  10668. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  10669. auto args = array_make<lbValue>(permanent_allocator(), 6);
  10670. args[0] = ok;
  10671. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  10672. args[2] = lb_const_int(p->module, t_i32, pos.line);
  10673. args[3] = lb_const_int(p->module, t_i32, pos.column);
  10674. args[4] = any_id;
  10675. args[5] = id;
  10676. lb_emit_runtime_call(p, "type_assertion_check", args);
  10677. return lb_emit_conv(p, data_ptr, tv.type);
  10678. } else {
  10679. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  10680. }
  10681. }
  10682. }
  10683. return lb_build_addr_ptr(p, ue->expr);
  10684. }
  10685. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  10686. lbModule *m = p->module;
  10687. u16 prev_state_flags = p->state_flags;
  10688. defer (p->state_flags = prev_state_flags);
  10689. if (expr->state_flags != 0) {
  10690. u16 in = expr->state_flags;
  10691. u16 out = p->state_flags;
  10692. if (in & StateFlag_bounds_check) {
  10693. out |= StateFlag_bounds_check;
  10694. out &= ~StateFlag_no_bounds_check;
  10695. } else if (in & StateFlag_no_bounds_check) {
  10696. out |= StateFlag_no_bounds_check;
  10697. out &= ~StateFlag_bounds_check;
  10698. }
  10699. p->state_flags = out;
  10700. }
  10701. expr = unparen_expr(expr);
  10702. TokenPos expr_pos = ast_token(expr).pos;
  10703. TypeAndValue tv = type_and_value_of_expr(expr);
  10704. 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));
  10705. if (tv.value.kind != ExactValue_Invalid) {
  10706. // NOTE(bill): The commented out code below is just for debug purposes only
  10707. // 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));
  10708. // if (is_type_untyped(tv.type)) {
  10709. // gb_printf_err("%s %s\n", token_pos_to_string(expr_pos), expr_to_string(expr));
  10710. // }
  10711. // NOTE(bill): Short on constant values
  10712. return lb_const_value(p->module, tv.type, tv.value);
  10713. }
  10714. #if 0
  10715. LLVMMetadataRef prev_debug_location = nullptr;
  10716. if (p->debug_info != nullptr) {
  10717. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  10718. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, expr));
  10719. }
  10720. defer (if (prev_debug_location != nullptr) {
  10721. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  10722. });
  10723. #endif
  10724. switch (expr->kind) {
  10725. case_ast_node(bl, BasicLit, expr);
  10726. TokenPos pos = bl->token.pos;
  10727. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(token_strings[bl->token.kind]));
  10728. case_end;
  10729. case_ast_node(bd, BasicDirective, expr);
  10730. TokenPos pos = bd->token.pos;
  10731. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(bd->name.string));
  10732. case_end;
  10733. case_ast_node(i, Implicit, expr);
  10734. return lb_addr_load(p, lb_build_addr(p, expr));
  10735. case_end;
  10736. case_ast_node(u, Undef, expr)
  10737. lbValue res = {};
  10738. if (is_type_untyped(tv.type)) {
  10739. res.value = nullptr;
  10740. res.type = t_untyped_undef;
  10741. } else {
  10742. res.value = LLVMGetUndef(lb_type(m, tv.type));
  10743. res.type = tv.type;
  10744. }
  10745. return res;
  10746. case_end;
  10747. case_ast_node(i, Ident, expr);
  10748. Entity *e = entity_from_expr(expr);
  10749. e = strip_entity_wrapping(e);
  10750. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  10751. if (e->kind == Entity_Builtin) {
  10752. Token token = ast_token(expr);
  10753. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  10754. "\t at %s", LIT(builtin_procs[e->Builtin.id].name),
  10755. token_pos_to_string(token.pos));
  10756. return {};
  10757. } else if (e->kind == Entity_Nil) {
  10758. lbValue res = {};
  10759. res.value = nullptr;
  10760. res.type = e->type;
  10761. return res;
  10762. }
  10763. GB_ASSERT(e->kind != Entity_ProcGroup);
  10764. return lb_find_ident(p, m, e, expr);
  10765. case_end;
  10766. case_ast_node(de, DerefExpr, expr);
  10767. return lb_addr_load(p, lb_build_addr(p, expr));
  10768. case_end;
  10769. case_ast_node(se, SelectorExpr, expr);
  10770. TypeAndValue tav = type_and_value_of_expr(expr);
  10771. GB_ASSERT(tav.mode != Addressing_Invalid);
  10772. return lb_addr_load(p, lb_build_addr(p, expr));
  10773. case_end;
  10774. case_ast_node(ise, ImplicitSelectorExpr, expr);
  10775. TypeAndValue tav = type_and_value_of_expr(expr);
  10776. GB_ASSERT(tav.mode == Addressing_Constant);
  10777. return lb_const_value(p->module, tv.type, tv.value);
  10778. case_end;
  10779. case_ast_node(se, SelectorCallExpr, expr);
  10780. GB_ASSERT(se->modified_call);
  10781. TypeAndValue tav = type_and_value_of_expr(expr);
  10782. GB_ASSERT(tav.mode != Addressing_Invalid);
  10783. lbValue res = lb_build_call_expr(p, se->call);
  10784. ast_node(ce, CallExpr, se->call);
  10785. ce->sce_temp_data = gb_alloc_copy(permanent_allocator(), &res, gb_size_of(res));
  10786. return res;
  10787. case_end;
  10788. case_ast_node(te, TernaryIfExpr, expr);
  10789. LLVMValueRef incoming_values[2] = {};
  10790. LLVMBasicBlockRef incoming_blocks[2] = {};
  10791. GB_ASSERT(te->y != nullptr);
  10792. lbBlock *then = lb_create_block(p, "if.then");
  10793. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  10794. lbBlock *else_ = lb_create_block(p, "if.else");
  10795. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  10796. lb_start_block(p, then);
  10797. Type *type = default_type(type_of_expr(expr));
  10798. lb_open_scope(p, nullptr);
  10799. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  10800. lb_close_scope(p, lbDeferExit_Default, nullptr);
  10801. lb_emit_jump(p, done);
  10802. lb_start_block(p, else_);
  10803. lb_open_scope(p, nullptr);
  10804. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  10805. lb_close_scope(p, lbDeferExit_Default, nullptr);
  10806. lb_emit_jump(p, done);
  10807. lb_start_block(p, done);
  10808. lbValue res = {};
  10809. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  10810. res.type = type;
  10811. GB_ASSERT(p->curr_block->preds.count >= 2);
  10812. incoming_blocks[0] = p->curr_block->preds[0]->block;
  10813. incoming_blocks[1] = p->curr_block->preds[1]->block;
  10814. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  10815. return res;
  10816. case_end;
  10817. case_ast_node(te, TernaryWhenExpr, expr);
  10818. TypeAndValue tav = type_and_value_of_expr(te->cond);
  10819. GB_ASSERT(tav.mode == Addressing_Constant);
  10820. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  10821. if (tav.value.value_bool) {
  10822. return lb_build_expr(p, te->x);
  10823. } else {
  10824. return lb_build_expr(p, te->y);
  10825. }
  10826. case_end;
  10827. case_ast_node(ta, TypeAssertion, expr);
  10828. TokenPos pos = ast_token(expr).pos;
  10829. Type *type = tv.type;
  10830. lbValue e = lb_build_expr(p, ta->expr);
  10831. Type *t = type_deref(e.type);
  10832. if (is_type_union(t)) {
  10833. if (ta->ignores[0]) {
  10834. // NOTE(bill): This is not needed for optimization levels other than 0
  10835. return lb_emit_union_cast_only_ok_check(p, e, type, pos);
  10836. }
  10837. return lb_emit_union_cast(p, e, type, pos);
  10838. } else if (is_type_any(t)) {
  10839. return lb_emit_any_cast(p, e, type, pos);
  10840. } else {
  10841. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  10842. }
  10843. case_end;
  10844. case_ast_node(tc, TypeCast, expr);
  10845. lbValue e = lb_build_expr(p, tc->expr);
  10846. switch (tc->token.kind) {
  10847. case Token_cast:
  10848. return lb_emit_conv(p, e, tv.type);
  10849. case Token_transmute:
  10850. return lb_emit_transmute(p, e, tv.type);
  10851. }
  10852. GB_PANIC("Invalid AST TypeCast");
  10853. case_end;
  10854. case_ast_node(ac, AutoCast, expr);
  10855. lbValue value = lb_build_expr(p, ac->expr);
  10856. return lb_emit_conv(p, value, tv.type);
  10857. case_end;
  10858. case_ast_node(ue, UnaryExpr, expr);
  10859. switch (ue->op.kind) {
  10860. case Token_And:
  10861. return lb_build_unary_and(p, expr);
  10862. default:
  10863. {
  10864. lbValue v = lb_build_expr(p, ue->expr);
  10865. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  10866. }
  10867. }
  10868. case_end;
  10869. case_ast_node(be, BinaryExpr, expr);
  10870. return lb_build_binary_expr(p, expr);
  10871. case_end;
  10872. case_ast_node(pl, ProcLit, expr);
  10873. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  10874. case_end;
  10875. case_ast_node(cl, CompoundLit, expr);
  10876. return lb_addr_load(p, lb_build_addr(p, expr));
  10877. case_end;
  10878. case_ast_node(ce, CallExpr, expr);
  10879. return lb_build_call_expr(p, expr);
  10880. case_end;
  10881. case_ast_node(se, SliceExpr, expr);
  10882. if (is_type_slice(type_of_expr(se->expr))) {
  10883. // NOTE(bill): Quick optimization
  10884. if (se->high == nullptr &&
  10885. (se->low == nullptr || lb_is_expr_constant_zero(se->low))) {
  10886. return lb_build_expr(p, se->expr);
  10887. }
  10888. }
  10889. return lb_addr_load(p, lb_build_addr(p, expr));
  10890. case_end;
  10891. case_ast_node(ie, IndexExpr, expr);
  10892. return lb_addr_load(p, lb_build_addr(p, expr));
  10893. case_end;
  10894. case_ast_node(ia, InlineAsmExpr, expr);
  10895. Type *t = type_of_expr(expr);
  10896. GB_ASSERT(is_type_asm_proc(t));
  10897. String asm_string = {};
  10898. String constraints_string = {};
  10899. TypeAndValue tav;
  10900. tav = type_and_value_of_expr(ia->asm_string);
  10901. GB_ASSERT(is_type_string(tav.type));
  10902. GB_ASSERT(tav.value.kind == ExactValue_String);
  10903. asm_string = tav.value.value_string;
  10904. tav = type_and_value_of_expr(ia->constraints_string);
  10905. GB_ASSERT(is_type_string(tav.type));
  10906. GB_ASSERT(tav.value.kind == ExactValue_String);
  10907. constraints_string = tav.value.value_string;
  10908. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  10909. switch (ia->dialect) {
  10910. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  10911. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  10912. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  10913. default: GB_PANIC("Unhandled inline asm dialect"); break;
  10914. }
  10915. LLVMTypeRef func_type = LLVMGetElementType(lb_type(p->module, t));
  10916. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  10917. cast(char *)asm_string.text, cast(size_t)asm_string.len,
  10918. cast(char *)constraints_string.text, cast(size_t)constraints_string.len,
  10919. ia->has_side_effects, ia->is_align_stack, dialect
  10920. );
  10921. GB_ASSERT(the_asm != nullptr);
  10922. return {the_asm, t};
  10923. case_end;
  10924. }
  10925. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  10926. return {};
  10927. }
  10928. lbAddr lb_get_soa_variable_addr(lbProcedure *p, Entity *e) {
  10929. return map_must_get(&p->module->soa_values, hash_entity(e));
  10930. }
  10931. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  10932. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  10933. String name = e->token.string;
  10934. Entity *parent = e->using_parent;
  10935. Selection sel = lookup_field(parent->type, name, false);
  10936. GB_ASSERT(sel.entity != nullptr);
  10937. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  10938. lbValue v = {};
  10939. if (pv == nullptr && parent->flags & EntityFlag_SoaPtrField) {
  10940. // NOTE(bill): using SOA value (probably from for-in statement)
  10941. lbAddr parent_addr = lb_get_soa_variable_addr(p, parent);
  10942. v = lb_addr_get_ptr(p, parent_addr);
  10943. } else if (pv != nullptr) {
  10944. v = *pv;
  10945. } else {
  10946. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  10947. v = lb_build_addr_ptr(p, e->using_expr);
  10948. }
  10949. GB_ASSERT(v.value != nullptr);
  10950. GB_ASSERT_MSG(parent->type == type_deref(v.type), "%s %s", type_to_string(parent->type), type_to_string(v.type));
  10951. lbValue ptr = lb_emit_deep_field_gep(p, v, sel);
  10952. if (parent->scope) {
  10953. if ((parent->scope->flags & (ScopeFlag_File|ScopeFlag_Pkg)) == 0) {
  10954. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  10955. }
  10956. } else {
  10957. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  10958. }
  10959. return ptr;
  10960. }
  10961. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  10962. GB_ASSERT(e != nullptr);
  10963. if (e->kind == Entity_Constant) {
  10964. Type *t = default_type(type_of_expr(expr));
  10965. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  10966. lbAddr g = lb_add_global_generated(p->module, t, v);
  10967. return g;
  10968. }
  10969. lbValue v = {};
  10970. lbValue *found = map_get(&p->module->values, hash_entity(e));
  10971. if (found) {
  10972. v = *found;
  10973. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  10974. // NOTE(bill): Calculate the using variable every time
  10975. v = lb_get_using_variable(p, e);
  10976. } else if (e->flags & EntityFlag_SoaPtrField) {
  10977. return lb_get_soa_variable_addr(p, e);
  10978. }
  10979. if (v.value == nullptr) {
  10980. return lb_addr(lb_find_value_from_entity(p->module, e));
  10981. // error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  10982. // LIT(p->name),
  10983. // LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  10984. // GB_PANIC("Unknown value");
  10985. }
  10986. return lb_addr(v);
  10987. }
  10988. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  10989. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  10990. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  10991. map_type = base_type(map_type);
  10992. GB_ASSERT(map_type->kind == Type_Map);
  10993. Type *key_type = map_type->Map.key;
  10994. Type *val_type = map_type->Map.value;
  10995. // NOTE(bill): Removes unnecessary allocation if split gep
  10996. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  10997. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  10998. lb_emit_store(p, gep0, m);
  10999. i64 entry_size = type_size_of (map_type->Map.entry_type);
  11000. i64 entry_align = type_align_of (map_type->Map.entry_type);
  11001. i64 key_offset = type_offset_of(map_type->Map.entry_type, 2);
  11002. i64 key_size = type_size_of (map_type->Map.key);
  11003. i64 value_offset = type_offset_of(map_type->Map.entry_type, 3);
  11004. i64 value_size = type_size_of (map_type->Map.value);
  11005. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_get_equal_proc_for_type(p->module, key_type));
  11006. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  11007. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  11008. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, key_offset));
  11009. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, key_size));
  11010. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 6), lb_const_int(p->module, t_uintptr, value_offset));
  11011. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 7), lb_const_int(p->module, t_int, value_size));
  11012. return lb_addr_load(p, h);
  11013. }
  11014. lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  11015. if (true) {
  11016. return {};
  11017. }
  11018. lbValue hashed_key = {};
  11019. if (lb_is_const(key)) {
  11020. u64 hash = 0xcbf29ce484222325;
  11021. if (is_type_cstring(key_type)) {
  11022. size_t length = 0;
  11023. char const *text = LLVMGetAsString(key.value, &length);
  11024. hash = fnv64a(text, cast(isize)length);
  11025. } else if (is_type_string(key_type)) {
  11026. unsigned data_indices[] = {0};
  11027. unsigned len_indices[] = {1};
  11028. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  11029. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  11030. i64 length = LLVMConstIntGetSExtValue(len);
  11031. char const *text = nullptr;
  11032. if (false && length != 0) {
  11033. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  11034. return {};
  11035. }
  11036. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  11037. size_t ulength = 0;
  11038. text = LLVMGetAsString(data, &ulength);
  11039. gb_printf_err("%td %td %s\n", length, ulength, text);
  11040. length = gb_min(length, cast(i64)ulength);
  11041. }
  11042. hash = fnv64a(text, cast(isize)length);
  11043. } else {
  11044. return {};
  11045. }
  11046. // TODO(bill): other const hash types
  11047. if (build_context.word_size == 4) {
  11048. hash &= 0xffffffffull;
  11049. }
  11050. hashed_key = lb_const_int(m, t_uintptr, hash);
  11051. }
  11052. return hashed_key;
  11053. }
  11054. lbValue lb_gen_map_hash(lbProcedure *p, lbValue key, Type *key_type) {
  11055. Type *hash_type = t_u64;
  11056. lbAddr v = lb_add_local_generated(p, t_map_hash, true);
  11057. lbValue vp = lb_addr_get_ptr(p, v);
  11058. Type *t = base_type(key.type);
  11059. key = lb_emit_conv(p, key, key_type);
  11060. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  11061. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  11062. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  11063. if (hashed_key.value == nullptr) {
  11064. lbValue hasher = lb_get_hasher_proc_for_type(p->module, key_type);
  11065. auto args = array_make<lbValue>(permanent_allocator(), 2);
  11066. args[0] = key_ptr;
  11067. args[1] = lb_const_int(p->module, t_uintptr, 0);
  11068. hashed_key = lb_emit_call(p, hasher, args);
  11069. }
  11070. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_key);
  11071. lb_emit_store(p, lb_emit_struct_ep(p, vp, 1), key_ptr);
  11072. return lb_addr_load(p, v);
  11073. }
  11074. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  11075. lbValue map_key, lbValue map_value, Ast *node) {
  11076. map_type = base_type(map_type);
  11077. GB_ASSERT(map_type->kind == Type_Map);
  11078. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  11079. lbValue key = lb_gen_map_hash(p, map_key, map_type->Map.key);
  11080. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  11081. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  11082. lb_addr_store(p, value_addr, v);
  11083. auto args = array_make<lbValue>(permanent_allocator(), 4);
  11084. args[0] = h;
  11085. args[1] = key;
  11086. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  11087. args[3] = lb_emit_source_code_location(p, node);
  11088. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  11089. }
  11090. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  11091. expr = unparen_expr(expr);
  11092. switch (expr->kind) {
  11093. case_ast_node(i, Implicit, expr);
  11094. lbAddr v = {};
  11095. switch (i->kind) {
  11096. case Token_context:
  11097. v = lb_find_or_generate_context_ptr(p);
  11098. break;
  11099. }
  11100. GB_ASSERT(v.addr.value != nullptr);
  11101. return v;
  11102. case_end;
  11103. case_ast_node(i, Ident, expr);
  11104. if (is_blank_ident(expr)) {
  11105. lbAddr val = {};
  11106. return val;
  11107. }
  11108. String name = i->token.string;
  11109. Entity *e = entity_of_node(expr);
  11110. return lb_build_addr_from_entity(p, e, expr);
  11111. case_end;
  11112. case_ast_node(se, SelectorExpr, expr);
  11113. Ast *sel = unparen_expr(se->selector);
  11114. if (sel->kind == Ast_Ident) {
  11115. String selector = sel->Ident.token.string;
  11116. TypeAndValue tav = type_and_value_of_expr(se->expr);
  11117. if (tav.mode == Addressing_Invalid) {
  11118. // NOTE(bill): Imports
  11119. Entity *imp = entity_of_node(se->expr);
  11120. if (imp != nullptr) {
  11121. GB_ASSERT(imp->kind == Entity_ImportName);
  11122. }
  11123. return lb_build_addr(p, unparen_expr(se->selector));
  11124. }
  11125. Type *type = base_type(tav.type);
  11126. if (tav.mode == Addressing_Type) { // Addressing_Type
  11127. GB_PANIC("Unreachable");
  11128. }
  11129. if (se->swizzle_count > 0) {
  11130. Type *array_type = base_type(type_deref(tav.type));
  11131. GB_ASSERT(array_type->kind == Type_Array);
  11132. u8 swizzle_count = se->swizzle_count;
  11133. u8 swizzle_indices_raw = se->swizzle_indices;
  11134. u8 swizzle_indices[4] = {};
  11135. for (u8 i = 0; i < swizzle_count; i++) {
  11136. u8 index = swizzle_indices_raw>>(i*2) & 3;
  11137. swizzle_indices[i] = index;
  11138. }
  11139. lbValue a = {};
  11140. if (is_type_pointer(tav.type)) {
  11141. a = lb_build_expr(p, se->expr);
  11142. } else {
  11143. lbAddr addr = lb_build_addr(p, se->expr);
  11144. a = lb_addr_get_ptr(p, addr);
  11145. }
  11146. GB_ASSERT(is_type_array(expr->tav.type));
  11147. return lb_addr_swizzle(a, expr->tav.type, swizzle_count, swizzle_indices);
  11148. }
  11149. Selection sel = lookup_field(type, selector, false);
  11150. GB_ASSERT(sel.entity != nullptr);
  11151. {
  11152. lbAddr addr = lb_build_addr(p, se->expr);
  11153. if (addr.kind == lbAddr_Map) {
  11154. lbValue v = lb_addr_load(p, addr);
  11155. lbValue a = lb_address_from_load_or_generate_local(p, v);
  11156. a = lb_emit_deep_field_gep(p, a, sel);
  11157. return lb_addr(a);
  11158. } else if (addr.kind == lbAddr_Context) {
  11159. GB_ASSERT(sel.index.count > 0);
  11160. if (addr.ctx.sel.index.count >= 0) {
  11161. sel = selection_combine(addr.ctx.sel, sel);
  11162. }
  11163. addr.ctx.sel = sel;
  11164. addr.kind = lbAddr_Context;
  11165. return addr;
  11166. } else if (addr.kind == lbAddr_SoaVariable) {
  11167. lbValue index = addr.soa.index;
  11168. i32 first_index = sel.index[0];
  11169. Selection sub_sel = sel;
  11170. sub_sel.index.data += 1;
  11171. sub_sel.index.count -= 1;
  11172. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  11173. Type *t = base_type(type_deref(addr.addr.type));
  11174. GB_ASSERT(is_type_soa_struct(t));
  11175. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  11176. lbValue len = lb_soa_struct_len(p, addr.addr);
  11177. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  11178. }
  11179. lbValue item = {};
  11180. if (t->Struct.soa_kind == StructSoa_Fixed) {
  11181. item = lb_emit_array_ep(p, arr, index);
  11182. } else {
  11183. item = lb_emit_ptr_offset(p, lb_emit_load(p, arr), index);
  11184. }
  11185. if (sub_sel.index.count > 0) {
  11186. item = lb_emit_deep_field_gep(p, item, sub_sel);
  11187. }
  11188. return lb_addr(item);
  11189. } else if (addr.kind == lbAddr_Swizzle) {
  11190. GB_ASSERT(sel.index.count > 0);
  11191. // NOTE(bill): just patch the index in place
  11192. sel.index[0] = addr.swizzle.indices[sel.index[0]];
  11193. }
  11194. lbValue a = lb_addr_get_ptr(p, addr);
  11195. a = lb_emit_deep_field_gep(p, a, sel);
  11196. return lb_addr(a);
  11197. }
  11198. } else {
  11199. GB_PANIC("Unsupported selector expression");
  11200. }
  11201. case_end;
  11202. case_ast_node(se, SelectorCallExpr, expr);
  11203. GB_ASSERT(se->modified_call);
  11204. TypeAndValue tav = type_and_value_of_expr(expr);
  11205. GB_ASSERT(tav.mode != Addressing_Invalid);
  11206. lbValue e = lb_build_expr(p, expr);
  11207. return lb_addr(lb_address_from_load_or_generate_local(p, e));
  11208. case_end;
  11209. case_ast_node(ta, TypeAssertion, expr);
  11210. TokenPos pos = ast_token(expr).pos;
  11211. lbValue e = lb_build_expr(p, ta->expr);
  11212. Type *t = type_deref(e.type);
  11213. if (is_type_union(t)) {
  11214. Type *type = type_of_expr(expr);
  11215. lbAddr v = lb_add_local_generated(p, type, false);
  11216. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  11217. return v;
  11218. } else if (is_type_any(t)) {
  11219. Type *type = type_of_expr(expr);
  11220. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  11221. } else {
  11222. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  11223. }
  11224. case_end;
  11225. case_ast_node(ue, UnaryExpr, expr);
  11226. switch (ue->op.kind) {
  11227. case Token_And:
  11228. return lb_build_addr(p, ue->expr);
  11229. default:
  11230. GB_PANIC("Invalid unary expression for lb_build_addr");
  11231. }
  11232. case_end;
  11233. case_ast_node(be, BinaryExpr, expr);
  11234. lbValue v = lb_build_expr(p, expr);
  11235. Type *t = v.type;
  11236. if (is_type_pointer(t)) {
  11237. return lb_addr(v);
  11238. }
  11239. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  11240. case_end;
  11241. case_ast_node(ie, IndexExpr, expr);
  11242. Type *t = base_type(type_of_expr(ie->expr));
  11243. bool deref = is_type_pointer(t);
  11244. t = base_type(type_deref(t));
  11245. if (is_type_soa_struct(t)) {
  11246. // SOA STRUCTURES!!!!
  11247. lbValue val = lb_build_addr_ptr(p, ie->expr);
  11248. if (deref) {
  11249. val = lb_emit_load(p, val);
  11250. }
  11251. lbValue index = lb_build_expr(p, ie->index);
  11252. return lb_addr_soa_variable(val, index, ie->index);
  11253. }
  11254. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  11255. // SOA Structures for slices/dynamic arrays
  11256. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  11257. lbValue field = lb_build_expr(p, ie->expr);
  11258. lbValue index = lb_build_expr(p, ie->index);
  11259. if (!build_context.no_bounds_check) {
  11260. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  11261. // GB_ASSERT(LLVMIsALoadInst(field.value));
  11262. // lbValue a = {};
  11263. // a.value = LLVMGetOperand(field.value, 0);
  11264. // a.type = alloc_type_pointer(field.type);
  11265. // irInstr *b = &a->Instr;
  11266. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  11267. // lbValue base_struct = b->StructElementPtr.address;
  11268. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  11269. // lbValue len = ir_soa_struct_len(p, base_struct);
  11270. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  11271. }
  11272. lbValue val = lb_emit_ptr_offset(p, field, index);
  11273. return lb_addr(val);
  11274. }
  11275. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  11276. if (is_type_map(t)) {
  11277. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  11278. if (deref) {
  11279. map_val = lb_emit_load(p, map_val);
  11280. }
  11281. lbValue key = lb_build_expr(p, ie->index);
  11282. key = lb_emit_conv(p, key, t->Map.key);
  11283. Type *result_type = type_of_expr(expr);
  11284. return lb_addr_map(map_val, key, t, result_type);
  11285. }
  11286. switch (t->kind) {
  11287. case Type_Array: {
  11288. lbValue array = {};
  11289. array = lb_build_addr_ptr(p, ie->expr);
  11290. if (deref) {
  11291. array = lb_emit_load(p, array);
  11292. }
  11293. lbValue index = lb_build_expr(p, ie->index);
  11294. index = lb_emit_conv(p, index, t_int);
  11295. lbValue elem = lb_emit_array_ep(p, array, index);
  11296. auto index_tv = type_and_value_of_expr(ie->index);
  11297. if (index_tv.mode != Addressing_Constant) {
  11298. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  11299. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  11300. }
  11301. return lb_addr(elem);
  11302. }
  11303. case Type_EnumeratedArray: {
  11304. lbValue array = {};
  11305. array = lb_build_addr_ptr(p, ie->expr);
  11306. if (deref) {
  11307. array = lb_emit_load(p, array);
  11308. }
  11309. Type *index_type = t->EnumeratedArray.index;
  11310. auto index_tv = type_and_value_of_expr(ie->index);
  11311. lbValue index = {};
  11312. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  11313. if (index_tv.mode == Addressing_Constant) {
  11314. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  11315. index = lb_const_value(p->module, index_type, idx);
  11316. } else {
  11317. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  11318. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  11319. }
  11320. } else {
  11321. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  11322. }
  11323. lbValue elem = lb_emit_array_ep(p, array, index);
  11324. if (index_tv.mode != Addressing_Constant) {
  11325. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  11326. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  11327. }
  11328. return lb_addr(elem);
  11329. }
  11330. case Type_Slice: {
  11331. lbValue slice = {};
  11332. slice = lb_build_expr(p, ie->expr);
  11333. if (deref) {
  11334. slice = lb_emit_load(p, slice);
  11335. }
  11336. lbValue elem = lb_slice_elem(p, slice);
  11337. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  11338. lbValue len = lb_slice_len(p, slice);
  11339. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  11340. lbValue v = lb_emit_ptr_offset(p, elem, index);
  11341. return lb_addr(v);
  11342. }
  11343. case Type_RelativeSlice: {
  11344. lbAddr slice_addr = {};
  11345. if (deref) {
  11346. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  11347. } else {
  11348. slice_addr = lb_build_addr(p, ie->expr);
  11349. }
  11350. lbValue slice = lb_addr_load(p, slice_addr);
  11351. lbValue elem = lb_slice_elem(p, slice);
  11352. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  11353. lbValue len = lb_slice_len(p, slice);
  11354. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  11355. lbValue v = lb_emit_ptr_offset(p, elem, index);
  11356. return lb_addr(v);
  11357. }
  11358. case Type_DynamicArray: {
  11359. lbValue dynamic_array = {};
  11360. dynamic_array = lb_build_expr(p, ie->expr);
  11361. if (deref) {
  11362. dynamic_array = lb_emit_load(p, dynamic_array);
  11363. }
  11364. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  11365. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  11366. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  11367. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  11368. lbValue v = lb_emit_ptr_offset(p, elem, index);
  11369. return lb_addr(v);
  11370. }
  11371. case Type_Basic: { // Basic_string
  11372. lbValue str;
  11373. lbValue elem;
  11374. lbValue len;
  11375. lbValue index;
  11376. str = lb_build_expr(p, ie->expr);
  11377. if (deref) {
  11378. str = lb_emit_load(p, str);
  11379. }
  11380. elem = lb_string_elem(p, str);
  11381. len = lb_string_len(p, str);
  11382. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  11383. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  11384. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  11385. }
  11386. }
  11387. case_end;
  11388. case_ast_node(se, SliceExpr, expr);
  11389. lbValue low = lb_const_int(p->module, t_int, 0);
  11390. lbValue high = {};
  11391. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  11392. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  11393. bool no_indices = se->low == nullptr && se->high == nullptr;
  11394. lbAddr addr = lb_build_addr(p, se->expr);
  11395. lbValue base = lb_addr_load(p, addr);
  11396. Type *type = base_type(base.type);
  11397. if (is_type_pointer(type)) {
  11398. type = base_type(type_deref(type));
  11399. addr = lb_addr(base);
  11400. base = lb_addr_load(p, addr);
  11401. }
  11402. switch (type->kind) {
  11403. case Type_Slice: {
  11404. Type *slice_type = type;
  11405. lbValue len = lb_slice_len(p, base);
  11406. if (high.value == nullptr) high = len;
  11407. if (!no_indices) {
  11408. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  11409. }
  11410. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  11411. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  11412. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  11413. lb_fill_slice(p, slice, elem, new_len);
  11414. return slice;
  11415. }
  11416. case Type_RelativeSlice:
  11417. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  11418. break;
  11419. case Type_DynamicArray: {
  11420. Type *elem_type = type->DynamicArray.elem;
  11421. Type *slice_type = alloc_type_slice(elem_type);
  11422. lbValue len = lb_dynamic_array_len(p, base);
  11423. if (high.value == nullptr) high = len;
  11424. if (!no_indices) {
  11425. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  11426. }
  11427. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  11428. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  11429. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  11430. lb_fill_slice(p, slice, elem, new_len);
  11431. return slice;
  11432. }
  11433. case Type_Array: {
  11434. Type *slice_type = alloc_type_slice(type->Array.elem);
  11435. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  11436. if (high.value == nullptr) high = len;
  11437. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  11438. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  11439. if (!low_const || !high_const) {
  11440. if (!no_indices) {
  11441. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  11442. }
  11443. }
  11444. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  11445. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  11446. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  11447. lb_fill_slice(p, slice, elem, new_len);
  11448. return slice;
  11449. }
  11450. case Type_Basic: {
  11451. GB_ASSERT(type == t_string);
  11452. lbValue len = lb_string_len(p, base);
  11453. if (high.value == nullptr) high = len;
  11454. if (!no_indices) {
  11455. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  11456. }
  11457. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  11458. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  11459. lbAddr str = lb_add_local_generated(p, t_string, false);
  11460. lb_fill_string(p, str, elem, new_len);
  11461. return str;
  11462. }
  11463. case Type_Struct:
  11464. if (is_type_soa_struct(type)) {
  11465. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  11466. if (high.value == nullptr) high = len;
  11467. if (!no_indices) {
  11468. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  11469. }
  11470. #if 1
  11471. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  11472. if (type->Struct.soa_kind == StructSoa_Fixed) {
  11473. i32 field_count = cast(i32)type->Struct.fields.count;
  11474. for (i32 i = 0; i < field_count; i++) {
  11475. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  11476. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  11477. field_src = lb_emit_array_ep(p, field_src, low);
  11478. lb_emit_store(p, field_dst, field_src);
  11479. }
  11480. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  11481. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  11482. lb_emit_store(p, len_dst, new_len);
  11483. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  11484. if (no_indices) {
  11485. lb_addr_store(p, dst, base);
  11486. } else {
  11487. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  11488. for (i32 i = 0; i < field_count; i++) {
  11489. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  11490. lbValue field_src = lb_emit_struct_ev(p, base, i);
  11491. field_src = lb_emit_ptr_offset(p, field_src, low);
  11492. lb_emit_store(p, field_dst, field_src);
  11493. }
  11494. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  11495. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  11496. lb_emit_store(p, len_dst, new_len);
  11497. }
  11498. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  11499. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  11500. for (i32 i = 0; i < field_count; i++) {
  11501. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  11502. lbValue field_src = lb_emit_struct_ev(p, base, i);
  11503. field_src = lb_emit_ptr_offset(p, field_src, low);
  11504. lb_emit_store(p, field_dst, field_src);
  11505. }
  11506. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  11507. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  11508. lb_emit_store(p, len_dst, new_len);
  11509. }
  11510. return dst;
  11511. #endif
  11512. }
  11513. break;
  11514. }
  11515. GB_PANIC("Unknown slicable type");
  11516. case_end;
  11517. case_ast_node(de, DerefExpr, expr);
  11518. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  11519. lbAddr addr = lb_build_addr(p, de->expr);
  11520. addr.relative.deref = true;
  11521. return addr;\
  11522. }
  11523. lbValue addr = lb_build_expr(p, de->expr);
  11524. return lb_addr(addr);
  11525. case_end;
  11526. case_ast_node(ce, CallExpr, expr);
  11527. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  11528. lbValue e = lb_build_expr(p, expr);
  11529. #if 1
  11530. return lb_addr(lb_address_from_load_or_generate_local(p, e));
  11531. #else
  11532. lbAddr v = lb_add_local_generated(p, e.type, false);
  11533. lb_addr_store(p, v, e);
  11534. return v;
  11535. #endif
  11536. case_end;
  11537. case_ast_node(cl, CompoundLit, expr);
  11538. Type *type = type_of_expr(expr);
  11539. Type *bt = base_type(type);
  11540. lbAddr v = lb_add_local_generated(p, type, true);
  11541. Type *et = nullptr;
  11542. switch (bt->kind) {
  11543. case Type_Array: et = bt->Array.elem; break;
  11544. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  11545. case Type_Slice: et = bt->Slice.elem; break;
  11546. case Type_BitSet: et = bt->BitSet.elem; break;
  11547. case Type_SimdVector: et = bt->SimdVector.elem; break;
  11548. }
  11549. String proc_name = {};
  11550. if (p->entity) {
  11551. proc_name = p->entity->token.string;
  11552. }
  11553. TokenPos pos = ast_token(expr).pos;
  11554. switch (bt->kind) {
  11555. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  11556. case Type_Struct: {
  11557. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  11558. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  11559. bool is_raw_union = is_type_raw_union(bt);
  11560. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  11561. TypeStruct *st = &bt->Struct;
  11562. if (cl->elems.count > 0) {
  11563. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  11564. lbValue comp_lit_ptr = lb_addr_get_ptr(p, v);
  11565. for_array(field_index, cl->elems) {
  11566. Ast *elem = cl->elems[field_index];
  11567. lbValue field_expr = {};
  11568. Entity *field = nullptr;
  11569. isize index = field_index;
  11570. if (elem->kind == Ast_FieldValue) {
  11571. ast_node(fv, FieldValue, elem);
  11572. String name = fv->field->Ident.token.string;
  11573. Selection sel = lookup_field(bt, name, false);
  11574. index = sel.index[0];
  11575. elem = fv->value;
  11576. TypeAndValue tav = type_and_value_of_expr(elem);
  11577. } else {
  11578. TypeAndValue tav = type_and_value_of_expr(elem);
  11579. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  11580. index = sel.index[0];
  11581. }
  11582. field = st->fields[index];
  11583. Type *ft = field->type;
  11584. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  11585. continue;
  11586. }
  11587. field_expr = lb_build_expr(p, elem);
  11588. lbValue gep = {};
  11589. if (is_raw_union) {
  11590. gep = lb_emit_conv(p, comp_lit_ptr, alloc_type_pointer(ft));
  11591. } else {
  11592. gep = lb_emit_struct_ep(p, comp_lit_ptr, cast(i32)index);
  11593. }
  11594. Type *fet = field_expr.type;
  11595. GB_ASSERT(fet->kind != Type_Tuple);
  11596. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  11597. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  11598. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  11599. lb_emit_store_union_variant(p, gep, field_expr, fet);
  11600. } else {
  11601. lbValue fv = lb_emit_conv(p, field_expr, ft);
  11602. lb_emit_store(p, gep, fv);
  11603. }
  11604. }
  11605. }
  11606. break;
  11607. }
  11608. case Type_Map: {
  11609. if (cl->elems.count == 0) {
  11610. break;
  11611. }
  11612. {
  11613. auto args = array_make<lbValue>(permanent_allocator(), 3);
  11614. args[0] = lb_gen_map_header(p, v.addr, type);
  11615. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  11616. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  11617. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  11618. }
  11619. for_array(field_index, cl->elems) {
  11620. Ast *elem = cl->elems[field_index];
  11621. ast_node(fv, FieldValue, elem);
  11622. lbValue key = lb_build_expr(p, fv->field);
  11623. lbValue value = lb_build_expr(p, fv->value);
  11624. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  11625. }
  11626. break;
  11627. }
  11628. case Type_Array: {
  11629. if (cl->elems.count > 0) {
  11630. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  11631. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  11632. // NOTE(bill): Separate value, gep, store into their own chunks
  11633. for_array(i, cl->elems) {
  11634. Ast *elem = cl->elems[i];
  11635. if (elem->kind == Ast_FieldValue) {
  11636. ast_node(fv, FieldValue, elem);
  11637. if (lb_is_elem_const(fv->value, et)) {
  11638. continue;
  11639. }
  11640. if (is_ast_range(fv->field)) {
  11641. ast_node(ie, BinaryExpr, fv->field);
  11642. TypeAndValue lo_tav = ie->left->tav;
  11643. TypeAndValue hi_tav = ie->right->tav;
  11644. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  11645. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  11646. TokenKind op = ie->op.kind;
  11647. i64 lo = exact_value_to_i64(lo_tav.value);
  11648. i64 hi = exact_value_to_i64(hi_tav.value);
  11649. if (op != Token_RangeHalf) {
  11650. hi += 1;
  11651. }
  11652. lbValue value = lb_build_expr(p, fv->value);
  11653. for (i64 k = lo; k < hi; k++) {
  11654. lbCompoundLitElemTempData data = {};
  11655. data.value = value;
  11656. data.elem_index = cast(i32)k;
  11657. array_add(&temp_data, data);
  11658. }
  11659. } else {
  11660. auto tav = fv->field->tav;
  11661. GB_ASSERT(tav.mode == Addressing_Constant);
  11662. i64 index = exact_value_to_i64(tav.value);
  11663. lbValue value = lb_build_expr(p, fv->value);
  11664. lbCompoundLitElemTempData data = {};
  11665. data.value = lb_emit_conv(p, value, et);
  11666. data.expr = fv->value;
  11667. data.elem_index = cast(i32)index;
  11668. array_add(&temp_data, data);
  11669. }
  11670. } else {
  11671. if (lb_is_elem_const(elem, et)) {
  11672. continue;
  11673. }
  11674. lbCompoundLitElemTempData data = {};
  11675. data.expr = elem;
  11676. data.elem_index = cast(i32)i;
  11677. array_add(&temp_data, data);
  11678. }
  11679. }
  11680. for_array(i, temp_data) {
  11681. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  11682. }
  11683. for_array(i, temp_data) {
  11684. lbValue field_expr = temp_data[i].value;
  11685. Ast *expr = temp_data[i].expr;
  11686. auto prev_hint = lb_set_copy_elision_hint(p, lb_addr(temp_data[i].gep), expr);
  11687. if (field_expr.value == nullptr) {
  11688. field_expr = lb_build_expr(p, expr);
  11689. }
  11690. Type *t = field_expr.type;
  11691. GB_ASSERT(t->kind != Type_Tuple);
  11692. lbValue ev = lb_emit_conv(p, field_expr, et);
  11693. if (!p->copy_elision_hint.used) {
  11694. temp_data[i].value = ev;
  11695. }
  11696. lb_reset_copy_elision_hint(p, prev_hint);
  11697. }
  11698. for_array(i, temp_data) {
  11699. if (temp_data[i].value.value != nullptr) {
  11700. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  11701. }
  11702. }
  11703. }
  11704. break;
  11705. }
  11706. case Type_EnumeratedArray: {
  11707. if (cl->elems.count > 0) {
  11708. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  11709. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  11710. // NOTE(bill): Separate value, gep, store into their own chunks
  11711. for_array(i, cl->elems) {
  11712. Ast *elem = cl->elems[i];
  11713. if (elem->kind == Ast_FieldValue) {
  11714. ast_node(fv, FieldValue, elem);
  11715. if (lb_is_elem_const(fv->value, et)) {
  11716. continue;
  11717. }
  11718. if (is_ast_range(fv->field)) {
  11719. ast_node(ie, BinaryExpr, fv->field);
  11720. TypeAndValue lo_tav = ie->left->tav;
  11721. TypeAndValue hi_tav = ie->right->tav;
  11722. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  11723. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  11724. TokenKind op = ie->op.kind;
  11725. i64 lo = exact_value_to_i64(lo_tav.value);
  11726. i64 hi = exact_value_to_i64(hi_tav.value);
  11727. if (op != Token_RangeHalf) {
  11728. hi += 1;
  11729. }
  11730. lbValue value = lb_build_expr(p, fv->value);
  11731. for (i64 k = lo; k < hi; k++) {
  11732. lbCompoundLitElemTempData data = {};
  11733. data.value = value;
  11734. data.elem_index = cast(i32)k;
  11735. array_add(&temp_data, data);
  11736. }
  11737. } else {
  11738. auto tav = fv->field->tav;
  11739. GB_ASSERT(tav.mode == Addressing_Constant);
  11740. i64 index = exact_value_to_i64(tav.value);
  11741. lbValue value = lb_build_expr(p, fv->value);
  11742. lbCompoundLitElemTempData data = {};
  11743. data.value = lb_emit_conv(p, value, et);
  11744. data.expr = fv->value;
  11745. data.elem_index = cast(i32)index;
  11746. array_add(&temp_data, data);
  11747. }
  11748. } else {
  11749. if (lb_is_elem_const(elem, et)) {
  11750. continue;
  11751. }
  11752. lbCompoundLitElemTempData data = {};
  11753. data.expr = elem;
  11754. data.elem_index = cast(i32)i;
  11755. array_add(&temp_data, data);
  11756. }
  11757. }
  11758. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  11759. for_array(i, temp_data) {
  11760. i32 index = temp_data[i].elem_index - index_offset;
  11761. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  11762. }
  11763. for_array(i, temp_data) {
  11764. lbValue field_expr = temp_data[i].value;
  11765. Ast *expr = temp_data[i].expr;
  11766. auto prev_hint = lb_set_copy_elision_hint(p, lb_addr(temp_data[i].gep), expr);
  11767. if (field_expr.value == nullptr) {
  11768. field_expr = lb_build_expr(p, expr);
  11769. }
  11770. Type *t = field_expr.type;
  11771. GB_ASSERT(t->kind != Type_Tuple);
  11772. lbValue ev = lb_emit_conv(p, field_expr, et);
  11773. if (!p->copy_elision_hint.used) {
  11774. temp_data[i].value = ev;
  11775. }
  11776. lb_reset_copy_elision_hint(p, prev_hint);
  11777. }
  11778. for_array(i, temp_data) {
  11779. if (temp_data[i].value.value != nullptr) {
  11780. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  11781. }
  11782. }
  11783. }
  11784. break;
  11785. }
  11786. case Type_Slice: {
  11787. if (cl->elems.count > 0) {
  11788. Type *elem_type = bt->Slice.elem;
  11789. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  11790. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  11791. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  11792. lbValue data = lb_slice_elem(p, slice);
  11793. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  11794. for_array(i, cl->elems) {
  11795. Ast *elem = cl->elems[i];
  11796. if (elem->kind == Ast_FieldValue) {
  11797. ast_node(fv, FieldValue, elem);
  11798. if (lb_is_elem_const(fv->value, et)) {
  11799. continue;
  11800. }
  11801. if (is_ast_range(fv->field)) {
  11802. ast_node(ie, BinaryExpr, fv->field);
  11803. TypeAndValue lo_tav = ie->left->tav;
  11804. TypeAndValue hi_tav = ie->right->tav;
  11805. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  11806. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  11807. TokenKind op = ie->op.kind;
  11808. i64 lo = exact_value_to_i64(lo_tav.value);
  11809. i64 hi = exact_value_to_i64(hi_tav.value);
  11810. if (op != Token_RangeHalf) {
  11811. hi += 1;
  11812. }
  11813. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  11814. for (i64 k = lo; k < hi; k++) {
  11815. lbCompoundLitElemTempData data = {};
  11816. data.value = value;
  11817. data.elem_index = cast(i32)k;
  11818. array_add(&temp_data, data);
  11819. }
  11820. } else {
  11821. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  11822. i64 index = exact_value_to_i64(fv->field->tav.value);
  11823. lbValue field_expr = lb_build_expr(p, fv->value);
  11824. GB_ASSERT(!is_type_tuple(field_expr.type));
  11825. lbValue ev = lb_emit_conv(p, field_expr, et);
  11826. lbCompoundLitElemTempData data = {};
  11827. data.value = ev;
  11828. data.elem_index = cast(i32)index;
  11829. array_add(&temp_data, data);
  11830. }
  11831. } else {
  11832. if (lb_is_elem_const(elem, et)) {
  11833. continue;
  11834. }
  11835. lbValue field_expr = lb_build_expr(p, elem);
  11836. GB_ASSERT(!is_type_tuple(field_expr.type));
  11837. lbValue ev = lb_emit_conv(p, field_expr, et);
  11838. lbCompoundLitElemTempData data = {};
  11839. data.value = ev;
  11840. data.elem_index = cast(i32)i;
  11841. array_add(&temp_data, data);
  11842. }
  11843. }
  11844. for_array(i, temp_data) {
  11845. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  11846. }
  11847. for_array(i, temp_data) {
  11848. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  11849. }
  11850. {
  11851. lbValue count = {};
  11852. count.type = t_int;
  11853. if (lb_is_const(slice)) {
  11854. unsigned indices[1] = {1};
  11855. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  11856. } else {
  11857. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  11858. }
  11859. lb_fill_slice(p, v, data, count);
  11860. }
  11861. }
  11862. break;
  11863. }
  11864. case Type_DynamicArray: {
  11865. if (cl->elems.count == 0) {
  11866. break;
  11867. }
  11868. Type *et = bt->DynamicArray.elem;
  11869. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  11870. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  11871. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  11872. {
  11873. auto args = array_make<lbValue>(permanent_allocator(), 5);
  11874. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  11875. args[1] = size;
  11876. args[2] = align;
  11877. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  11878. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  11879. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  11880. }
  11881. lbValue items = lb_generate_local_array(p, et, item_count);
  11882. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  11883. for_array(i, cl->elems) {
  11884. Ast *elem = cl->elems[i];
  11885. if (elem->kind == Ast_FieldValue) {
  11886. ast_node(fv, FieldValue, elem);
  11887. if (is_ast_range(fv->field)) {
  11888. ast_node(ie, BinaryExpr, fv->field);
  11889. TypeAndValue lo_tav = ie->left->tav;
  11890. TypeAndValue hi_tav = ie->right->tav;
  11891. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  11892. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  11893. TokenKind op = ie->op.kind;
  11894. i64 lo = exact_value_to_i64(lo_tav.value);
  11895. i64 hi = exact_value_to_i64(hi_tav.value);
  11896. if (op != Token_RangeHalf) {
  11897. hi += 1;
  11898. }
  11899. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  11900. for (i64 k = lo; k < hi; k++) {
  11901. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  11902. lb_emit_store(p, ep, value);
  11903. }
  11904. } else {
  11905. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  11906. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  11907. lbValue ev = lb_build_expr(p, fv->value);
  11908. lbValue value = lb_emit_conv(p, ev, et);
  11909. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  11910. lb_emit_store(p, ep, value);
  11911. }
  11912. } else {
  11913. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  11914. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  11915. lb_emit_store(p, ep, value);
  11916. }
  11917. }
  11918. {
  11919. auto args = array_make<lbValue>(permanent_allocator(), 6);
  11920. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  11921. args[1] = size;
  11922. args[2] = align;
  11923. args[3] = lb_emit_conv(p, items, t_rawptr);
  11924. args[4] = lb_const_int(p->module, t_int, item_count);
  11925. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  11926. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  11927. }
  11928. break;
  11929. }
  11930. case Type_Basic: {
  11931. GB_ASSERT(is_type_any(bt));
  11932. if (cl->elems.count > 0) {
  11933. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  11934. String field_names[2] = {
  11935. str_lit("data"),
  11936. str_lit("id"),
  11937. };
  11938. Type *field_types[2] = {
  11939. t_rawptr,
  11940. t_typeid,
  11941. };
  11942. for_array(field_index, cl->elems) {
  11943. Ast *elem = cl->elems[field_index];
  11944. lbValue field_expr = {};
  11945. isize index = field_index;
  11946. if (elem->kind == Ast_FieldValue) {
  11947. ast_node(fv, FieldValue, elem);
  11948. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  11949. index = sel.index[0];
  11950. elem = fv->value;
  11951. } else {
  11952. TypeAndValue tav = type_and_value_of_expr(elem);
  11953. Selection sel = lookup_field(bt, field_names[field_index], false);
  11954. index = sel.index[0];
  11955. }
  11956. field_expr = lb_build_expr(p, elem);
  11957. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  11958. Type *ft = field_types[index];
  11959. lbValue fv = lb_emit_conv(p, field_expr, ft);
  11960. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  11961. lb_emit_store(p, gep, fv);
  11962. }
  11963. }
  11964. break;
  11965. }
  11966. case Type_BitSet: {
  11967. i64 sz = type_size_of(type);
  11968. if (cl->elems.count > 0 && sz > 0) {
  11969. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  11970. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  11971. for_array(i, cl->elems) {
  11972. Ast *elem = cl->elems[i];
  11973. GB_ASSERT(elem->kind != Ast_FieldValue);
  11974. if (lb_is_elem_const(elem, et)) {
  11975. continue;
  11976. }
  11977. lbValue expr = lb_build_expr(p, elem);
  11978. GB_ASSERT(expr.type->kind != Type_Tuple);
  11979. Type *it = bit_set_to_int(bt);
  11980. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  11981. lbValue e = lb_emit_conv(p, expr, it);
  11982. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  11983. e = lb_emit_arith(p, Token_Shl, one, e, it);
  11984. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  11985. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  11986. new_value = lb_emit_transmute(p, new_value, type);
  11987. lb_addr_store(p, v, new_value);
  11988. }
  11989. }
  11990. break;
  11991. }
  11992. }
  11993. return v;
  11994. case_end;
  11995. case_ast_node(tc, TypeCast, expr);
  11996. Type *type = type_of_expr(expr);
  11997. lbValue x = lb_build_expr(p, tc->expr);
  11998. lbValue e = {};
  11999. switch (tc->token.kind) {
  12000. case Token_cast:
  12001. e = lb_emit_conv(p, x, type);
  12002. break;
  12003. case Token_transmute:
  12004. e = lb_emit_transmute(p, x, type);
  12005. break;
  12006. default:
  12007. GB_PANIC("Invalid AST TypeCast");
  12008. }
  12009. lbAddr v = lb_add_local_generated(p, type, false);
  12010. lb_addr_store(p, v, e);
  12011. return v;
  12012. case_end;
  12013. case_ast_node(ac, AutoCast, expr);
  12014. return lb_build_addr(p, ac->expr);
  12015. case_end;
  12016. }
  12017. TokenPos token_pos = ast_token(expr).pos;
  12018. GB_PANIC("Unexpected address expression\n"
  12019. "\tAst: %.*s @ "
  12020. "%s\n",
  12021. LIT(ast_strings[expr->kind]),
  12022. token_pos_to_string(token_pos));
  12023. return {};
  12024. }
  12025. void lb_init_module(lbModule *m, Checker *c) {
  12026. m->info = &c->info;
  12027. gbString module_name = gb_string_make(heap_allocator(), "odin_package");
  12028. if (m->pkg) {
  12029. module_name = gb_string_appendc(module_name, "-");
  12030. module_name = gb_string_append_length(module_name, m->pkg->name.text, m->pkg->name.len);
  12031. } else if (USE_SEPARTE_MODULES) {
  12032. module_name = gb_string_appendc(module_name, "-builtin");
  12033. }
  12034. m->ctx = LLVMContextCreate();
  12035. m->mod = LLVMModuleCreateWithNameInContext(module_name ? module_name : "odin_package", m->ctx);
  12036. // m->debug_builder = nullptr;
  12037. if (build_context.ODIN_DEBUG) {
  12038. enum {DEBUG_METADATA_VERSION = 3};
  12039. LLVMMetadataRef debug_ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), DEBUG_METADATA_VERSION, true));
  12040. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "Debug Info Version", 18, debug_ref);
  12041. switch (build_context.metrics.os) {
  12042. case TargetOs_windows:
  12043. LLVMAddModuleFlag(m->mod,
  12044. LLVMModuleFlagBehaviorWarning,
  12045. "CodeView", 8,
  12046. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 1, true)));
  12047. break;
  12048. case TargetOs_darwin:
  12049. // NOTE(bill): Darwin only supports DWARF2 (that I know of)
  12050. LLVMAddModuleFlag(m->mod,
  12051. LLVMModuleFlagBehaviorWarning,
  12052. "Dwarf Version", 13,
  12053. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 2, true)));
  12054. break;
  12055. }
  12056. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  12057. }
  12058. gbAllocator a = heap_allocator();
  12059. map_init(&m->types, a);
  12060. map_init(&m->llvm_types, a);
  12061. map_init(&m->values, a);
  12062. map_init(&m->soa_values, a);
  12063. string_map_init(&m->members, a);
  12064. map_init(&m->procedure_values, a);
  12065. string_map_init(&m->procedures, a);
  12066. string_map_init(&m->const_strings, a);
  12067. map_init(&m->anonymous_proc_lits, a);
  12068. map_init(&m->function_type_map, a);
  12069. map_init(&m->equal_procs, a);
  12070. map_init(&m->hasher_procs, a);
  12071. array_init(&m->procedures_to_generate, a, 0, 1024);
  12072. array_init(&m->foreign_library_paths, a, 0, 1024);
  12073. map_init(&m->debug_values, a);
  12074. array_init(&m->debug_incomplete_types, a, 0, 1024);
  12075. }
  12076. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  12077. if (global_error_collector.count != 0) {
  12078. return false;
  12079. }
  12080. isize tc = c->parser->total_token_count;
  12081. if (tc < 2) {
  12082. return false;
  12083. }
  12084. String init_fullpath = c->parser->init_fullpath;
  12085. if (build_context.out_filepath.len == 0) {
  12086. gen->output_name = remove_directory_from_path(init_fullpath);
  12087. gen->output_name = remove_extension_from_path(gen->output_name);
  12088. gen->output_name = string_trim_whitespace(gen->output_name);
  12089. if (gen->output_name.len == 0) {
  12090. gen->output_name = c->info.init_scope->pkg->name;
  12091. }
  12092. gen->output_base = gen->output_name;
  12093. } else {
  12094. gen->output_name = build_context.out_filepath;
  12095. gen->output_name = string_trim_whitespace(gen->output_name);
  12096. if (gen->output_name.len == 0) {
  12097. gen->output_name = c->info.init_scope->pkg->name;
  12098. }
  12099. isize pos = string_extension_position(gen->output_name);
  12100. if (pos < 0) {
  12101. gen->output_base = gen->output_name;
  12102. } else {
  12103. gen->output_base = substring(gen->output_name, 0, pos);
  12104. }
  12105. }
  12106. gbAllocator ha = heap_allocator();
  12107. array_init(&gen->output_object_paths, ha);
  12108. array_init(&gen->output_temp_paths, ha);
  12109. gen->output_base = path_to_full_path(ha, gen->output_base);
  12110. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  12111. output_file_path = gb_string_appendc(output_file_path, ".obj");
  12112. defer (gb_string_free(output_file_path));
  12113. gen->info = &c->info;
  12114. map_init(&gen->modules, permanent_allocator(), gen->info->packages.entries.count*2);
  12115. map_init(&gen->modules_through_ctx, permanent_allocator(), gen->info->packages.entries.count*2);
  12116. map_init(&gen->anonymous_proc_lits, heap_allocator(), 1024);
  12117. gb_mutex_init(&gen->mutex);
  12118. if (USE_SEPARTE_MODULES) {
  12119. for_array(i, gen->info->packages.entries) {
  12120. AstPackage *pkg = gen->info->packages.entries[i].value;
  12121. auto m = gb_alloc_item(permanent_allocator(), lbModule);
  12122. m->pkg = pkg;
  12123. m->gen = gen;
  12124. map_set(&gen->modules, hash_pointer(pkg), m);
  12125. lb_init_module(m, c);
  12126. }
  12127. }
  12128. gen->default_module.gen = gen;
  12129. map_set(&gen->modules, hash_pointer(nullptr), &gen->default_module);
  12130. lb_init_module(&gen->default_module, c);
  12131. for_array(i, gen->modules.entries) {
  12132. lbModule *m = gen->modules.entries[i].value;
  12133. LLVMContextRef ctx = LLVMGetModuleContext(m->mod);
  12134. map_set(&gen->modules_through_ctx, hash_pointer(ctx), m);
  12135. }
  12136. return true;
  12137. }
  12138. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  12139. GB_ASSERT(type != nullptr);
  12140. type = default_type(type);
  12141. isize max_len = 7+8+1;
  12142. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  12143. u32 id = cast(u32)gb_atomic32_fetch_add(&m->gen->global_generated_index, 1);
  12144. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", id);
  12145. String name = make_string(str, len-1);
  12146. Scope *scope = nullptr;
  12147. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  12148. lbValue g = {};
  12149. g.type = alloc_type_pointer(type);
  12150. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  12151. if (value.value != nullptr) {
  12152. GB_ASSERT_MSG(LLVMIsConstant(value.value), LLVMPrintValueToString(value.value));
  12153. LLVMSetInitializer(g.value, value.value);
  12154. } else {
  12155. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  12156. }
  12157. lb_add_entity(m, e, g);
  12158. lb_add_member(m, name, g);
  12159. return lb_addr(g);
  12160. }
  12161. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  12162. AstPackage *p = m->info->runtime_package;
  12163. Entity *e = scope_lookup_current(p->scope, name);
  12164. return lb_find_value_from_entity(m, e);
  12165. }
  12166. lbValue lb_find_package_value(lbModule *m, String const &pkg, String const &name) {
  12167. Entity *e = find_entity_in_pkg(m->info, pkg, name);
  12168. return lb_find_value_from_entity(m, e);
  12169. }
  12170. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  12171. i32 index = cast(i32)lb_type_info_index(m->info, type);
  12172. GB_ASSERT(index >= 0);
  12173. // gb_printf_err("%d %s\n", index, type_to_string(type));
  12174. LLVMValueRef indices[2] = {
  12175. LLVMConstInt(lb_type(m, t_int), 0, false),
  12176. LLVMConstInt(lb_type(m, t_int), index, false),
  12177. };
  12178. lbValue res = {};
  12179. res.type = t_type_info_ptr;
  12180. res.value = LLVMConstGEP(lb_global_type_info_data_ptr(m).value, indices, cast(unsigned)gb_count_of(indices));
  12181. return res;
  12182. }
  12183. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  12184. GB_ASSERT(p->module == &p->module->gen->default_module);
  12185. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  12186. lb_global_type_info_member_types_index += cast(i32)count;
  12187. return offset;
  12188. }
  12189. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  12190. GB_ASSERT(p->module == &p->module->gen->default_module);
  12191. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  12192. lb_global_type_info_member_names_index += cast(i32)count;
  12193. return offset;
  12194. }
  12195. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  12196. GB_ASSERT(p->module == &p->module->gen->default_module);
  12197. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  12198. lb_global_type_info_member_offsets_index += cast(i32)count;
  12199. return offset;
  12200. }
  12201. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  12202. GB_ASSERT(p->module == &p->module->gen->default_module);
  12203. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  12204. lb_global_type_info_member_usings_index += cast(i32)count;
  12205. return offset;
  12206. }
  12207. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  12208. GB_ASSERT(p->module == &p->module->gen->default_module);
  12209. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  12210. lb_global_type_info_member_tags_index += cast(i32)count;
  12211. return offset;
  12212. }
  12213. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  12214. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  12215. return lb_addr_get_ptr(p, addr);
  12216. }
  12217. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  12218. Token token = {Token_Ident};
  12219. isize name_len = prefix.len + 1 + 20;
  12220. auto suffix_id = cast(unsigned long long)id;
  12221. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  12222. gb_snprintf(text, name_len,
  12223. "%.*s-%llu", LIT(prefix), suffix_id);
  12224. text[name_len] = 0;
  12225. String s = make_string_c(text);
  12226. Type *t = alloc_type_array(elem_type, count);
  12227. lbValue g = {};
  12228. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  12229. g.type = alloc_type_pointer(t);
  12230. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  12231. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  12232. string_map_set(&m->members, s, g);
  12233. return g;
  12234. }
  12235. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  12236. lbModule *m = p->module;
  12237. LLVMContextRef ctx = m->ctx;
  12238. CheckerInfo *info = m->info;
  12239. {
  12240. // NOTE(bill): Set the type_table slice with the global backing array
  12241. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  12242. Type *type = base_type(lb_global_type_info_data_entity->type);
  12243. GB_ASSERT(is_type_array(type));
  12244. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  12245. LLVMValueRef values[2] = {
  12246. LLVMConstInBoundsGEP(lb_global_type_info_data_ptr(m).value, indices, gb_count_of(indices)),
  12247. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  12248. };
  12249. LLVMValueRef slice = llvm_const_named_struct(llvm_addr_type(global_type_table), values, gb_count_of(values));
  12250. LLVMSetInitializer(global_type_table.value, slice);
  12251. }
  12252. // Useful types
  12253. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  12254. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  12255. Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags"));
  12256. Type *t_type_info_flags = type_info_flags_entity->type;
  12257. i32 type_info_member_types_index = 0;
  12258. i32 type_info_member_names_index = 0;
  12259. i32 type_info_member_offsets_index = 0;
  12260. for_array(type_info_type_index, info->type_info_types) {
  12261. Type *t = info->type_info_types[type_info_type_index];
  12262. if (t == nullptr || t == t_invalid) {
  12263. continue;
  12264. }
  12265. isize entry_index = lb_type_info_index(info, t, false);
  12266. if (entry_index <= 0) {
  12267. continue;
  12268. }
  12269. lbValue tag = {};
  12270. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data_ptr(m), cast(i32)entry_index);
  12271. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 4);
  12272. lbValue type_info_flags = lb_const_int(p->module, t_type_info_flags, type_info_flags_of_type(t));
  12273. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  12274. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  12275. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), type_info_flags);
  12276. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 3), lb_typeid(m, t));
  12277. switch (t->kind) {
  12278. case Type_Named: {
  12279. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  12280. LLVMValueRef pkg_name = nullptr;
  12281. if (t->Named.type_name->pkg) {
  12282. pkg_name = lb_const_string(m, t->Named.type_name->pkg->name).value;
  12283. } else {
  12284. pkg_name = LLVMConstNull(lb_type(m, t_string));
  12285. }
  12286. String proc_name = {};
  12287. if (t->Named.type_name->parent_proc_decl) {
  12288. DeclInfo *decl = t->Named.type_name->parent_proc_decl;
  12289. if (decl->entity && decl->entity->kind == Entity_Procedure) {
  12290. proc_name = decl->entity->token.string;
  12291. }
  12292. }
  12293. TokenPos pos = t->Named.type_name->token.pos;
  12294. lbValue loc = lb_emit_source_code_location(p, proc_name, pos);
  12295. LLVMValueRef vals[4] = {
  12296. lb_const_string(p->module, t->Named.type_name->token.string).value,
  12297. lb_get_type_info_ptr(m, t->Named.base).value,
  12298. pkg_name,
  12299. loc.value
  12300. };
  12301. lbValue res = {};
  12302. res.type = type_deref(tag.type);
  12303. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12304. lb_emit_store(p, tag, res);
  12305. break;
  12306. }
  12307. case Type_Basic:
  12308. switch (t->Basic.kind) {
  12309. case Basic_bool:
  12310. case Basic_b8:
  12311. case Basic_b16:
  12312. case Basic_b32:
  12313. case Basic_b64:
  12314. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  12315. break;
  12316. case Basic_i8:
  12317. case Basic_u8:
  12318. case Basic_i16:
  12319. case Basic_u16:
  12320. case Basic_i32:
  12321. case Basic_u32:
  12322. case Basic_i64:
  12323. case Basic_u64:
  12324. case Basic_i128:
  12325. case Basic_u128:
  12326. case Basic_i16le:
  12327. case Basic_u16le:
  12328. case Basic_i32le:
  12329. case Basic_u32le:
  12330. case Basic_i64le:
  12331. case Basic_u64le:
  12332. case Basic_i128le:
  12333. case Basic_u128le:
  12334. case Basic_i16be:
  12335. case Basic_u16be:
  12336. case Basic_i32be:
  12337. case Basic_u32be:
  12338. case Basic_i64be:
  12339. case Basic_u64be:
  12340. case Basic_i128be:
  12341. case Basic_u128be:
  12342. case Basic_int:
  12343. case Basic_uint:
  12344. case Basic_uintptr: {
  12345. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  12346. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  12347. // NOTE(bill): This is matches the runtime layout
  12348. u8 endianness_value = 0;
  12349. if (t->Basic.flags & BasicFlag_EndianLittle) {
  12350. endianness_value = 1;
  12351. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  12352. endianness_value = 2;
  12353. }
  12354. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  12355. LLVMValueRef vals[2] = {
  12356. is_signed.value,
  12357. endianness.value,
  12358. };
  12359. lbValue res = {};
  12360. res.type = type_deref(tag.type);
  12361. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12362. lb_emit_store(p, tag, res);
  12363. break;
  12364. }
  12365. case Basic_rune:
  12366. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  12367. break;
  12368. case Basic_f16:
  12369. case Basic_f32:
  12370. case Basic_f64:
  12371. case Basic_f16le:
  12372. case Basic_f32le:
  12373. case Basic_f64le:
  12374. case Basic_f16be:
  12375. case Basic_f32be:
  12376. case Basic_f64be:
  12377. {
  12378. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  12379. // NOTE(bill): This is matches the runtime layout
  12380. u8 endianness_value = 0;
  12381. if (t->Basic.flags & BasicFlag_EndianLittle) {
  12382. endianness_value = 1;
  12383. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  12384. endianness_value = 2;
  12385. }
  12386. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  12387. LLVMValueRef vals[1] = {
  12388. endianness.value,
  12389. };
  12390. lbValue res = {};
  12391. res.type = type_deref(tag.type);
  12392. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12393. lb_emit_store(p, tag, res);
  12394. }
  12395. break;
  12396. case Basic_complex32:
  12397. case Basic_complex64:
  12398. case Basic_complex128:
  12399. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  12400. break;
  12401. case Basic_quaternion64:
  12402. case Basic_quaternion128:
  12403. case Basic_quaternion256:
  12404. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  12405. break;
  12406. case Basic_rawptr:
  12407. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  12408. break;
  12409. case Basic_string:
  12410. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  12411. break;
  12412. case Basic_cstring:
  12413. {
  12414. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  12415. LLVMValueRef vals[1] = {
  12416. lb_const_bool(m, t_bool, true).value,
  12417. };
  12418. lbValue res = {};
  12419. res.type = type_deref(tag.type);
  12420. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12421. lb_emit_store(p, tag, res);
  12422. }
  12423. break;
  12424. case Basic_any:
  12425. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  12426. break;
  12427. case Basic_typeid:
  12428. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  12429. break;
  12430. }
  12431. break;
  12432. case Type_Pointer: {
  12433. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  12434. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  12435. LLVMValueRef vals[1] = {
  12436. gep.value,
  12437. };
  12438. lbValue res = {};
  12439. res.type = type_deref(tag.type);
  12440. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12441. lb_emit_store(p, tag, res);
  12442. break;
  12443. }
  12444. case Type_Array: {
  12445. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  12446. i64 ez = type_size_of(t->Array.elem);
  12447. LLVMValueRef vals[3] = {
  12448. lb_get_type_info_ptr(m, t->Array.elem).value,
  12449. lb_const_int(m, t_int, ez).value,
  12450. lb_const_int(m, t_int, t->Array.count).value,
  12451. };
  12452. lbValue res = {};
  12453. res.type = type_deref(tag.type);
  12454. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12455. lb_emit_store(p, tag, res);
  12456. break;
  12457. }
  12458. case Type_EnumeratedArray: {
  12459. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  12460. LLVMValueRef vals[6] = {
  12461. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  12462. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  12463. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  12464. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  12465. // Unions
  12466. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  12467. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  12468. };
  12469. lbValue res = {};
  12470. res.type = type_deref(tag.type);
  12471. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12472. lb_emit_store(p, tag, res);
  12473. // NOTE(bill): Union assignment
  12474. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  12475. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  12476. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  12477. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  12478. lb_emit_store(p, min_value, min_v);
  12479. lb_emit_store(p, max_value, max_v);
  12480. break;
  12481. }
  12482. case Type_DynamicArray: {
  12483. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  12484. LLVMValueRef vals[2] = {
  12485. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  12486. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  12487. };
  12488. lbValue res = {};
  12489. res.type = type_deref(tag.type);
  12490. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12491. lb_emit_store(p, tag, res);
  12492. break;
  12493. }
  12494. case Type_Slice: {
  12495. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  12496. LLVMValueRef vals[2] = {
  12497. lb_get_type_info_ptr(m, t->Slice.elem).value,
  12498. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  12499. };
  12500. lbValue res = {};
  12501. res.type = type_deref(tag.type);
  12502. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12503. lb_emit_store(p, tag, res);
  12504. break;
  12505. }
  12506. case Type_Proc: {
  12507. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  12508. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  12509. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  12510. if (t->Proc.params != nullptr) {
  12511. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  12512. }
  12513. if (t->Proc.results != nullptr) {
  12514. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  12515. }
  12516. LLVMValueRef vals[4] = {
  12517. params,
  12518. results,
  12519. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  12520. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  12521. };
  12522. lbValue res = {};
  12523. res.type = type_deref(tag.type);
  12524. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12525. lb_emit_store(p, tag, res);
  12526. break;
  12527. }
  12528. case Type_Tuple: {
  12529. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  12530. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  12531. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  12532. for_array(i, t->Tuple.variables) {
  12533. // NOTE(bill): offset is not used for tuples
  12534. Entity *f = t->Tuple.variables[i];
  12535. lbValue index = lb_const_int(m, t_int, i);
  12536. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  12537. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  12538. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  12539. if (f->token.string.len > 0) {
  12540. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  12541. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  12542. }
  12543. }
  12544. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  12545. LLVMValueRef types_slice = llvm_const_slice(m, memory_types, count);
  12546. LLVMValueRef names_slice = llvm_const_slice(m, memory_names, count);
  12547. LLVMValueRef vals[2] = {
  12548. types_slice,
  12549. names_slice,
  12550. };
  12551. lbValue res = {};
  12552. res.type = type_deref(tag.type);
  12553. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12554. lb_emit_store(p, tag, res);
  12555. break;
  12556. }
  12557. case Type_Enum:
  12558. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  12559. {
  12560. GB_ASSERT(t->Enum.base_type != nullptr);
  12561. // 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));
  12562. LLVMValueRef vals[3] = {};
  12563. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  12564. if (t->Enum.fields.count > 0) {
  12565. auto fields = t->Enum.fields;
  12566. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  12567. str_lit("$enum_names"), cast(i64)entry_index);
  12568. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  12569. str_lit("$enum_values"), cast(i64)entry_index);
  12570. LLVMValueRef *name_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  12571. LLVMValueRef *value_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  12572. GB_ASSERT(is_type_integer(t->Enum.base_type));
  12573. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  12574. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  12575. for_array(i, fields) {
  12576. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  12577. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  12578. }
  12579. LLVMValueRef name_init = llvm_const_array(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  12580. LLVMValueRef value_init = llvm_const_array(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  12581. LLVMSetInitializer(name_array.value, name_init);
  12582. LLVMSetInitializer(value_array.value, value_init);
  12583. lbValue v_count = lb_const_int(m, t_int, fields.count);
  12584. vals[1] = llvm_const_slice(m, lb_array_elem(p, name_array), v_count);
  12585. vals[2] = llvm_const_slice(m, lb_array_elem(p, value_array), v_count);
  12586. } else {
  12587. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  12588. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  12589. }
  12590. lbValue res = {};
  12591. res.type = type_deref(tag.type);
  12592. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12593. lb_emit_store(p, tag, res);
  12594. }
  12595. break;
  12596. case Type_Union: {
  12597. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  12598. {
  12599. LLVMValueRef vals[7] = {};
  12600. isize variant_count = gb_max(0, t->Union.variants.count);
  12601. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  12602. // NOTE(bill): Zeroth is nil so ignore it
  12603. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  12604. Type *vt = t->Union.variants[variant_index];
  12605. lbValue tip = lb_get_type_info_ptr(m, vt);
  12606. lbValue index = lb_const_int(m, t_int, variant_index);
  12607. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  12608. lb_emit_store(p, type_info, lb_type_info(m, vt));
  12609. }
  12610. lbValue count = lb_const_int(m, t_int, variant_count);
  12611. vals[0] = llvm_const_slice(m, memory_types, count);
  12612. i64 tag_size = union_tag_size(t);
  12613. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  12614. if (tag_size > 0) {
  12615. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  12616. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  12617. } else {
  12618. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  12619. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  12620. }
  12621. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  12622. vals[3] = lb_get_equal_proc_for_type(m, t).value;
  12623. }
  12624. vals[4] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  12625. vals[5] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  12626. vals[6] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  12627. for (isize i = 0; i < gb_count_of(vals); i++) {
  12628. if (vals[i] == nullptr) {
  12629. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  12630. }
  12631. }
  12632. lbValue res = {};
  12633. res.type = type_deref(tag.type);
  12634. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12635. lb_emit_store(p, tag, res);
  12636. }
  12637. break;
  12638. }
  12639. case Type_Struct: {
  12640. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  12641. LLVMValueRef vals[12] = {};
  12642. {
  12643. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  12644. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  12645. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  12646. vals[5] = is_packed.value;
  12647. vals[6] = is_raw_union.value;
  12648. vals[7] = is_custom_align.value;
  12649. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  12650. vals[8] = lb_get_equal_proc_for_type(m, t).value;
  12651. }
  12652. if (t->Struct.soa_kind != StructSoa_None) {
  12653. lbValue kind = lb_emit_struct_ep(p, tag, 9);
  12654. Type *kind_type = type_deref(kind.type);
  12655. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  12656. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  12657. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  12658. vals[9] = soa_kind.value;
  12659. vals[10] = soa_type.value;
  12660. vals[11] = soa_len.value;
  12661. }
  12662. }
  12663. isize count = t->Struct.fields.count;
  12664. if (count > 0) {
  12665. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  12666. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  12667. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  12668. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  12669. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  12670. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  12671. for (isize source_index = 0; source_index < count; source_index++) {
  12672. // TODO(bill): Order fields in source order not layout order
  12673. Entity *f = t->Struct.fields[source_index];
  12674. lbValue tip = lb_get_type_info_ptr(m, f->type);
  12675. i64 foffset = 0;
  12676. if (!t->Struct.is_raw_union) {
  12677. foffset = t->Struct.offsets[f->Variable.field_index];
  12678. }
  12679. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  12680. lbValue index = lb_const_int(m, t_int, source_index);
  12681. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  12682. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  12683. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  12684. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  12685. if (f->token.string.len > 0) {
  12686. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  12687. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  12688. }
  12689. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  12690. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  12691. if (t->Struct.tags.count > 0) {
  12692. String tag_string = t->Struct.tags[source_index];
  12693. if (tag_string.len > 0) {
  12694. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  12695. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  12696. }
  12697. }
  12698. }
  12699. lbValue cv = lb_const_int(m, t_int, count);
  12700. vals[0] = llvm_const_slice(m, memory_types, cv);
  12701. vals[1] = llvm_const_slice(m, memory_names, cv);
  12702. vals[2] = llvm_const_slice(m, memory_offsets, cv);
  12703. vals[3] = llvm_const_slice(m, memory_usings, cv);
  12704. vals[4] = llvm_const_slice(m, memory_tags, cv);
  12705. }
  12706. for (isize i = 0; i < gb_count_of(vals); i++) {
  12707. if (vals[i] == nullptr) {
  12708. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  12709. }
  12710. }
  12711. lbValue res = {};
  12712. res.type = type_deref(tag.type);
  12713. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12714. lb_emit_store(p, tag, res);
  12715. break;
  12716. }
  12717. case Type_Map: {
  12718. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  12719. init_map_internal_types(t);
  12720. LLVMValueRef vals[5] = {
  12721. lb_get_type_info_ptr(m, t->Map.key).value,
  12722. lb_get_type_info_ptr(m, t->Map.value).value,
  12723. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  12724. lb_get_equal_proc_for_type(m, t->Map.key).value,
  12725. lb_get_hasher_proc_for_type(m, t->Map.key).value
  12726. };
  12727. lbValue res = {};
  12728. res.type = type_deref(tag.type);
  12729. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12730. lb_emit_store(p, tag, res);
  12731. break;
  12732. }
  12733. case Type_BitSet:
  12734. {
  12735. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  12736. GB_ASSERT(is_type_typed(t->BitSet.elem));
  12737. LLVMValueRef vals[4] = {
  12738. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  12739. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  12740. lb_const_int(m, t_i64, t->BitSet.lower).value,
  12741. lb_const_int(m, t_i64, t->BitSet.upper).value,
  12742. };
  12743. if (t->BitSet.underlying != nullptr) {
  12744. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  12745. }
  12746. lbValue res = {};
  12747. res.type = type_deref(tag.type);
  12748. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12749. lb_emit_store(p, tag, res);
  12750. }
  12751. break;
  12752. case Type_SimdVector:
  12753. {
  12754. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  12755. LLVMValueRef vals[3] = {};
  12756. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  12757. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  12758. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  12759. lbValue res = {};
  12760. res.type = type_deref(tag.type);
  12761. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12762. lb_emit_store(p, tag, res);
  12763. }
  12764. break;
  12765. case Type_RelativePointer:
  12766. {
  12767. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  12768. LLVMValueRef vals[2] = {
  12769. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  12770. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  12771. };
  12772. lbValue res = {};
  12773. res.type = type_deref(tag.type);
  12774. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12775. lb_emit_store(p, tag, res);
  12776. }
  12777. break;
  12778. case Type_RelativeSlice:
  12779. {
  12780. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  12781. LLVMValueRef vals[2] = {
  12782. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  12783. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  12784. };
  12785. lbValue res = {};
  12786. res.type = type_deref(tag.type);
  12787. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12788. lb_emit_store(p, tag, res);
  12789. }
  12790. break;
  12791. }
  12792. if (tag.value != nullptr) {
  12793. Type *tag_type = type_deref(tag.type);
  12794. GB_ASSERT(is_type_named(tag_type));
  12795. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  12796. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  12797. } else {
  12798. if (t != t_llvm_bool) {
  12799. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  12800. }
  12801. }
  12802. }
  12803. }
  12804. struct lbGlobalVariable {
  12805. lbValue var;
  12806. lbValue init;
  12807. DeclInfo *decl;
  12808. bool is_initialized;
  12809. };
  12810. lbProcedure *lb_create_startup_type_info(lbModule *m) {
  12811. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  12812. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  12813. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  12814. Type *params = alloc_type_tuple();
  12815. Type *results = alloc_type_tuple();
  12816. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  12817. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  12818. p->is_startup = true;
  12819. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  12820. lb_begin_procedure_body(p);
  12821. lb_setup_type_info_data(p);
  12822. lb_end_procedure_body(p);
  12823. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  12824. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  12825. LLVMDumpValue(p->value);
  12826. gb_printf_err("\n\n\n\n");
  12827. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  12828. }
  12829. lb_run_function_pass_manager(default_function_pass_manager, p);
  12830. return p;
  12831. }
  12832. lbProcedure *lb_create_startup_runtime(lbModule *main_module, lbProcedure *startup_type_info, Array<lbGlobalVariable> &global_variables) { // Startup Runtime
  12833. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(main_module->mod);
  12834. lb_populate_function_pass_manager(main_module, default_function_pass_manager, false, build_context.optimization_level);
  12835. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  12836. Type *params = alloc_type_tuple();
  12837. Type *results = alloc_type_tuple();
  12838. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  12839. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  12840. p->is_startup = true;
  12841. lb_begin_procedure_body(p);
  12842. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(main_module, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  12843. for_array(i, global_variables) {
  12844. auto *var = &global_variables[i];
  12845. if (var->is_initialized) {
  12846. continue;
  12847. }
  12848. lbModule *entity_module = main_module;
  12849. Entity *e = var->decl->entity;
  12850. GB_ASSERT(e->kind == Entity_Variable);
  12851. e->code_gen_module = entity_module;
  12852. Ast *init_expr = var->decl->init_expr;
  12853. if (init_expr != nullptr) {
  12854. lbValue init = lb_build_expr(p, init_expr);
  12855. if (init.value == nullptr) {
  12856. LLVMTypeRef global_type = LLVMGetElementType(LLVMTypeOf(var->var.value));
  12857. if (is_type_untyped_undef(init.type)) {
  12858. LLVMSetInitializer(var->var.value, LLVMGetUndef(global_type));
  12859. var->is_initialized = true;
  12860. continue;
  12861. } else if (is_type_untyped_nil(init.type)) {
  12862. LLVMSetInitializer(var->var.value, LLVMConstNull(global_type));
  12863. var->is_initialized = true;
  12864. continue;
  12865. }
  12866. GB_PANIC("Invalid init value, got %s", expr_to_string(init_expr));
  12867. }
  12868. LLVMValueKind value_kind = LLVMGetValueKind(init.value);
  12869. // gb_printf_err("%s %d\n", LLVMPrintValueToString(init.value));
  12870. if (is_type_any(e->type) || is_type_union(e->type)) {
  12871. var->init = init;
  12872. } else if (lb_is_const_or_global(init)) {
  12873. if (!var->is_initialized) {
  12874. LLVMSetInitializer(var->var.value, init.value);
  12875. var->is_initialized = true;
  12876. continue;
  12877. }
  12878. } else {
  12879. var->init = init;
  12880. }
  12881. }
  12882. if (var->init.value != nullptr) {
  12883. GB_ASSERT(!var->is_initialized);
  12884. Type *t = type_deref(var->var.type);
  12885. if (is_type_any(t)) {
  12886. // NOTE(bill): Edge case for 'any' type
  12887. Type *var_type = default_type(var->init.type);
  12888. lbAddr g = lb_add_global_generated(main_module, var_type, var->init);
  12889. lb_addr_store(p, g, var->init);
  12890. lbValue gp = lb_addr_get_ptr(p, g);
  12891. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  12892. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  12893. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  12894. lb_emit_store(p, ti, lb_type_info(main_module, var_type));
  12895. } else {
  12896. LLVMTypeRef pvt = LLVMTypeOf(var->var.value);
  12897. LLVMTypeRef vt = LLVMGetElementType(pvt);
  12898. lbValue src0 = lb_emit_conv(p, var->init, t);
  12899. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  12900. LLVMValueRef dst = var->var.value;
  12901. LLVMBuildStore(p->builder, src, dst);
  12902. }
  12903. var->is_initialized = true;
  12904. }
  12905. }
  12906. lb_end_procedure_body(p);
  12907. if (!main_module->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  12908. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  12909. LLVMDumpValue(p->value);
  12910. gb_printf_err("\n\n\n\n");
  12911. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  12912. }
  12913. lb_run_function_pass_manager(default_function_pass_manager, p);
  12914. return p;
  12915. }
  12916. lbProcedure *lb_create_main_procedure(lbModule *m, lbProcedure *startup_runtime) {
  12917. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  12918. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  12919. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  12920. Type *params = alloc_type_tuple();
  12921. Type *results = alloc_type_tuple();
  12922. Type *t_ptr_cstring = alloc_type_pointer(t_cstring);
  12923. String name = str_lit("main");
  12924. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  12925. name = str_lit("mainCRTStartup");
  12926. } else {
  12927. array_init(&params->Tuple.variables, permanent_allocator(), 2);
  12928. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  12929. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), t_ptr_cstring, false, true);
  12930. }
  12931. array_init(&results->Tuple.variables, permanent_allocator(), 1);
  12932. results->Tuple.variables[0] = alloc_entity_param(nullptr, blank_token, t_i32, false, true);
  12933. Type *proc_type = alloc_type_proc(nullptr,
  12934. params, params->Tuple.variables.count,
  12935. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  12936. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  12937. p->is_startup = true;
  12938. lb_begin_procedure_body(p);
  12939. { // initialize `runtime.args__`
  12940. lbValue argc = {LLVMGetParam(p->value, 0), t_i32};
  12941. lbValue argv = {LLVMGetParam(p->value, 1), t_ptr_cstring};
  12942. LLVMSetValueName2(argc.value, "argc", 4);
  12943. LLVMSetValueName2(argv.value, "argv", 4);
  12944. argc = lb_emit_conv(p, argc, t_int);
  12945. lbAddr args = lb_addr(lb_find_runtime_value(p->module, str_lit("args__")));
  12946. lb_fill_slice(p, args, argv, argc);
  12947. }
  12948. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  12949. if (build_context.command_kind == Command_test) {
  12950. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  12951. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  12952. Type *slice_type = alloc_type_slice(t_Internal_Test);
  12953. lbAddr all_tests_array_addr = lb_add_global_generated(p->module, array_type, {});
  12954. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  12955. LLVMTypeRef lbt_Internal_Test = lb_type(m, t_Internal_Test);
  12956. LLVMValueRef indices[2] = {};
  12957. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  12958. for_array(i, m->info->testing_procedures) {
  12959. Entity *testing_proc = m->info->testing_procedures[i];
  12960. String name = testing_proc->token.string;
  12961. String pkg_name = {};
  12962. if (testing_proc->pkg != nullptr) {
  12963. pkg_name = testing_proc->pkg->name;
  12964. }
  12965. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name);
  12966. lbValue v_name = lb_find_or_add_entity_string(m, name);
  12967. lbValue v_proc = lb_find_procedure_value_from_entity(m, testing_proc);
  12968. indices[1] = LLVMConstInt(lb_type(m, t_int), i, false);
  12969. LLVMValueRef vals[3] = {};
  12970. vals[0] = v_pkg.value;
  12971. vals[1] = v_name.value;
  12972. vals[2] = v_proc.value;
  12973. GB_ASSERT(LLVMIsConstant(vals[0]));
  12974. GB_ASSERT(LLVMIsConstant(vals[1]));
  12975. GB_ASSERT(LLVMIsConstant(vals[2]));
  12976. LLVMValueRef dst = LLVMConstInBoundsGEP(all_tests_array.value, indices, gb_count_of(indices));
  12977. LLVMValueRef src = llvm_const_named_struct(lbt_Internal_Test, vals, gb_count_of(vals));
  12978. LLVMBuildStore(p->builder, src, dst);
  12979. }
  12980. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  12981. lb_fill_slice(p, all_tests_slice,
  12982. lb_array_elem(p, all_tests_array),
  12983. lb_const_int(m, t_int, m->info->testing_procedures.count));
  12984. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  12985. auto args = array_make<lbValue>(heap_allocator(), 1);
  12986. args[0] = lb_addr_load(p, all_tests_slice);
  12987. lb_emit_call(p, runner, args);
  12988. } else {
  12989. if (m->info->entry_point != nullptr) {
  12990. lbValue entry_point = lb_find_procedure_value_from_entity(m, m->info->entry_point);
  12991. lb_emit_call(p, entry_point, {});
  12992. }
  12993. }
  12994. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  12995. lb_end_procedure_body(p);
  12996. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  12997. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  12998. LLVMDumpValue(p->value);
  12999. gb_printf_err("\n\n\n\n");
  13000. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  13001. }
  13002. lb_run_function_pass_manager(default_function_pass_manager, p);
  13003. return p;
  13004. }
  13005. String lb_filepath_ll_for_module(lbModule *m) {
  13006. String path = m->gen->output_base;
  13007. if (m->pkg) {
  13008. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  13009. } else if (USE_SEPARTE_MODULES) {
  13010. path = concatenate_strings(permanent_allocator(), path, STR_LIT("-builtin"));
  13011. }
  13012. path = concatenate_strings(permanent_allocator(), path, STR_LIT(".ll"));
  13013. return path;
  13014. }
  13015. String lb_filepath_obj_for_module(lbModule *m) {
  13016. String path = m->gen->output_base;
  13017. if (m->pkg) {
  13018. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  13019. }
  13020. String ext = {};
  13021. if (build_context.build_mode == BuildMode_Assembly) {
  13022. ext = STR_LIT(".S");
  13023. } else {
  13024. if (is_arch_wasm()) {
  13025. ext = STR_LIT(".wasm.o");
  13026. } else {
  13027. switch (build_context.metrics.os) {
  13028. case TargetOs_windows:
  13029. ext = STR_LIT(".obj");
  13030. break;
  13031. default:
  13032. case TargetOs_darwin:
  13033. case TargetOs_linux:
  13034. case TargetOs_essence:
  13035. ext = STR_LIT(".o");
  13036. break;
  13037. }
  13038. }
  13039. }
  13040. return concatenate_strings(permanent_allocator(), path, ext);
  13041. }
  13042. bool lb_is_module_empty(lbModule *m) {
  13043. if (LLVMGetFirstFunction(m->mod) == nullptr &&
  13044. LLVMGetFirstGlobal(m->mod) == nullptr) {
  13045. return true;
  13046. }
  13047. for (auto fn = LLVMGetFirstFunction(m->mod); fn != nullptr; fn = LLVMGetNextFunction(fn)) {
  13048. if (LLVMGetFirstBasicBlock(fn) != nullptr) {
  13049. return false;
  13050. }
  13051. }
  13052. for (auto g = LLVMGetFirstGlobal(m->mod); g != nullptr; g = LLVMGetNextGlobal(g)) {
  13053. if (LLVMGetLinkage(g) == LLVMExternalLinkage) {
  13054. continue;
  13055. }
  13056. if (!LLVMIsExternallyInitialized(g)) {
  13057. return false;
  13058. }
  13059. }
  13060. return true;
  13061. }
  13062. struct lbLLVMEmitWorker {
  13063. LLVMTargetMachineRef target_machine;
  13064. LLVMCodeGenFileType code_gen_file_type;
  13065. String filepath_obj;
  13066. lbModule *m;
  13067. };
  13068. WORKER_TASK_PROC(lb_llvm_emit_worker_proc) {
  13069. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  13070. char *llvm_error = nullptr;
  13071. auto wd = cast(lbLLVMEmitWorker *)data;
  13072. if (LLVMTargetMachineEmitToFile(wd->target_machine, wd->m->mod, cast(char *)wd->filepath_obj.text, wd->code_gen_file_type, &llvm_error)) {
  13073. gb_printf_err("LLVM Error: %s\n", llvm_error);
  13074. gb_exit(1);
  13075. }
  13076. return 0;
  13077. }
  13078. WORKER_TASK_PROC(lb_llvm_function_pass_worker_proc) {
  13079. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  13080. auto m = cast(lbModule *)data;
  13081. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  13082. LLVMPassManagerRef function_pass_manager_minimal = LLVMCreateFunctionPassManagerForModule(m->mod);
  13083. LLVMPassManagerRef function_pass_manager_size = LLVMCreateFunctionPassManagerForModule(m->mod);
  13084. LLVMPassManagerRef function_pass_manager_speed = LLVMCreateFunctionPassManagerForModule(m->mod);
  13085. LLVMInitializeFunctionPassManager(default_function_pass_manager);
  13086. LLVMInitializeFunctionPassManager(function_pass_manager_minimal);
  13087. LLVMInitializeFunctionPassManager(function_pass_manager_size);
  13088. LLVMInitializeFunctionPassManager(function_pass_manager_speed);
  13089. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  13090. lb_populate_function_pass_manager_specific(m, function_pass_manager_minimal, 0);
  13091. lb_populate_function_pass_manager_specific(m, function_pass_manager_size, 1);
  13092. lb_populate_function_pass_manager_specific(m, function_pass_manager_speed, 2);
  13093. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  13094. LLVMFinalizeFunctionPassManager(function_pass_manager_minimal);
  13095. LLVMFinalizeFunctionPassManager(function_pass_manager_size);
  13096. LLVMFinalizeFunctionPassManager(function_pass_manager_speed);
  13097. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(m->mod);
  13098. LLVMInitializeFunctionPassManager(default_function_pass_manager_without_memcpy);
  13099. lb_populate_function_pass_manager(m, default_function_pass_manager_without_memcpy, true, build_context.optimization_level);
  13100. LLVMFinalizeFunctionPassManager(default_function_pass_manager_without_memcpy);
  13101. for_array(i, m->procedures_to_generate) {
  13102. lbProcedure *p = m->procedures_to_generate[i];
  13103. if (p->body != nullptr) { // Build Procedure
  13104. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  13105. lb_run_function_pass_manager(default_function_pass_manager_without_memcpy, p);
  13106. } else {
  13107. if (p->entity && p->entity->kind == Entity_Procedure) {
  13108. switch (p->entity->Procedure.optimization_mode) {
  13109. case ProcedureOptimizationMode_None:
  13110. case ProcedureOptimizationMode_Minimal:
  13111. lb_run_function_pass_manager(function_pass_manager_minimal, p);
  13112. break;
  13113. case ProcedureOptimizationMode_Size:
  13114. lb_run_function_pass_manager(function_pass_manager_size, p);
  13115. break;
  13116. case ProcedureOptimizationMode_Speed:
  13117. lb_run_function_pass_manager(function_pass_manager_speed, p);
  13118. break;
  13119. default:
  13120. lb_run_function_pass_manager(default_function_pass_manager, p);
  13121. break;
  13122. }
  13123. } else {
  13124. lb_run_function_pass_manager(default_function_pass_manager, p);
  13125. }
  13126. }
  13127. }
  13128. }
  13129. for_array(i, m->equal_procs.entries) {
  13130. lbProcedure *p = m->equal_procs.entries[i].value;
  13131. lb_run_function_pass_manager(default_function_pass_manager, p);
  13132. }
  13133. for_array(i, m->hasher_procs.entries) {
  13134. lbProcedure *p = m->hasher_procs.entries[i].value;
  13135. lb_run_function_pass_manager(default_function_pass_manager, p);
  13136. }
  13137. return 0;
  13138. }
  13139. struct lbLLVMModulePassWorkerData {
  13140. lbModule *m;
  13141. LLVMTargetMachineRef target_machine;
  13142. };
  13143. WORKER_TASK_PROC(lb_llvm_module_pass_worker_proc) {
  13144. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  13145. auto wd = cast(lbLLVMModulePassWorkerData *)data;
  13146. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  13147. lb_populate_module_pass_manager(wd->target_machine, module_pass_manager, build_context.optimization_level);
  13148. LLVMRunPassManager(module_pass_manager, wd->m->mod);
  13149. return 0;
  13150. }
  13151. void lb_generate_code(lbGenerator *gen) {
  13152. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  13153. #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)
  13154. TIME_SECTION("LLVM Initializtion");
  13155. isize thread_count = gb_max(build_context.thread_count, 1);
  13156. isize worker_count = thread_count-1;
  13157. LLVMBool do_threading = (LLVMIsMultithreaded() && USE_SEPARTE_MODULES && MULTITHREAD_OBJECT_GENERATION && worker_count > 0);
  13158. thread_pool_init(&lb_thread_pool, heap_allocator(), worker_count, "LLVMBackend");
  13159. defer (thread_pool_destroy(&lb_thread_pool));
  13160. lbModule *default_module = &gen->default_module;
  13161. CheckerInfo *info = gen->info;
  13162. auto *min_dep_set = &info->minimum_dependency_set;
  13163. LLVMInitializeAllTargetInfos();
  13164. LLVMInitializeAllTargets();
  13165. LLVMInitializeAllTargetMCs();
  13166. LLVMInitializeAllAsmPrinters();
  13167. LLVMInitializeAllAsmParsers();
  13168. LLVMInitializeAllDisassemblers();
  13169. LLVMInitializeNativeTarget();
  13170. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  13171. char const *target_data_layout = alloc_cstring(permanent_allocator(), build_context.metrics.target_data_layout);
  13172. for_array(i, gen->modules.entries) {
  13173. LLVMSetTarget(gen->modules.entries[i].value->mod, target_triple);
  13174. }
  13175. LLVMTargetRef target = {};
  13176. char *llvm_error = nullptr;
  13177. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  13178. GB_ASSERT(target != nullptr);
  13179. TIME_SECTION("LLVM Create Target Machine");
  13180. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  13181. if (is_arch_wasm()) {
  13182. code_mode = LLVMCodeModelJITDefault;
  13183. }
  13184. char const *host_cpu_name = LLVMGetHostCPUName();
  13185. char const *llvm_cpu = "generic";
  13186. char const *llvm_features = "";
  13187. if (build_context.microarch.len != 0) {
  13188. if (build_context.microarch == "native") {
  13189. llvm_cpu = host_cpu_name;
  13190. } else {
  13191. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  13192. }
  13193. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  13194. llvm_features = LLVMGetHostCPUFeatures();
  13195. }
  13196. }
  13197. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  13198. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  13199. switch (build_context.optimization_level) {
  13200. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  13201. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  13202. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  13203. case 3: code_gen_level = LLVMCodeGenLevelDefault; break; // NOTE(bill): force -opt:3 to be the same as -opt:2
  13204. // case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  13205. }
  13206. // NOTE(bill): Target Machine Creation
  13207. // NOTE(bill, 2021-05-04): Target machines must be unique to each module because they are not thread safe
  13208. auto target_machines = array_make<LLVMTargetMachineRef>(permanent_allocator(), gen->modules.entries.count);
  13209. for_array(i, gen->modules.entries) {
  13210. target_machines[i] = LLVMCreateTargetMachine(
  13211. target, target_triple, llvm_cpu,
  13212. llvm_features,
  13213. code_gen_level,
  13214. LLVMRelocDefault,
  13215. code_mode);
  13216. LLVMSetModuleDataLayout(gen->modules.entries[i].value->mod, LLVMCreateTargetDataLayout(target_machines[i]));
  13217. }
  13218. for_array(i, gen->modules.entries) {
  13219. lbModule *m = gen->modules.entries[i].value;
  13220. if (m->debug_builder) { // Debug Info
  13221. for_array(i, info->files.entries) {
  13222. AstFile *f = info->files.entries[i].value;
  13223. String fullpath = f->fullpath;
  13224. String filename = remove_directory_from_path(fullpath);
  13225. String directory = directory_from_path(fullpath);
  13226. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  13227. cast(char const *)filename.text, filename.len,
  13228. cast(char const *)directory.text, directory.len);
  13229. lb_set_llvm_metadata(m, f, res);
  13230. }
  13231. gbString producer = gb_string_make(heap_allocator(), "odin");
  13232. // producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  13233. // #ifdef NIGHTLY
  13234. // producer = gb_string_appendc(producer, "-nightly");
  13235. // #endif
  13236. // #ifdef GIT_SHA
  13237. // producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  13238. // #endif
  13239. gbString split_name = gb_string_make(heap_allocator(), "");
  13240. LLVMBool is_optimized = build_context.optimization_level > 0;
  13241. AstFile *init_file = m->info->init_package->files[0];
  13242. if (m->info->entry_point && m->info->entry_point->identifier && m->info->entry_point->identifier->file) {
  13243. init_file = m->info->entry_point->identifier->file;
  13244. }
  13245. LLVMBool split_debug_inlining = false;
  13246. LLVMBool debug_info_for_profiling = false;
  13247. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  13248. lb_get_llvm_metadata(m, init_file),
  13249. producer, gb_string_length(producer),
  13250. is_optimized, "", 0,
  13251. 1, split_name, gb_string_length(split_name),
  13252. LLVMDWARFEmissionFull,
  13253. 0, split_debug_inlining,
  13254. debug_info_for_profiling,
  13255. "", 0, // sys_root
  13256. "", 0 // SDK
  13257. );
  13258. GB_ASSERT(m->debug_compile_unit != nullptr);
  13259. }
  13260. }
  13261. TIME_SECTION("LLVM Global Variables");
  13262. {
  13263. lbModule *m = default_module;
  13264. { // Add type info data
  13265. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  13266. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  13267. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  13268. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  13269. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  13270. if (!USE_SEPARTE_MODULES) {
  13271. LLVMSetLinkage(g, LLVMInternalLinkage);
  13272. }
  13273. lbValue value = {};
  13274. value.value = g;
  13275. value.type = alloc_type_pointer(t);
  13276. lb_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(LB_TYPE_INFO_DATA_NAME), t, EntityState_Resolved);
  13277. lb_add_entity(m, lb_global_type_info_data_entity, value);
  13278. }
  13279. { // Type info member buffer
  13280. // NOTE(bill): Removes need for heap allocation by making it global memory
  13281. isize count = 0;
  13282. for_array(entry_index, m->info->type_info_types) {
  13283. Type *t = m->info->type_info_types[entry_index];
  13284. isize index = lb_type_info_index(m->info, t, false);
  13285. if (index < 0) {
  13286. continue;
  13287. }
  13288. switch (t->kind) {
  13289. case Type_Union:
  13290. count += t->Union.variants.count;
  13291. break;
  13292. case Type_Struct:
  13293. count += t->Struct.fields.count;
  13294. break;
  13295. case Type_Tuple:
  13296. count += t->Tuple.variables.count;
  13297. break;
  13298. }
  13299. }
  13300. if (count > 0) {
  13301. {
  13302. char const *name = LB_TYPE_INFO_TYPES_NAME;
  13303. Type *t = alloc_type_array(t_type_info_ptr, count);
  13304. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  13305. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  13306. LLVMSetLinkage(g, LLVMInternalLinkage);
  13307. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  13308. }
  13309. {
  13310. char const *name = LB_TYPE_INFO_NAMES_NAME;
  13311. Type *t = alloc_type_array(t_string, count);
  13312. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  13313. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  13314. LLVMSetLinkage(g, LLVMInternalLinkage);
  13315. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  13316. }
  13317. {
  13318. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  13319. Type *t = alloc_type_array(t_uintptr, count);
  13320. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  13321. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  13322. LLVMSetLinkage(g, LLVMInternalLinkage);
  13323. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  13324. }
  13325. {
  13326. char const *name = LB_TYPE_INFO_USINGS_NAME;
  13327. Type *t = alloc_type_array(t_bool, count);
  13328. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  13329. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  13330. LLVMSetLinkage(g, LLVMInternalLinkage);
  13331. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  13332. }
  13333. {
  13334. char const *name = LB_TYPE_INFO_TAGS_NAME;
  13335. Type *t = alloc_type_array(t_string, count);
  13336. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  13337. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  13338. LLVMSetLinkage(g, LLVMInternalLinkage);
  13339. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  13340. }
  13341. }
  13342. }
  13343. }
  13344. isize global_variable_max_count = 0;
  13345. Entity *entry_point = info->entry_point;
  13346. bool has_dll_main = false;
  13347. bool has_win_main = false;
  13348. for_array(i, info->entities) {
  13349. Entity *e = info->entities[i];
  13350. String name = e->token.string;
  13351. bool is_global = e->pkg != nullptr;
  13352. if (e->kind == Entity_Variable) {
  13353. global_variable_max_count++;
  13354. } else if (e->kind == Entity_Procedure && !is_global) {
  13355. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  13356. GB_ASSERT(e == entry_point);
  13357. // entry_point = e;
  13358. }
  13359. if (e->Procedure.is_export ||
  13360. (e->Procedure.link_name.len > 0) ||
  13361. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  13362. if (!has_dll_main && name == "DllMain") {
  13363. has_dll_main = true;
  13364. } else if (!has_win_main && name == "WinMain") {
  13365. has_win_main = true;
  13366. }
  13367. }
  13368. }
  13369. }
  13370. auto global_variables = array_make<lbGlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  13371. for_array(i, info->variable_init_order) {
  13372. DeclInfo *d = info->variable_init_order[i];
  13373. Entity *e = d->entity;
  13374. if ((e->scope->flags & ScopeFlag_File) == 0) {
  13375. continue;
  13376. }
  13377. if (!ptr_set_exists(min_dep_set, e)) {
  13378. continue;
  13379. }
  13380. DeclInfo *decl = decl_info_of_entity(e);
  13381. if (decl == nullptr) {
  13382. continue;
  13383. }
  13384. GB_ASSERT(e->kind == Entity_Variable);
  13385. bool is_foreign = e->Variable.is_foreign;
  13386. bool is_export = e->Variable.is_export;
  13387. lbModule *m = &gen->default_module;
  13388. String name = lb_get_entity_name(m, e);
  13389. lbValue g = {};
  13390. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  13391. g.type = alloc_type_pointer(e->type);
  13392. if (e->Variable.thread_local_model != "") {
  13393. LLVMSetThreadLocal(g.value, true);
  13394. String m = e->Variable.thread_local_model;
  13395. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  13396. if (m == "default") {
  13397. mode = LLVMGeneralDynamicTLSModel;
  13398. } else if (m == "localdynamic") {
  13399. mode = LLVMLocalDynamicTLSModel;
  13400. } else if (m == "initialexec") {
  13401. mode = LLVMInitialExecTLSModel;
  13402. } else if (m == "localexec") {
  13403. mode = LLVMLocalExecTLSModel;
  13404. } else {
  13405. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  13406. }
  13407. LLVMSetThreadLocalMode(g.value, mode);
  13408. }
  13409. if (is_foreign) {
  13410. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  13411. LLVMSetExternallyInitialized(g.value, true);
  13412. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  13413. } else {
  13414. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  13415. }
  13416. if (is_export) {
  13417. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  13418. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  13419. } else if (!is_foreign) {
  13420. if (USE_SEPARTE_MODULES) {
  13421. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  13422. } else {
  13423. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  13424. }
  13425. }
  13426. if (e->Variable.link_section.len > 0) {
  13427. LLVMSetSection(g.value, alloc_cstring(permanent_allocator(), e->Variable.link_section));
  13428. }
  13429. lbGlobalVariable var = {};
  13430. var.var = g;
  13431. var.decl = decl;
  13432. if (decl->init_expr != nullptr) {
  13433. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  13434. if (!is_type_any(e->type) && !is_type_union(e->type)) {
  13435. if (tav.mode != Addressing_Invalid) {
  13436. if (tav.value.kind != ExactValue_Invalid) {
  13437. ExactValue v = tav.value;
  13438. lbValue init = lb_const_value(m, tav.type, v);
  13439. LLVMSetInitializer(g.value, init.value);
  13440. var.is_initialized = true;
  13441. }
  13442. }
  13443. }
  13444. if (!var.is_initialized &&
  13445. (is_type_untyped_nil(tav.type) || is_type_untyped_undef(tav.type))) {
  13446. var.is_initialized = true;
  13447. }
  13448. }
  13449. array_add(&global_variables, var);
  13450. lb_add_entity(m, e, g);
  13451. lb_add_member(m, name, g);
  13452. if (m->debug_builder) {
  13453. String global_name = e->token.string;
  13454. if (global_name.len != 0 && global_name != "_") {
  13455. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  13456. LLVMMetadataRef llvm_scope = llvm_file;
  13457. LLVMBool local_to_unit = LLVMGetLinkage(g.value) == LLVMInternalLinkage;
  13458. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  13459. LLVMMetadataRef llvm_decl = nullptr;
  13460. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  13461. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  13462. m->debug_builder, llvm_scope,
  13463. cast(char const *)global_name.text, global_name.len,
  13464. "", 0, // linkage
  13465. llvm_file, e->token.pos.line,
  13466. lb_debug_type(m, e->type),
  13467. local_to_unit,
  13468. llvm_expr,
  13469. llvm_decl,
  13470. align_in_bits
  13471. );
  13472. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  13473. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  13474. }
  13475. }
  13476. }
  13477. TIME_SECTION("LLVM Global Procedures and Types");
  13478. for_array(i, info->entities) {
  13479. Entity *e = info->entities[i];
  13480. String name = e->token.string;
  13481. DeclInfo *decl = e->decl_info;
  13482. Scope * scope = e->scope;
  13483. if ((scope->flags & ScopeFlag_File) == 0) {
  13484. continue;
  13485. }
  13486. Scope *package_scope = scope->parent;
  13487. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  13488. switch (e->kind) {
  13489. case Entity_Variable:
  13490. // NOTE(bill): Handled above as it requires a specific load order
  13491. continue;
  13492. case Entity_ProcGroup:
  13493. continue;
  13494. case Entity_TypeName:
  13495. case Entity_Procedure:
  13496. break;
  13497. }
  13498. bool polymorphic_struct = false;
  13499. if (e->type != nullptr && e->kind == Entity_TypeName) {
  13500. Type *bt = base_type(e->type);
  13501. if (bt->kind == Type_Struct) {
  13502. polymorphic_struct = is_type_polymorphic(bt);
  13503. }
  13504. }
  13505. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  13506. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  13507. continue;
  13508. }
  13509. lbModule *m = &gen->default_module;
  13510. if (USE_SEPARTE_MODULES) {
  13511. m = lb_pkg_module(gen, e->pkg);
  13512. }
  13513. String mangled_name = lb_get_entity_name(m, e);
  13514. switch (e->kind) {
  13515. case Entity_TypeName:
  13516. lb_type(m, e->type);
  13517. break;
  13518. case Entity_Procedure:
  13519. {
  13520. lbProcedure *p = lb_create_procedure(m, e);
  13521. array_add(&m->procedures_to_generate, p);
  13522. }
  13523. break;
  13524. }
  13525. }
  13526. TIME_SECTION("LLVM Runtime Type Information Creation");
  13527. lbProcedure *startup_type_info = lb_create_startup_type_info(default_module);
  13528. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables)");
  13529. lbProcedure *startup_runtime = lb_create_startup_runtime(default_module, startup_type_info, global_variables);
  13530. TIME_SECTION("LLVM Procedure Generation");
  13531. for_array(j, gen->modules.entries) {
  13532. lbModule *m = gen->modules.entries[j].value;
  13533. for_array(i, m->procedures_to_generate) {
  13534. lbProcedure *p = m->procedures_to_generate[i];
  13535. if (p->is_done) {
  13536. continue;
  13537. }
  13538. if (p->body != nullptr) { // Build Procedure
  13539. m->curr_procedure = p;
  13540. lb_begin_procedure_body(p);
  13541. lb_build_stmt(p, p->body);
  13542. lb_end_procedure_body(p);
  13543. p->is_done = true;
  13544. m->curr_procedure = nullptr;
  13545. }
  13546. lb_end_procedure(p);
  13547. // Add Flags
  13548. if (p->body != nullptr) {
  13549. if (p->name == "memcpy" || p->name == "memmove" ||
  13550. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  13551. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  13552. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  13553. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  13554. }
  13555. }
  13556. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  13557. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  13558. LLVMDumpValue(p->value);
  13559. gb_printf_err("\n\n\n\n");
  13560. String filepath_ll = lb_filepath_ll_for_module(m);
  13561. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  13562. gb_printf_err("LLVM Error: %s\n", llvm_error);
  13563. }
  13564. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  13565. gb_exit(1);
  13566. }
  13567. }
  13568. }
  13569. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  13570. TIME_SECTION("LLVM main");
  13571. lb_create_main_procedure(default_module, startup_runtime);
  13572. }
  13573. if (build_context.ODIN_DEBUG) {
  13574. TIME_SECTION("LLVM Debug Info Complete Types and Finalize");
  13575. for_array(j, gen->modules.entries) {
  13576. lbModule *m = gen->modules.entries[j].value;
  13577. if (m->debug_builder != nullptr) {
  13578. lb_debug_complete_types(m);
  13579. LLVMDIBuilderFinalize(m->debug_builder);
  13580. }
  13581. }
  13582. }
  13583. TIME_SECTION("LLVM Function Pass");
  13584. for_array(i, gen->modules.entries) {
  13585. lbModule *m = gen->modules.entries[i].value;
  13586. lb_llvm_function_pass_worker_proc(m);
  13587. }
  13588. TIME_SECTION("LLVM Module Pass");
  13589. for_array(i, gen->modules.entries) {
  13590. lbModule *m = gen->modules.entries[i].value;
  13591. auto wd = gb_alloc_item(permanent_allocator(), lbLLVMModulePassWorkerData);
  13592. wd->m = m;
  13593. wd->target_machine = target_machines[i];
  13594. lb_llvm_module_pass_worker_proc(wd);
  13595. }
  13596. llvm_error = nullptr;
  13597. defer (LLVMDisposeMessage(llvm_error));
  13598. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  13599. if (build_context.build_mode == BuildMode_Assembly) {
  13600. code_gen_file_type = LLVMAssemblyFile;
  13601. }
  13602. for_array(j, gen->modules.entries) {
  13603. lbModule *m = gen->modules.entries[j].value;
  13604. if (LLVMVerifyModule(m->mod, LLVMReturnStatusAction, &llvm_error)) {
  13605. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  13606. if (build_context.keep_temp_files) {
  13607. TIME_SECTION("LLVM Print Module to File");
  13608. String filepath_ll = lb_filepath_ll_for_module(m);
  13609. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  13610. gb_printf_err("LLVM Error: %s\n", llvm_error);
  13611. gb_exit(1);
  13612. return;
  13613. }
  13614. }
  13615. gb_exit(1);
  13616. return;
  13617. }
  13618. }
  13619. llvm_error = nullptr;
  13620. if (build_context.keep_temp_files ||
  13621. build_context.build_mode == BuildMode_LLVM_IR) {
  13622. TIME_SECTION("LLVM Print Module to File");
  13623. for_array(j, gen->modules.entries) {
  13624. lbModule *m = gen->modules.entries[j].value;
  13625. if (lb_is_module_empty(m)) {
  13626. continue;
  13627. }
  13628. String filepath_ll = lb_filepath_ll_for_module(m);
  13629. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  13630. gb_printf_err("LLVM Error: %s\n", llvm_error);
  13631. gb_exit(1);
  13632. return;
  13633. }
  13634. array_add(&gen->output_temp_paths, filepath_ll);
  13635. }
  13636. if (build_context.build_mode == BuildMode_LLVM_IR) {
  13637. gb_exit(0);
  13638. return;
  13639. }
  13640. }
  13641. TIME_SECTION("LLVM Add Foreign Library Paths");
  13642. for_array(j, gen->modules.entries) {
  13643. lbModule *m = gen->modules.entries[j].value;
  13644. for_array(i, m->info->required_foreign_imports_through_force) {
  13645. Entity *e = m->info->required_foreign_imports_through_force[i];
  13646. lb_add_foreign_library_path(m, e);
  13647. }
  13648. if (lb_is_module_empty(m)) {
  13649. continue;
  13650. }
  13651. }
  13652. TIME_SECTION("LLVM Object Generation");
  13653. if (do_threading) {
  13654. for_array(j, gen->modules.entries) {
  13655. lbModule *m = gen->modules.entries[j].value;
  13656. if (lb_is_module_empty(m)) {
  13657. continue;
  13658. }
  13659. String filepath_ll = lb_filepath_ll_for_module(m);
  13660. String filepath_obj = lb_filepath_obj_for_module(m);
  13661. array_add(&gen->output_object_paths, filepath_obj);
  13662. array_add(&gen->output_temp_paths, filepath_ll);
  13663. auto *wd = gb_alloc_item(heap_allocator(), lbLLVMEmitWorker);
  13664. wd->target_machine = target_machines[j];
  13665. wd->code_gen_file_type = code_gen_file_type;
  13666. wd->filepath_obj = filepath_obj;
  13667. wd->m = m;
  13668. thread_pool_add_task(&lb_thread_pool, lb_llvm_emit_worker_proc, wd);
  13669. }
  13670. thread_pool_start(&lb_thread_pool);
  13671. thread_pool_wait_to_process(&lb_thread_pool);
  13672. } else {
  13673. for_array(j, gen->modules.entries) {
  13674. lbModule *m = gen->modules.entries[j].value;
  13675. if (lb_is_module_empty(m)) {
  13676. continue;
  13677. }
  13678. String filepath_obj = lb_filepath_obj_for_module(m);
  13679. array_add(&gen->output_object_paths, filepath_obj);
  13680. String short_name = remove_directory_from_path(filepath_obj);
  13681. gbString section_name = gb_string_make(heap_allocator(), "LLVM Generate Object: ");
  13682. section_name = gb_string_append_length(section_name, short_name.text, short_name.len);
  13683. TIME_SECTION_WITH_LEN(section_name, gb_string_length(section_name));
  13684. if (LLVMTargetMachineEmitToFile(target_machines[j], m->mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  13685. gb_printf_err("LLVM Error: %s\n", llvm_error);
  13686. gb_exit(1);
  13687. return;
  13688. }
  13689. }
  13690. }
  13691. #undef TIME_SECTION
  13692. }